Example of Array Index Value –
const array = [1, "JS", true]; console.log(array); // Here, 2 is an index // => "JS"
Array push method
For Example –
const array = [1, 2]; array.push(3); // => [1, 2, 3]
Array unshift method
For example –
const array = [1, 2]; array.unshift(0); // => [0, 1, 2]
const array = [10, 15, 20];
In the second step, value of 25 assign to array at index 5.
array = 25;
Now, we use the array push method and pass 30 value to it and also use another array method unshift and 35 value pass to it.
Finally, we are checking the value of array at index 5 using console log.
const array = [10, 15, 20]; array = 25; array.push(30); array.unshift(35); console.log(array); // output => ?
Any idea what should the output above code snippet ?
Now, you know the answer is “undefined” But why we haven’t added undefined value to an array and even if add 25 value to an array at index 5. Let me explain
So, as you are correct the value at index is 25. But when we also push the 30 to array. But it didn’t change the position of 25. As 30 added at the bottom of array.
But when we use the unshift method with value 35. This value-added at top of the array. And when we assign 25 to index 5 then automatically at index 3 & 4 undefined is assigned.
So, the value array look process like –
const array = [10, 15, 20]; // => [10, 15, 20] array = 25; // => [10, 15, 20, undefined, undefined, 25] array.push(30); // => [10, 15, 20, undefined, undefined, 25, 30] array.unshift(35); // => [30, 10, 15, 20, undefined, undefined, 25, 30] console.log(array); // output => undefined
At last, That’s why we get an answer “undefined“.
Let me know in the comment section, what you think about it.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – zero date can give get full year method
- JS Quiz – does set object really store duplicate object
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.