# 14 useful javascript code snippets

Everyday development often uses some very simple and easy to use Javascript code, this article organized 14 code snippets, quickly bookmarked.

## init Array​

If you want to initialize a one-dimensional array of the specified length, specify the default value.

// default value is empty stringconst array = Array(6).fill("");// ['', '', '', '', '', '']

If you want to initialize a two-dimensional array of specified length and specify a default value, you can do this

const matrix = Array(6)  .fill(0)  .map(() => Array(5).fill(0));// [[0, 0, 0, 0, 0],//  [0, 0, 0, 0, 0],//  [0, 0, 0, 0, 0],//  [0, 0, 0, 0, 0],//  [0, 0, 0, 0, 0],//  [0, 0, 0, 0, 0]]

## Array summation, find the maximum, minimum value​

const array = [5, 4, 7, 8, 9, 2];

Array summation:

array.reduce((a, b) => a + b);

Array maximum:

array.reduce((a, b) => (a > b ? a : b));Math.max(...array);

Array minimum:

array.reduce((a, b) => (a < b ? a : b));Math.min(...array);
##### tip

Using the reduce method of arrays can solve many array evaluation problems.

## Filter empty value​

If you want to filter the values of false, 0, null, and undefined in an array, you can do this:

const array = [1, 0, undefined, 6, 7, "", false];array.filter(Boolean);// [1, 6, 7]

## Logical operator​

If you have a code that looks like this:

if (a > 10) {  doSomething(a);}

This can be overwritten using logical operators:

a > 10 && doSomething(a);

If the value of the && operator is false, it will short-circuit and terminate the execution of the statement. If true, the code after && continues and returns the return value of the code after it. Using this method can reduce a lot of if... The else.

## Judge to simplify​

If there is a judgment like this:

if (a === undefined || a === 10 || a === 15 || a === null) {  //...}

We can use arrays to simplify the logic:

if ([undefined, 10, 15, null].includes(a)) {  //...}

So it's a lot cleaner, and it's easy to expand, and if you still need to equal a, you just add it to the array.

## Empty array​

If you want to empty an array, you can set the length of the array to 0:

let array = ["A", "B", "C", "D", "E", "F"];array.length = 0;console.log(array); // []

## Calculate code performance​

You can use the following operations to calculate the performance of your code:

const startTime = performance.now();// some expensive codefor (let i = 0; i < 1000; i++) {  console.log(i);}const endTime = performance.now();const totaltime = endTime - startTime;console.log(totaltime); // 30.299999952316284

## Splice array​

If we want to concatenate several arrays, we can use the extension operator:

const start = [1, 2];const end = [5, 6, 7];const numbers = [9, ...start, ...end, 8]; // [9, 1, 2, 5, 6, 7 , 8]

Or use the concat() method of arrays:

const start = [1, 2, 3, 4];const end = [5, 6, 7];start.concat(end); // [1, 2, 3, 4, 5, 6, 7]

But with concat(), if the array to be merged is large, the concat() function consumes a lot of memory when creating a separate new array. You can use the following methods to merge arrays:

Array.prototype.push.apply(start, end);

This way you can use less memory to a large extent.

## Optional chaining​

If we have an object like this:

const parent = {  child: {    child1: {      child2: {        key: 10,      },    },  },};

Most of the time we will write this to avoid a level that does not exist to cause an error:

parent && parent.child && parent.child.child1 && parent.child.child1.child2;

This makes the code look bloated, using JavaScript's optional chain operator:

parent?.child?.child1?.child2;

This implementation and result is the same as the long list above.

The optional chain operator also works with arrays:

const array = [1, 2, 3];array?.;

The optional chain operator allows us to read the value of a property located deep in the chain of connected objects without explicitly verifying that each reference in the chain is valid. An error is not raised if the reference is null (or undefined), and the expression short-circuited returns undefined. When used with a function call, returns undefined if the given function does not exist.

## Validates undefined and NULL​

If you have code like this:

if (a === null || a === undefined) {  doSomething();}

If you need to verify that a value is equal to null or undefined, you can use the null value merge operator to simplify the above code:

a ?? doSomething();

Thus, the code following the control merge operator is executed only if a is undefined or null. Null-value merge operator (??) Is a logical operator that returns the right-hand operand if the left-hand operand is null or undefined, otherwise returns the left-hand operand.

## Array elements are converted to numbers​

If you have an array and want to convert the elements of the array to numbers, you can use the map method:

const array = ["12", "1", "3.1415", "-10.01"];array.map(Number); // [12, 1, 3.1415, -10.01]

In this way, the map executes the Number constructor on each element of the array as it iterates through the array and returns the result.

## Array-liked list to array​

covert arguments to array

Array.prototype.slice.call(arguments);

[...arguments];

## Check whether the object is empty​

If we want to check whether an object is empty, we can use the following method:

Object.keys({}).length; // 0Object.keys({ key: 1 }).length; // 1

The object.keys() method is used to get the keyof the object and returns an array containing these key values. If the length of the returned array is 0, the object must be empty.

## Gets the last item in the array​

If you want to get the last item in an array, you will often write:

const arr = [1, 2, 3, 4, 5];arr[arr.length - 1]; // 5

We can also use the array's slice method to retrieve the last element of the array:

arr.slice(-1);

When we set the slice method to a negative value, we truncate the array values from the back of the array. If we want to truncate the last two values, we pass the argument -2.