Folky.H
Folky.H

Reputation: 1204

JavaScript - Can't check if variable is undefined

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

Upvotes: 0

Views: 2376

Answers (3)

Bruno Peres
Bruno Peres

Reputation: 16365

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 !")
}

Upvotes: 0

Viacheslav
Viacheslav

Reputation: 84

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)

Upvotes: 0

Barmar
Barmar

Reputation: 780974

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 !")
}

Upvotes: 1

Related Questions