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
4
  • It means that variable.obj is undefined. Commented Jun 1, 2017 at 14:10
  • 3
    Possible duplicate of How to check for "undefined" in JavaScript? Commented Jun 1, 2017 at 14:11
  • For my suggestion simple if(var) is enought to validate null,undefined,empty,Nan => if(variable.obj[0]) Commented Jun 1, 2017 at 14:12
  • Hi @Folky.H! If one of the answers has solved your question please consider accepting it 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. Commented May 10, 2018 at 20:13

3 Answers 3

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 !")
}
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

This will say that the variable is defined even if variable.obj is not defined.
It will also get an error if variable is undefined.
@Emissary Sorry :) I changed || to &&.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.