Tips for arrays in JavaScript

Tram Ho

Array is a data structure used a lot in programming languages ​​and in Javascript is no exception. With the new features introduced in ES6, ES7 makes Javascript even more interesting. In this article, I would like to share the ways / tips used with the array that I have collected.

1. Pass a blank parameter to a function

If you want to execute a function and don’t pass any parameters even though the function has already been defined, then JS will throw an error. For example:

The most common solution people use is to pass null or undefined

But passing null or undefined only solves the problem right now, although it still works, but really if so many parameters make our code redundant and unprofessional. To solve this we can use the spread operators introduced in ES6. Given the properties of the array, we can have an empty element and we can pass that array into the function call.

method(...['parameter1', , 'parameter3']);

2. Create unique values ​​in the array

By using the spread operator and Set we can create an array of values ​​with different values.

3. Map with Array.from ()

Array.from() is an alternative to the map function in some cases. For example, when using the document.querySelectorAll() function, the result is Object Like-array, so in order to use the map function, we have to convert it to array. With array.from () we can always make that move.

4. Delete the element in the array

To reduce the size of the array or delete n elements in the array, we can use array.length

5. Get the last element in the array

Array.prototype.slice(begin, end) is used to trim elements in the array when you pass parameters begin and end , otherwise the transmission end , it will automatically set the value of length of the array. Because begin can receive negative values, we can get the last element of the array.

Thank you for taking the time to read the article.

Source: Collector

Share the news now

Source : Viblo