skip to Main Content

Here is the code:

let test = [];
test.someProp = "haha";
console.log(test); // result:  [ someProp: 'haha' ]
console.log(JSON.stringify(test)); // result: []
console.log(test.someProp); // result: haha
console.log(JSON.stringify(test)); // result: []

How console.log(test) returns an object and the line after it console.log(JSON.stringify(test)) returns an empty array ?

3

Answers


  1. let test = [];
    test.someProp = "haha";
    console.log(test); // result: []
    console.log(JSON.stringify(test)); // result: []
    console.log(test.someProp); // result: haha
    console.log(JSON.stringify(test)); // result: []

    The reason you can see someProp: ‘haha’ is because the console interprets the object differently on different dev tools. On the SO snippet tool, as you can see, the result is []. Here is why:

    Arrays in JS are objects with numeric keys. Because they are objects, they can have properties like your someProp. This doesn’t add an element to the array (which would require a numeric index). That is why you might see [someProp: ‘haha’]. Some consoles use the names of the props and values to print the object to help devs with debugging. When you log test.someProp, it accesses only the property you asked for as a value.

    When you JSON.stringify, it converts only the array elements into the JSON string because you called it on the array. That is why you once more see [].

    Login or Signup to reply.
  2. In brief, this quote from MDN should shed some light on this:

    In JavaScript, arrays aren’t primitives but are instead Array objects

    The Array is still an Array. It is also, and always was, an Object too. How a given type of Object is converted to JSON will usually depend on the toJSON() method of its prototype, though in the case of Array (being a built in type) it is treated as a special case and has a default implementation which doesn’t, for example, output the length property of Array in the stringified output but rather the [...] format you see.

    Login or Signup to reply.
  3. As @jonrsharpe pointed out, JSON can’t represent an array with extra properties.

    However, if you need to translate such an array into JSON and back, you can do it like this:

    let test = [4,5,6]
    
    test.someProp = 'haha'
    
    let json = JSON.stringify(Object.assign({}, test))
    
    console.log(json)
    
    let test2 = Object.assign([], JSON.parse(json))
    
    console.log(test2)
    
    console.log(test2.someProp)
    
    console.log(Array.isArray(test2))
    
    console.log(test2.length)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search