0

I am trying to check if a variable is defined or not using the below:

if(variable.obj[0] === undefined){
 console.log("yes it's undefined !")
}

and also tried :

if ("undefined" === typeof variable.obj[0]) {
  console.log("variable is undefined");
}

However it throws on the console:

Uncaught TypeError: Cannot read property '0' of undefined
at <anonymous>:1:16
Folky.H
  • 1,164
  • 4
  • 15
  • 37
  • It means that `variable.obj` is undefined. – PeterMader Jun 01 '17 at 14:10
  • 3
    Possible duplicate of [How to check for "undefined" in JavaScript?](https://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript) – Samvel Petrosov Jun 01 '17 at 14:11
  • For my suggestion simple `if(var)` is enought to validate `null,undefined,empty,Nan` => `if(variable.obj[0])` – prasanth Jun 01 '17 at 14:12
  • Hi @Folky.H! If one of the answers has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Bruno Peres May 10 '18 at 20:13

3 Answers3

1

You need to check the containing objects first, before you can access a property or array index.

if (variable === undefined || variable.obj === undefined || variable.obj[0] == undefined) {
    console.log("yes it's undefined !")
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

The obj property is undefined. First, you need check variable and the obj property. After it you can access and check if variable.obj[0] is undefined.

Try:

if (variable && variable.obj && typeof variable.obj[0] === 'undefined'){
    console.log("yes it's undefined !")
}
Bruno Peres
  • 15,845
  • 5
  • 53
  • 89
0

typeof does not check for existance of "parent" objects. You have to check all parts that might not exist.

Assuming variable.obj is an object you will need this code:

if (typeof variable === "object" && typeof variable.obj === "object" && variable.obj.hasOwnProperty("0"))

If it is an array then

if (typeof variable === "object" && typeof variable.obj === "object" && variable.obj.length > 0)
Viacheslav
  • 84
  • 1
  • 5