The best way is to check the type, because undefined
/null
/false
are a tricky thing in JS.
So:
if(typeof obj !== "undefined") {
// obj is a valid variable, do something here.
}
Note that typeof
always returns a string, and doesn’t generate an error if the variable doesn’t exist at all.
More Related Contents:
- Detecting an undefined object property
- What is the difference between null and undefined in JavaScript?
- Why is null an object and what’s the difference between null and undefined?
- How can I unset a JavaScript variable?
- How to check a not-defined variable in JavaScript
- variable === undefined vs. typeof variable === “undefined”
- How to check for an undefined or null variable in JavaScript?
- JavaScript checking for null vs. undefined and difference between == and ===
- Why does this JavaScript code print “undefined” on the console?
- forEach on array of undefined created by Array constructor
- JavaScript “cannot read property “bar” of undefined [duplicate]
- Why is there a `null` value in JavaScript?
- How dangerous is it in JavaScript, really, to assume undefined is not overwritten?
- node.js displays “undefined” on the console
- this is undefined inside arrow function
- What reason is there to use null instead of undefined in JavaScript?
- JavaScript String concatenation behavior with null or undefined values
- When is null or undefined used in JavaScript? [duplicate]
- Javascript – removing undefined fields from an object [duplicate]
- Undefined return value from the function call Javascritpt
- console.log(myFunction()) returns undefined
- JS checking deep object property existence [duplicate]
- What’s the difference between empty items in a JavaScript array and undefined? [duplicate]
- Is it better to return `undefined` or `null` from a javascript function? [closed]
- Can I set variables to undefined or pass undefined as an argument?
- Should JSON include null values [closed]
- Count of “Defined” Array Elements
- Why is my JavaScript hoisted local variable returning undefined but the hoisted global variable is returning blank? [duplicate]
- Test if something is not undefined in JavaScript
- JSLint: was used before it was defined