Shift Array Element To Right
Basic Syntax of Array Unshift and Pop
let array = [1, 2, 3, 4];
In the next step, we use two array methods which are the unshift and pop method.
Now, we check the length of the array and element inside the array element using console log.
So, any idea what should be output of above code statement.
let array = [1, 2, 3, 4]; array.unshift(array.pop()); console.log(array.length); // output => 🧐 ? console.log(array); // output => 🧐 ? // Made with ❤️, by @jsstartup
Now, you know the answer is 4, [4, 1, 2, 3]. But why doesn’t pop remove the element and unshift need an element to add in the array? Let me explain
First we use a array pop method which remove the last array element but in return it gives the remove element which means array pop return 4.
let array = [1, 2, 3, 4]; array.pop(); // 4 console.log(array); // [1, 2, 3]
But as we pass the array pop method in unshift method so value 4 added to array at start.
array.unshift(4); console.log(array.length); // 4 console.log(array); // [4, 1, 2, 3]
At last, That’s why we get an answer “4, [4, 1, 2, 3]“.
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 – effect of misplaced semicolon after if statement
- JS Quiz – what does triple value compare 10 > 9 > 8 return
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.