In JavaScript, null is an object. There's another value for things that don't exist, undefined. The DOM returns null for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined is the value used.

Second, no, there is not a direct equivalent. If you really want to check for specifically for null, do:

if (yourvar === null) // Does not execute if yourvar is `undefined`

If you want to check if a variable exists, that can only be done with try/catch, since typeof will treat an undeclared variable and a variable declared with the value of undefined as equivalent.

But, to check if a variable is declared and is not undefined:

if (yourvar !== undefined) // Any scope

Previously, it was necessary to use the typeof operator to check for undefined safely, because it was possible to reassign undefined just like a variable. The old way looked like this:

if (typeof yourvar !== 'undefined') // Any scope

The issue of undefined being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use === and !== to test for undefined without using typeof as undefined has been read-only for some time.

If you want to know if a member exists independent but don't care what its value is:

if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance

If you want to to know whether a variable is truthy:

if (yourvar)

Source

Answer from Natrium on Stack Overflow
Top answer
1 of 15
1875

In JavaScript, null is an object. There's another value for things that don't exist, undefined. The DOM returns null for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined is the value used.

Second, no, there is not a direct equivalent. If you really want to check for specifically for null, do:

if (yourvar === null) // Does not execute if yourvar is `undefined`

If you want to check if a variable exists, that can only be done with try/catch, since typeof will treat an undeclared variable and a variable declared with the value of undefined as equivalent.

But, to check if a variable is declared and is not undefined:

if (yourvar !== undefined) // Any scope

Previously, it was necessary to use the typeof operator to check for undefined safely, because it was possible to reassign undefined just like a variable. The old way looked like this:

if (typeof yourvar !== 'undefined') // Any scope

The issue of undefined being re-assignable was fixed in ECMAScript 5, which was released in 2009. You can now safely use === and !== to test for undefined without using typeof as undefined has been read-only for some time.

If you want to know if a member exists independent but don't care what its value is:

if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance

If you want to to know whether a variable is truthy:

if (yourvar)

Source

2 of 15
405

The only way to truly test if a variable is undefined is to do the following. Remember, undefined is an object in JavaScript.

if (typeof someVar === 'undefined') {
  // Your variable is undefined
}

Some of the other solutions in this thread will lead you to believe a variable is undefined even though it has been defined (with a value of NULL or 0, for instance).

๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ javascript-check-if-undefined-how-to-test-for-undefined-in-js
JavaScript Check if Undefined โ€“ How to Test for Undefined in JS
November 7, 2024 - In this article, you will learn ... in JavaScript. This is necessary if you want to avoid your code throwing errors when performing an operation with an undefined variable. In case you are in a rush, here are the three standard methods that can help you check if a variable ...
๐ŸŒ
ui.dev
ui.dev โ€บ check-for-undefined-javascript
How to check for undefined in JavaScript
The way I recommend to check for undefined in JavaScript is using the strict equality operator, ===, and comparing it to the primitive undefined. ... Checking for `undefined`` this way will work in every use case except for one, if the variable ...
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ undefined
undefined - JavaScript | MDN
It is one of JavaScript's primitive types. function test(t) { if (t === undefined) { return "Undefined value!"; } return t; } let x; console.log(test(x)); // Expected output: "Undefined value!" The primitive value undefined. undefined is a property of the global object.
๐ŸŒ
BrowserStack
browserstack.com โ€บ home โ€บ guide โ€บ how to check if a variable is undefined in javascript
How to Check if a Variable is Undefined in JavaScript | BrowserStack
February 18, 2025 - In JavaScript, undefined is the default value for variables that have been declared but not initialized. On the other hand, null is an intentional assignment that explicitly indicates the absence of a value. ... This article covers different ways to check if a variable is undefined, helping you write code that handles these situations smoothly.
๐ŸŒ
Codedamn
codedamn.com โ€บ news โ€บ javascript
How to check if value is undefined or null in JavaScript
June 8, 2023 - If you want to check if a value is specifically undefined or null without type coercion, you can use the identity operator (===). The identity operator checks for both value and type equality, which means it does not perform type coercion.
๐ŸŒ
Tutorial Republic
tutorialrepublic.com โ€บ faq โ€บ how-to-determine-if-variable-is-undefined-or-null-in-javascript.php
How to Determine If Variable is Undefined or NULL in JavaScript
Note: The undefined is not a reserved ... test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined')....
Find elsewhere
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ javascript-check-if-variable-is-a-undefined-or-null
JavaScript: Check if Variable is undefined or null
March 29, 2023 - If you're using a non-existent reference variable - silently ignoring that issue by using typeof might lead to silent failure down the line. The typeof operator can additionally be used alongside the === operator to check if the type of a variable is equal to 'undefined' or 'null':
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ javascript โ€บ how can i check for "undefined" in javascript?
How can I Check for "undefined" in JavaScript? | Sentry
You can use the strict equality operator (===) to check if a value is undefined: ... An interesting thing to note is that undefined is not a reserved word in JavaScript. A reserved word is a keyword that canโ€™t be used as an identifier for ...
Top answer
1 of 16
3234

If you are interested in finding out whether a variable has been declared regardless of its value, then using the in operator is the safest way to go. Consider this example:

// global scope
var theFu; // theFu has been declared, but its value is undefined
typeof theFu; // "undefined"

But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in operator for a more robust check.

"theFu" in window; // true
"theFoo" in window; // false

If you are interested in knowing whether the variable hasn't been declared or has the value undefined, then use the typeof operator, which is guaranteed to return a string:

if (typeof myVar !== 'undefined')

Direct comparisons against undefined are troublesome as undefined can be overwritten.

window.undefined = "foo";
"foo" == undefined // true

As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.

if (window.myVar) will also include these falsy values, so it's not very robust:

false
0
""
NaN
null
undefined

Thanks to @CMS for pointing out that your third case - if (myVariable) can also throw an error in two cases. The first is when the variable hasn't been defined which throws a ReferenceError.

// abc was never declared.
if (abc) {
    // ReferenceError: abc is not defined
} 

The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,

// or it's a property that can throw an error
Object.defineProperty(window, "myVariable", { 
    get: function() { throw new Error("W00t?"); }, 
    set: undefined 
});
if (myVariable) {
    // Error: W00t?
}
2 of 16
1586

I personally use

myVar === undefined

Warning: Please note that === is used over == and that myVar has been previously declared (not defined).


I do not like typeof myVar === "undefined". I think it is long winded and unnecessary. (I can get the same done in less code.)

Now some people will keel over in pain when they read this, screaming: "Wait! WAAITTT!!! undefined can be redefined!"

Cool. I know this. Then again, most variables in Javascript can be redefined. Should you never use any built-in identifier that can be redefined?

If you follow this rule, good for you: you aren't a hypocrite.

The thing is, in order to do lots of real work in JS, developers need to rely on redefinable identifiers to be what they are. I don't hear people telling me that I shouldn't use setTimeout because someone can

window.setTimeout = function () {
    alert("Got you now!");
};

Bottom line, the "it can be redefined" argument to not use a raw === undefined is bogus.

(If you are still scared of undefined being redefined, why are you blindly integrating untested library code into your code base? Or even simpler: a linting tool.)


Also, like the typeof approach, this technique can "detect" undeclared variables:

if (window.someVar === undefined) {
    doSomething();
}

But both these techniques leak in their abstraction. I urge you not to use this or even

if (typeof myVar !== "undefined") {
    doSomething();
}

Consider:

var iAmUndefined;

To catch whether or not that variable is declared or not, you may need to resort to the in operator. (In many cases, you can simply read the code O_o).

if ("myVar" in window) {
    doSomething();
}

But wait! There's more! What if some prototype chain magic is happeningโ€ฆ? Now even the superior in operator does not suffice. (Okay, I'm done here about this part except to say that for 99% of the time, === undefined (and ****cough**** typeof) works just fine. If you really care, you can read about this subject on its own.)

๐ŸŒ
Mastering JS
masteringjs.io โ€บ tutorials โ€บ fundamentals โ€บ undefined-check
How to Check if a JavaScript Variable is Undefined - Mastering JS
If you want to check if x is strictly equal to undefined regardless of whether is has been declared or not, you should use typeof x === 'undefined'.
๐ŸŒ
W3docs
w3docs.com โ€บ javascript
How to Check if the Variable is Undefined
If you check by value, you will get that variable is assigned a value or not. In the case of undefined, the assigned variable donโ€™t have any value but the variable exists. Checking the type is done with the typeof operator.
๐ŸŒ
W3Schools
w3schools.com โ€บ jsref โ€บ jsref_undefined.asp
JavaScript undefined Property
โฎ Previous JavaScript Global Methods Next โฏ ยท Variable with no value: let x; if (x === undefined) { text = "x is undefined"; } else { text = "x is defined"; } Try it Yourself ยป ยท let x; if (typeof x === "undefined") { text = "x is undefined"; } else { text = "x is defined"; } Try it Yourself ยป ยท More examples below. The undefined property indicates that a variable has not been assigned a value, or not declared at all.
๐ŸŒ
The Valley of Code
thevalleyofcode.com โ€บ how-to-check-undefined-property-javascript
How to check if a JavaScript object property is undefined
In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. typeof returns a string that tells the type of the operand. It is used without parentheses, passing it any value you want to ...
๐ŸŒ
Programiz
programiz.com โ€บ javascript โ€บ examples โ€บ check-undefined-null
JavaScript Program To Check If A Variable Is undefined or null
To understand this example, you ... is undefined or null function checkVariable(variable) { if(variable == null) { console.log('The variable is undefined or null'); } else { console.log('The variable is neither undefined nor null'); } } let newVariable; checkVariable(5); ...
๐ŸŒ
SheCodes
shecodes.io โ€บ athena โ€บ 81408-what-does-undefined-mean-in-javascript
[JavaScript] - What does !==undefined mean in JavaScript? - | SheCodes
Learn about the !==undefined comparison operator in JavaScript and how it is used to check if a variable is not undefined.
Top answer
1 of 16
5789

You can just check if the variable has a truthy value or not. That means

if (value) {
    // do something..
}

will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section.

Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. For instance

if (typeof foo !== 'undefined') {
    // foo could get resolved and it's defined
}

If you can be sure that a variable is declared at least, you should directly check if it has a truthy value like shown above.

2 of 16
457

This question has two interpretations:

Check if the variable has a value
Check if the variable has a truthy value

The following answers both.

In JavaScript, a value could be nullish or not nullish, and a value could be falsy or truthy.
Nullish values are a proper subset of falsy values:

 โ•ญโ”€ nullish โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ•ญโ”€ not nullish โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”
โ”‚ undefined โ”‚ null โ”‚ false โ”‚ 0 โ”‚ "" โ”‚ ... โ”‚ true โ”‚ 1 โ”‚ "hello" โ”‚ ... โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”˜
 โ•ฐโ”€ falsy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ฐโ”€ truthy โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ

Check if value is nullish (undefined or null)

Use one of the following depending on your coding style:

if (value == null)                         { /* value is nullish */ }
if (value === undefined || value === null) { /* value is nullish */ }
if (value == undefined)                    { /* value is nullish */ }
if ((value ?? null) === null)              { /* value is nullish */ }

Notes:

  • The == operator works because it has a special case for null vs undefined comparison
  • The === operator is more readable (opinion based), eqeqeq friendly and allows checking for undefined and null separately
  • The first and third examples work identically, however the third one is rarely seen in production code
  • The fourth example uses nullish coalescing operator to change nullish values to null for straight forward comparison

Check if value is not nullish

if (value != null)                         { /* value is not nullish, although it could be falsy */ }
if (value !== undefined && value !== null) { /* value is not nullish, although it could be falsy */ }
if (value != undefined)                    { /* value is not nullish, although it could be falsy */ }
if ((value ?? null) !== null)              { /* value is not nullish, although it could be falsy */ }

Check if value is falsy

Use the ! operator:

if (!value) { /* value is falsy */ }

Check if value is truthy

if (value) { /* value is truthy */ }

Data validation

The nullish, falsy and truthy checks cannot be used for data validation on their own. For example, 0 (falsy) is valid age of a person and -1 (truthy) is not. Additional logic needs to be added on case-by-case basis. Some examples:

/*
 * check if value is greater than/equal to 0
 * note that we cannot use truthy check here because 0 must be allowed
 */
[null, -1, 0, 1].forEach(num => {
  if (num != null && num >= 0) {
    console.log("%o is not nullish and greater than/equal to 0", num);
  } else {
    console.log("%o is bad", num);
  }
});

/*
 * check if value is not empty-or-whitespace string
 */
[null, "", " ", "hello"].forEach(str => {
  if (str && /\S/.test(str)) {
    console.log("%o is truthy and has non-whitespace characters", str);
  } else {
    console.log("%o is bad", str);
  }
});

/*
 * check if value is not an empty array
 * check for truthy before checking the length property
 */
[null, [], [1]].forEach(arr => {
  if (arr && arr.length) {
    console.log("%o is truthy and has one or more items", arr);
  } else {
    console.log("%o is bad", arr);
  }
});

/*
 * check if value is not an empty array
 * using optional chaining operator to make sure that the value is not nullish
 */
[null, [], [1]].forEach(arr => {
  if (arr?.length) {
    console.log("%o is not nullish and has one or more items", arr);
  } else {
    console.log("%o is bad", arr);
  }
});
๐ŸŒ
Index.dev
index.dev โ€บ blog โ€บ check-undefined-variable-javascript
How to Check if a Variable is Undefined in JavaScript
It works consistently across all ... more precise and slightly more performant: let x; // Preferred for known variables if (x === undefined) { /* ......