Guangzhou Lanjing Sharing—13 Basic JavaScript Functions Every Web Developer Knows

insert image description here

Dear programming enthusiasts, today Xiaolan will share with you 13 basic JavaScript functions. If you are a web front-end developer, you should be familiar with these functions.

You can add all of the JavaScript functions in this article to your toolbox so that you can use these snippets as much as possible in your software projects.

1. Retrieve the first/last item in any JavaScript array

Normally, if using JavaScript, I need the first element of the array. For usability, I created a simple head function that I can use for arrays and will return the first item.

As a bonus, I added the JavaScript last function, which retrieves the last item from the array.

const head = (arr) => arr[0];

const last = (arr) => arr[arr.length - 1];

head([1, 2, 3, 4, 5, 6, 7, 8]); // 1

last([1, 2, 3, 4, 5, 6, 7, 8]); // 8

2. The comma operator in JavaScript

The comma operator in JavaScript can be complicated at first.

But, actually, it's really easy!

For example, using [x,y] always returns the correct operand. See the following JavaScript snippet for a better understanding:

console.log([1, 2, 3, 4][1]); // 2

console.log([1, 2, 3, 4][(1, 2)]); // 3

console.log([1, 2, 3, 4][2]); // 3

3. Copy anything to the clipboard

When developing a website, you sometimes want to copy specific content to the clipboard to improve usability.

In JavaScript, this can be done by using the document directly (the old method) or using the Navigator component (the new method).

function copyToClipboard() {

const copyText = document.getElementById('myInput');

copyText.select();

document.execCommand('copy');

}

// new API

function copyToClipboard() {

navigator.clipboard.writeText(document.querySelector('#myInput').value);

}

4. Nested Destructuring in JavaScript

Destructuring is an important JavaScript topic and has been shared in detail before.

But today this code snippet shows simple object reorganization, extracting only two variables from the object.

const user = {

id: 459,

name: 'Paul Knulst',

age: 29,

job: {

role: 'Tech Lead',

},

};

const {

name,

job: { role },

} = user;

console.log(name); // Paul Knulst

console.log(role); // Tech Lead

5. Add globally available functions to any object

In JavaScript, any object can be extended with new methods.

The following JavaScript snippet shows how to add the toUpperCase function to an array.

Array.prototype.toUpperCase = function () {

let i;

for (let i = 0; i < this.length; i++) {

this[i] = this[i].toUpperCase();

}

return this;

};

const myArray = ['paul', 'knulst', 'medium'];

console.log(myArray); // ['paul', 'knulst', 'medium']

console.log(myArray.toUpperCase()); // ['PAUL', 'KNULST', 'MEDIUM']

This concept is called prototypal inheritance and is covered in detail in this article.

6. Natively convert an array to an object in JavaScript

JavaScript has a native function Object.fromEntries that can be used to convert any input array to an object.

const anArray = [

['firstname', 'Paul'],

['surname', 'Knulst'],

['address', 'worldwide'],

['role', 'Senior Engineer'],

['followers', 'not much'],

];

const anObj = Object.fromEntries(anArray);

console.log(anObj);

// {
    
    

// firstname: 'Paul',

// surname: 'Knulst',

// address: 'worldwide',

// role: 'Senior Engineer',

// followers: 'not much'

// }

7. Recursively get the Fibonacci of a number

Recursion is a concept every software developer must know!

This JavaScript snippet shows the Fibonacci function implemented recursively.

const getFibonacci = (n, memo = {
    
    }) =>

memo[n] ||

(n <= 2

? 1

: (memo[n] = getFibonacci(n - 1, memo) + getFibonacci(n - 2, memo)));

console.log(getFibonacci(4)); // 3

console.log(getFibonacci(8)); // 21

8. Check if your date is on the weekend

This JavaScript snippet shows how easy it is to check whether each Date object is a weekend.

You can change the week number (6 and 0) and replace it with any other weekday number to check for different days.

const isWeekend = (date) => date.getDay() === 6 || date.getDay() === 0;

console.log(isWeekend(new Date())); // false

console.log(isWeekend(new Date('2022-10-28'))); // false

console.log(isWeekend(new Date('2022-10-29'))); // true

9. Convert 24-hour time format to am/pm

Working with different time formats is a pain.

This simple JavaScript snippet shows a function that converts any 24-hour time to am/pm time.

const toAMPMFormat = (h) =>

`${
    
    h % 12 === 0 ? 12 : h % 12}${
    
    h < 12 ? ' am.' : ' pm.'}`;

console.log(toAMPMFormat(12)); // 12 pm.

console.log(toAMPMFormat(21)); // 9 pm.

console.log(toAMPMFormat(8)); // 8 am.

console.log(toAMPMFormat(16)); // 4 pm

10. Check if a property exists in an object

Sometimes you want to check whether attributes exist before printing or using them.

Instead of doing if property !== undefined before using it, JavaScript has a built-in function to do it.

const developer = {
    
    

name: 'Paul Knulst',

role: 'Tech Lead',

extra: 'Loves DevOps',

company: 'Realcore',

os: 'Windows',

};

const laptop = {
    
    

os: 'Windows',

buydate: '27.10.2022',

extra: 'looks cool',

};

console.log('name' in developer); // true

console.log('extra' in developer); // true

console.log('name' in laptop); // false

console.log('extra' in laptop); // true

Combined with the nullish coalescing operator, it can make your JavaScript code cleaner!

11. Check if the array contains the same value

In some cases, you need to know whether two arrays contain the same value.

This JavaScript snippet contains a function containSameValues ​​that does this by sorting and concatenating two arrays and comparing their strings.

const containSameValues = (arr1, arr2) =>

arr1.sort().join(',') === arr2.sort().join(',');

console.log(containSameValues([1, 2, 3], [1, 2, 3])); // true

console.log(containSameValues([1, 2, 3], [2, 3, 4])); // false

console.log(containSameValues([1, 2, 3], [1, 2, 3, 4])); // false

Remember that arrays must be sortable to actually compare them correctly!

12. Make sure variables are in scope

This JavaScript function works great for me!

It checks to see if the variable is within a certain range, and if not, it will clamp it to the nearest minimum or maximum value.

const clamp = (min, max, value) => {
    
    

if (min > max) {
    
    

throw new Error('min cannot be greater than max');

}

return value < min ? min : value > max ? max : value;

};

clamp(0, 6, -5); // 0

clamp(0, 6, 20); // 6

clamp(0, 6, 3); // 3

13. Swap two variables in one line

It's not a JavaScript function, but it's a really cool way to swap two variables.

It shows how to do it in one line, instead of putting the value into a "temporary" object (which has to be done in some other programming languages)

let x = 50;

let y = 100;

console.log(x, y); //50 100

[y, x] = [x, y];

console.log(x, y); //100 50

conclusion

The above is the content shared today. If you have good JavaScript snippets in your study or work, you can comment and learn together.

Guess you like

Origin blog.csdn.net/qq_43230405/article/details/130088460