0

If I do

var a = [].push(undefined);
console.log(a);

it gives output as 1 even though undefined was pushed to the array. Any idea why?

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • 2
    `var a=[];a.push(undefined);console.log(a)` – Jeon Oct 14 '16 at 06:00
  • 2
    _The push() method adds one or more elements to the end of an array and returns the new length of the array._ `undefined` is a valid array element: `[ undefined ].length === 1`. RTFM? – Oka Oct 14 '16 at 06:01
  • 1
    See `Return value` at JavaScript Array push() Method http://www.w3schools.com/jsref/jsref_push.asp – Jeon Oct 14 '16 at 06:01
  • It will be the same if you push `null` too – David R Oct 14 '16 at 06:02

4 Answers4

3

You're testing it the wrong way. a is not defined as the array, as I think you suppose it to be. Try this:

var a = []
a.push(undefined);
console.log(a);

You are assigning the return value of push function to variable a. push returns the length of the array after pushing the current element in context. So, it returns 1 after pushing undefined in the array.

Mohit Bhardwaj
  • 9,650
  • 3
  • 37
  • 64
3

its pushing the length of array inside not the elements

example

var a = [].push(5,6,7,8);
  console.log(a); //gives 4
Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
nivendha
  • 792
  • 7
  • 16
1

Push returns the new length of the array, and thats what is stored in a

BobbyTables
  • 4,481
  • 1
  • 31
  • 39
1

There was no explicit check has been done when assigning a new property to array object. Assigning a new property in the sense, setting 0,1,2..n properties with values, based on the length of the array.

  1. Repeat, while items is not empty
    • Remove the first element from items and let E be the value of the element.
    • Let setStatus be Set(O, ToString(len), E, true).
    • ReturnIfAbrupt(setStatus).
    • Let len be len+1.

You can see it here. Step 8.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • 1
    Thanks for the detailed analysis +1 for that. – gurvinder372 Oct 14 '16 at 06:17
  • This doesn't seem to answer the question, because it doesn't mention the return value from the `.push()` method. – nnnnnn Oct 14 '16 at 06:32
  • @nnnnnn OP seems to be having knowledge in why push returns 1. I personally assumed it by seeing his reps. But `it gives output as 1 even though undefined was pushed to the array.` this sentence in his question made me to think he wants to know why undefined is getting pushed into the array. – Rajaprabhu Aravindasamy Oct 14 '16 at 06:39
  • 1
    Oh right. I see what you mean, although I think you made that distinction clearly in your comment but not in the answer. (Although if "undefined **was** pushed" then that means that undefined *is* in the array...) – nnnnnn Oct 14 '16 at 06:42