Yassine Badache Yassine Badache - 7 months ago 19
JSON Question

Json property of an undefined object not printing. Why?

I came around a simple behavior that I cannot quite understand. I am trying to check for the validity of a JSON array of objects, the core point here is that the user 'choses' its size (for example, if he types 2, there will be 2 objects).

Each object is supposed to have a name and a version.

I wanted to be sure that he enters something, so when he hits he submit button, I'm checking for this kind of statement:

if (myarray[0].name !== undefined || myarray.name !== null)
// Do some crazy stuff as crazy a return;

And I was not working. When I went to further inspection (console.log, wow), I noticed this:

console.log(myarray); // Prints '[]' because it is empty
console.log(myarray[0]); // Prints 'undefined', seems legit
console.log(myarray[0].name); // Prints ... Well, nothing

Why does the third
does not print
? Any property of an undefined object should be
, or is there something I am missing in JavaScript ?

Thank you in advance !


Why does the third console.log does not print undefined ?

Because it throws an exception: TypeError: Cannot read property 'name' of undefined. That happens when you try to read a property from undefined or null.