1

I created two different variables a and b and in first for loop, I placed a.push and then a.unshift and in second for loop, I placed b.unshift first and then b.push but why the both variables (a and b) output will be same as [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

let a =  [];
for(let i=0 ; i <=10 ; i++) {
    a.push(i); 
    a.unshift(i);
}
console.log(a); 

let b =  [];
for(let j=0 ; j <=10 ; j++) {
    b.unshift(j); 
    b.push(j); 
}
console.log(b); 
4
  • What difference were you expecting? Commented Apr 15, 2020 at 19:18
  • I think in the first case the result would be [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 1, 2,3, 4, 5, 6, 7, 8, 9, 10] and in the second case the result would be [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ] Commented Apr 15, 2020 at 19:44
  • Switching the order of 'push' and 'unshift' has no effect. Unshift adds the item to front of the array, and unshift, to the back, so in both cases you're building the array "from the middle out". To get '[0, 1, 2...", you would change your for loop to 'for (let j=10; j >=0; j--'. Commented Apr 15, 2020 at 19:47
  • ya, its working thanks @zanerock Commented Apr 15, 2020 at 19:52

1 Answer 1

1

The push() method adds one or more elements to the end of an array and returns the new length of the array.

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

First one always works on the end, second one on the beginning. So it doesn't matter if you call first unshift() or push() because they do the same action every time. It's like adding. It doesn't matter if you do 3 + 5 or 5 + 3. Theoretically, it do the same in the opposite order, but because it uses the same value the result is the same.

Try

let a =  [];
for(let i=0 ; i <=10 ; i++) {
    a.push(i + 1); 
    a.unshift(i);
}
console.log(a); 

let b =  [];
for(let j=0 ; j <=10 ; j++) {
    b.unshift(j + 1); 
    b.push(j); 
}
console.log(b); 

The result is different.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.