Rafael Adel
Rafael Adel

Reputation: 7759

About pop() and push() in Javascript

I'm really a beginner in Javascript, and trying what i read as much as I can.

But when comes to pop() and push(), I get some strange results that I'm wondering about.

Here's the code :

var arr = [];
arr.push(2,3);
console.log(arr);

console.log(arr.pop());
console.log(arr);

the result is :

[2, undefined × 1]

3

[2]

Shouldn't it be :

[2, 3]

3

[2]

Upvotes: 2

Views: 2335

Answers (2)

Joseph
Joseph

Reputation: 119837

You'd have to note that the console handles objects as "live". Any object (arrays, objects etc.) you already outputted on the console is still subject to operations.

That's why when you expected [2,3] on the first log, the code already popped the 3, thus replaced undefined on 3's spot.

Of course, this event depends on how the browser implement's their console.

Upvotes: 4

user1479055
user1479055

Reputation:

This is due to console.log's asynchronous evaluation on your browser. By the time the result of the first console.log has been displayed, the item is already gone because of pop().

For accurate results, call toString():

var arr = [];
arr.push(2,3);
console.log(arr.toString()); // 2,3 - as expected.

console.log(arr.pop());
console.log(arr);

Upvotes: 5

Related Questions