3

I'd like to know why the following function works:

function foo(list){
 var array = [];
 array.push(list);
 return array;
}
> foo([1,2,3])
[[1,2,3]]

while this one doesn't:

function foo(list){
 var array = [];
 return array.push(list);
}
> foo([1,2,3])
1 

What's the difference between them?

Marco Bonelli
70.7k21 gold badges129 silver badges152 bronze badges
asked Apr 7, 2015 at 1:30
2

1 Answer 1

10

If you look at the definition of the push method, it returns the length of the array after the push, not the array itself, that is why it is returning 1.

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

You are pushing an array with 3 elements to the new array, so in the new array you have an array as its content thus 1 is returned

answered Apr 7, 2015 at 1:32

1 Comment

Ouch...now I see it. Thank you :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.