0

So i am trying to dig into a lot more Vanilla JS and i set up an object and an empty array and i pushed the object inside the array but when i console.log my array it returns the length only. What am i doing wrong or how can i see what is inside the array?

This is my sample code

let empty = []

let exp = {
  2: 'Hey',
  28: 'Yo',
  9: 'Heyyyy!!',
  6: 'Foo'
}

let newValue = empty.push(exp)
console.log(newValue)

Now if i do not use the newValue but do this instead it seems to work:-

let empty = []

let exp = {
   2: 'Hey',
   28: 'Yo',
   9: 'Heyyyy!!',
   6: 'Foo'
}

empty.push(exp)
console.log(empty)

Why does console.log(newValue) does not return the array and the object stored inside it? i thought that i should be able to assign values to a new variable. If someone can clear it, i sure will appreciate it.

3 Answers 3

2

push method add the value to array we are operating on and returns the new length of array.

let newValue = empty.push(exp) 

is same as.

let newValue = empty.length ( length after pushing value )

second snippets shows the array as you're logging the actual array where as in first snippet newValue is same as length of array.

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

1 Comment

ohh!!! Thanks for clearing it up!! It makes sense now!! Accepting the answer. :)
1

You are logging the return value of push, which is the length. Check the docs for more information.

Comments

0

You could use the spread syntax in order to achieve a similar result to what you've attempted:

let empty = [];

let exp = {
  2: "Hey",
  28: "Yo",
  9: "Heyyyy!!",
  6: "Foo",
};

let newValue = [...empty, exp];
console.log(newValue);

Comments

Your Answer

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