- Array Destructuring
Array destructuring allows us to assign values to variables from an array using syntax similar to the array itself. Let’s look at the code below where we have an array of animals. We need to assign variables a, b & c to first three elements of the array.
Now here we needed 3 statements just to assign 3 variables a, b & c. If we had like 10 variables, we would need 10 such statements. This approach definitely doesn’t scale efficiently. To cater to this problem, ES2015 introduced the concept to array destructuring. So instead of assigning each variable in a new line, we assign all local variables in single line of code within square brackets. For example:
[ variable1, variable2, ..., variableN ] = array;
We can reduce the number of lines even further by declaring the variables at the time of assignment itself.
So in the above example, we didn’t want to access the 2nd element of the array, so we left it’s placeholder in the array as blank and still got the correct values in variables a and b i.e. a = ‘Dog’ and b = ‘Rat’. ‘Cat’ was discarded.
Now next time you need to swap two variables say a and b, do the following and you’ll be done in a single line.
- For-of Loop:
ES2015 introduced a new loop to iterate over array elements. Firstly let’s see the current approach we follow when we need to access (print in our example) all elements in an array. We currently use any of the below three approaches.
The problem with the 1st& 2nd approach is that we need to iteratively update the value of index and then use that index value to access the element in the array. This is useless extra effort. 3rd< approach is free from this problem, but it has another problem. What if we don’t want to execute function over all elements of the array? What if we want to break out of the loop on some condition? We cannot do that in the 3 approach.
So with the use of ‘for-of’ loop, we can directly access the element inside the loop as shown in below example
We don’t need any extra effort of assigning the index variable each time. Now we can directly access the individual element of the array
About the author:
“Harshit is a technology enthusiast and has keen interest in programming. He holds a B.Tech. degree in Computer Science from JIIT, Noida and currently works as Front-end Developer at SAP. He is also a state level table tennis player. Apart from this he likes to unwind by watching movies and English sitcoms. He is based out of Delhi and you can reach out to him at https://in.linkedin.com/pub/harshit-jain/2a/129/bb5
If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.