0

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 console.log does not print undefined ? Any property of an undefined object should be undefined, or is there something I am missing in JavaScript ?

Thank you in advance !

Yassine Badache
  • 1,810
  • 1
  • 19
  • 38
  • JSON is a *textual notation* for data exchange. [(More)](http://stackoverflow.com/a/2904181/157247) If you're working in JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Jul 27 '16 at 07:40

1 Answers1

3

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875