0

I'm trying to check if a node exists in an array but can't seem to get my if statement correct.

I've currently got :

if (obj2["spec"]["3"]["spec2"]["14"] != null) { do stuff }

In some cases [14] wont exist as the array length is only 5 or 6, so want to make sure it doesn't try to do anything if [14] doesn't have any items in it.

Oriol
  • 274,082
  • 63
  • 437
  • 513
NewToCode
  • 61
  • 6

2 Answers2

-2

You snippet is correct, when a node doesn't exist, is undefined, but in no-strict comparation, undefined == null. If a node doesn't exist, will show a error. if you use typeof, this will cover if all nodes is valid.

Example

// ["spec2"] is undefined, this case will show a error.
if(array["spec"]["3"]["spec2"]["14"] != undefined) { 

}

// This doesn't he show error, if "specs2" is undefined.
if(typeof array["spec"]["3"]["spec2"]["14"] !== "undefined") { 

}
Rafael Dantas
  • 599
  • 5
  • 11
-2

If the array length is only 5 or 6, then it means element 14 won't even exist, you should be checking for undefined not null:

if(typeof array["spec"]["3"]["spec2"]["14"] !== "undefined")

or:

if(array["spec"]["3"]["spec2"]["14"] !== undefined)

or even:

if(!array["spec"]["3"]["spec2"]["14"])

I would recommend an option but it really comes down to preference and I'd rather not incite a style/best practice war :) Just pick whichever you prefer.

Here's a thorough explanation on the difference between null and undefined, but essentially null means the value is null, whereas undefined means the variable has not been declared.

Community
  • 1
  • 1
Pabs123
  • 3,385
  • 13
  • 29
  • Or even `!= null`, which is what OP is doing. What does your answer attempt to fix? – Oriol Dec 22 '16 at 17:00
  • `!= null` is wrong. If you try to access an element in an array which has not been defined yet, it will be undefined not null. try defining an empty array and checking if `arr['something'] == null`, you'll see it returns false – Pabs123 Dec 22 '16 at 17:02
  • But `undefined == null`. It's an abstract comparison, not strict. – Oriol Dec 22 '16 at 17:02