10 JavaScript code snippets

10 JavaScript code snippets
There is no doubt that JavaScript is one of the most popular programming languages ​​in web development. Whether you are using React, Vue or Angular, they are all JavaScript. JS revolves around the development of a vast and vital ecosystem, and provides many frameworks and libraries to help you develop applications quickly.
But sometimes it is better to take a step back and try to understand how to operate without a library. Take a look at the following code snippets, they solve simple problems in an elegant manner, and use this knowledge in daily project situations to improve the efficiency of writing code.

1. Reverse the string

In this example, we used the scatter operator (...), the reverse method of Array and the join method of String to reverse the given string.

2. Calculate the factorial of numbers

To calculate the factorial of a given number, we use arrow functions and nested ternary operators.

3. Convert numbers to arrays of numbers

In this example, we used the scatter operator (...), Array's map method, and the parseInt function that converts the given number into a singular array.

4. Check if the number is a power of 2

this is very simple. We check that this number is not false and use the bitwise AND operator (&) to determine whether number is a power of 2.

5. Create an array of key-value pairs from the object

In this example, we use the keys method in Object and the map method in Array to map the keys of Object and create an array of key-value pairs.

6. Return [Number] of the largest elements from the array

In order to return the largest element from the array, we use an arrow function that gets the number of elements in the array and the function we want to return. We used the scatter operator (...) and the sort and slice methods in Array. Note that if the second parameter is not provided, the default value for number is 1, so only one largest element is returned.

7. Check if all elements in the array are equal

In this short example, we use the every method in Array to check whether all elements in the array are equal. We basically check if each element is equal to the first element in the array.

8. Return the average of two numbers

In this example, we used the spread operator (...) and the reduce method in Array to return the average of two given numbers or an array.

9. Return the sum of two or more numbers

To return the sum of two or more given numbers or an array, we again use the scatter operator (...) and the reduce method in Array.

10. Return the power set of an array of numbers

In the last example, we want to return the power set of an array of numbers. Therefore, we use the reduce, map and concat methods in Array.

Guess you like

Origin www.cnblogs.com/xiewangfei123/p/12717316.html