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.

Answer from jAndy on Stack Overflow
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);
  }
});
People also ask

Is null false in JavaScript?
Null is not considered false in JavaScript, but it is considered falsy. This means that null is treated as if itโ€™s false when viewed through boolean logic. However, this is not the same thing as saying null is false or untrue.
๐ŸŒ
builtin.com
builtin.com โ€บ software-engineering-perspectives โ€บ javascript-null-check
How to Check for Null in JavaScript | Built In
What is a strict null check?
StrictNullChecks is a feature that treats null and undefined as two separate types, reducing errors and making it easier to find coding bugs. It also has stronger measures for defining variables as null or undefined, ensuring variables are declared as null only when itโ€™s safe to do so.
๐ŸŒ
builtin.com
builtin.com โ€บ software-engineering-perspectives โ€บ javascript-null-check
How to Check for Null in JavaScript | Built In
What is a null check?
In JavaScript, null represents an intentional absence of a value, indicating that a variable has been declared with a null value on purpose. On the other hand, undefined represents the absence of any object value that is unintentional. A null check determines whether a variable has a null value, meaning a valid instance of a type exists.
๐ŸŒ
builtin.com
builtin.com โ€บ software-engineering-perspectives โ€บ javascript-null-check
How to Check for Null in JavaScript | Built In
Top answer
1 of 16
674

I think the most efficient way to test for "value is null or undefined" is

if ( some_variable == null ){
  // some_variable is either null or undefined
}

So these two lines are equivalent:

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

Note 1

As mentioned in the question, the short variant requires that some_variable has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:

check for optional arguments:

function(foo){
    if( foo == null ) {...}

check for properties on an existing object

if(my_obj.foo == null) {...}

On the other hand typeof can deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.

Note 2

This - even shorter - variant is not equivalent:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

so

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

Note 3

In general it is recommended to use === instead of ==. The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull option for this reason.

From the jQuery style guide:

Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

EDIT 2021-03:

Nowadays most browsers support the Nullish coalescing operator (??) and the Logical nullish assignment (??=), which allows a more concise way to assign a default value if a variable is null or undefined, for example:

if (a.speed == null) {
  // Set default if null or undefined
  a.speed = 42;
}

can be written as any of these forms

a.speed ??= 42;
a.speed ?? a.speed = 42;
a.speed = a.speed ?? 42;
2 of 16
382

You have to differentiate between cases:

  1. Variables can be undefined or undeclared. You'll get an error if you access an undeclared variable in any context other than typeof.

    if(typeof someUndeclaredVar == whatever) // Works
    if(someUndeclaredVar) // Throws an error
    

    A variable that has been declared but not initialized is undefined.

    let foo;
    if (foo) // Evaluates to false because foo === undefined
    
  2. Undefined properties, like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a Boolean, evaluates to false. So, if you don't care about 0 and false, using if(obj.undefProp) is OK. There's a common idiom based on this fact:

    value = obj.prop || defaultValue
    

    which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue".

    Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead

    value = ('prop' in obj) ? obj.prop : defaultValue
    
๐ŸŒ
Built In
builtin.com โ€บ software-engineering-perspectives โ€บ javascript-null-check
How to Check for Null in JavaScript | Built In
Written by Dr. Derek Austin ... Summary: JavaScript offers several ways to check for null, including strict (===) and loose (==) equality, Object.is() and boolean coercion. Developers often use typeof and optional chaining (?.) to safely identify ...
Published ย  August 4, 2025
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ javascript โ€บ how do i check for an empty/undefined/null string in javascript?
How do I Check for an Empty/Undefined/Null String in JavaScript? | Sentry
To check that a value is not an empty string, null, or undefined, you can create a custom function that returns true if a value is null, undefined, or an empty string and false for all other falsy values and truthy values: ... function ...
Find elsewhere
๐ŸŒ
CSS { In Real Life }
css-irl.info โ€บ handling-null-undefined-and-zero-values-in-javascript
CSS { In Real Life } | Handling Null, Undefined and Zero Values in JavaScript
The issue here is that if daysSinceLastPost is 0, the text will read โ€œUnknown days since last postโ€ too! Instead, we could use the ?? operator, otherwise known as the nullish coalescing operator.
๐ŸŒ
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
<script> var firstName; var lastName = null; // Try to get non existing DOM element var comment = document.getElementById('comment'); console.log(firstName); // Print: undefined console.log(lastName); // Print: null console.log(comment); // Print: null console.log(typeof firstName); // Print: undefined console.log(typeof lastName); // Print: object console.log(typeof comment); // Print: object console.log(null == undefined) // Print: true console.log(null === undefined) // Print: false /* Since null == undefined is true, the following statements will catch both null and undefined */ if(firstNa
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ javascript โ€บ how-to-check-if-a-variable-is-not-null-in-javascript
How to check if a Variable Is Not Null in JavaScript ? - GeeksforGeeks
August 5, 2025 - Example: In this example we are using typeof operator with !== undefined and !== null checks if a variable is not null in JavaScript. Output Variable is not null if true, else Variable is null.
๐ŸŒ
LogRocket
blog.logrocket.com โ€บ home โ€บ how to check for null, undefined, or empty values in javascript
How to check for null, undefined, or empty values in JavaScript - LogRocket Blog
February 14, 2025 - Learn how to write a null check function in JavaScript and explore the differences between the null and undefined attributes.
๐ŸŒ
Omarileon
omarileon.me โ€บ blog โ€บ typescript-null-undefined
mari. | How to Detect Null and Undefined in Your TypeScript Code
February 27, 2024 - The key here though is that anything ...ndefined!'); //Prints ยท Another way to check for null or undefined is to use the nullish coalescing operator (??), which was introduced in TypeScript 3.7....
๐ŸŒ
Medium
tirumalsutrave.medium.com โ€บ null-undefined-and-empty-checks-in-javascript-fb7110aca7cc
Null, undefined and empty checks in JavaScript | by Tirumal Sutrave | Medium
August 30, 2020 - var myVariable = ""; if(myVariable !== ""){ console.log(โ€˜I will not print if the string value is empty.โ€™); } You can use inequality(!=) operator to check if the value is an empty string(โ€œโ€) or zero(0). This will give some multi-value ...
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Operators โ€บ null
null - JavaScript | MDN
function getVowels(str) { const m = str.match(/[aeiou]/gi); if (m === null) { return 0; } return m.length; } console.log(getVowels("sky")); // Expected output: 0 ... The keyword null is a literal for the null value. Unlike undefined, which is a global variable, null is not an identifier but ...
๐ŸŒ
Reddit
reddit.com โ€บ r/javascript โ€บ basic js question: when to check for undefined, null, etc
r/javascript on Reddit: Basic JS question: when to check for undefined, null, etc
September 11, 2016 -

So I'm usually more of a server side developer, but lately I've been working with more of the client code at work. I understand what undefined and null are in JavaScript, but I find myself always checking for both of them. In fact, when checking if a String property exists, I end up writing this:

if(value !== undefined && value !== null && value !== '')

I figure there is a better way than this, and it's probably because I'm not 100% clear of when to check for what. So if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.

Top answer
1 of 5
28

TL;DR: Use value != null. It checks for both null and undefined in one step.

In my mind, there are different levels of checking whether something exists:

0) 'property' in object - Returns true if the property exists at all, even if it's undefined or null.

  1. object.property !== undefined - Returns true if the property exists and is not undefined. Null values still pass.

  2. object.property != null - Return true if the property exists and is not undefined or null. Empty strings and 0's still pass.

  3. !!object.property - Returns true if the property exists and is "truthy", so even 0 and empty strings are considered false.

From my experience, level 2 is usually the sweet spot. Oftentimes, things like empty strings or 0 will be valid values, so level 3 is too strict. On the other hand, levels 0 and 1 are usually too loose (you don't want nulls or undefineds in your program). Notice that level 1 uses strict equality (!==), while level 2 uses loose equality (!=).

2 of 5
16

I would just say

if (value) {
  // do stuff
}

because

'' || false
// false
null || false
// false
undefined || false
//false

Edit:

Based on this statement

I end up writing this: if(value !== undefined && value !== null && value !== '')

I initially assumed that what OP was really looking for was a better way to ask "is there a value?", but...

if someone could help fill me in here on the rules of when to check for undefined vs null, that would be great.

If you're looking to see if something is "truthy":

if (foo.bar) {
  alert(foo.bar)
}

This won't alert if value is '', 0, false, null, or undefined

If you want to make sure something is a String so you can use string methods:

if (typeof foo.bar === 'string') {
  alert(foo.bar.charAt(0))
}

This won't alert unless value is of type 'string'.

So.. "when to check for undefined vs null"? I would just say, whenever you know that you specifically need to check for them. If you know that you want to do something different when a value is null vs when a value is undefined, then you can check for the difference. But if you're just looking for "truthy" then you don't need to.

Top answer
1 of 9
983

How do I check a variable if it's null or undefined...

Is the variable null:

if (a === null)
// or
if (a == null) // but see note below

...but note the latter will also be true if a is undefined.

Is it undefined:

if (typeof a === "undefined")
// or
if (a === undefined)
// or
if (a == undefined) // but see note below

...but again, note that the last one is vague; it will also be true if a is null.

Now, despite the above, the usual way to check for those is to use the fact that they're falsey:

if (!a) {
    // `a` is falsey, which includes `undefined` and `null`
    // (and `""`, and `0`, and `NaN`, and [of course] `false`)
}

This is defined by ToBoolean in the spec.

...and what is the difference between the null and undefined?

They're both values usually used to indicate the absence of something. undefined is the more generic one, used as the default value of variables until they're assigned some other value, as the value of function arguments that weren't provided when the function was called, and as the value you get when you ask an object for a property it doesn't have. But it can also be explicitly used in all of those situations. (There's a difference between an object not having a property, and having the property with the value undefined; there's a difference between calling a function with the value undefined for an argument, and leaving that argument off entirely.)

null is slightly more specific than undefined: It's a blank object reference. JavaScript is loosely typed, of course, but not all of the things JavaScript interacts with are loosely typed. If an API like the DOM in browsers needs an object reference that's blank, we use null, not undefined. And similarly, the DOM's getElementById operation returns an object reference โ€” either a valid one (if it found the DOM element), or null (if it didn't).

Interestingly (or not), they're their own types. Which is to say, null is the only value in the Null type, and undefined is the only value in the Undefined type.

What is the difference between "==" and "==="

The only difference between them is that == will do type coercion to try to get the values to match, and === won't. So for instance "1" == 1 is true, because "1" coerces to 1. But "1" === 1 is false, because the types don't match. ("1" !== 1 is true.) The first (real) step of === is "Are the types of the operands the same?" and if the answer is "no", the result is false. If the types are the same, it does exactly what == does.

Type coercion uses quite complex rules and can have surprising results (for instance, "" == 0 is true).

More in the spec:

  • Abstract Equality Comparison (==, also called "loose" equality)
  • Strict Equality Comparison (===)
2 of 9
99

The difference is subtle.

In JavaScript an undefined variable is a variable that as never been declared, or never assigned a value. Let's say you declare var a; for instance, then a will be undefined, because it was never assigned any value.

But if you then assign a = null; then a will now be null. In JavaScript null is an object (try typeof null in a JavaScript console if you don't believe me), which means that null is a value (in fact even undefined is a value).

Example:

var a;
typeof a;     # => "undefined"

a = null;
typeof null;  # => "object"

This can prove useful in function arguments. You may want to have a default value, but consider null to be acceptable. In which case you may do:

function doSomething(first, second, optional) {
    if (typeof optional === "undefined") {
        optional = "three";
    }
    // do something
}

If you omit the optional parameter doSomething(1, 2) thenoptional will be the "three" string but if you pass doSomething(1, 2, null) then optional will be null.

As for the equal == and strictly equal === comparators, the first one is weakly type, while strictly equal also checks for the type of values. That means that 0 == "0" will return true; while 0 === "0" will return false, because a number is not a string.

You may use those operators to check between undefined an null. For example:

null === null            # => true
undefined === undefined  # => true
undefined === null       # => false
undefined == null        # => true

The last case is interesting, because it allows you to check if a variable is either undefined or null and nothing else:

function test(val) {
    return val == null;
}
test(null);       # => true
test(undefined);  # => true
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ javascript-check-if-variable-is-a-undefined-or-null
JavaScript: Check if Variable is undefined or null
March 29, 2023 - In this short guide, we've taken a look at how to check if a variable is null, undefined or nil in JavaScript, using the ==, === and typeof operators, noting the pros and cons of each approach.
๐ŸŒ
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.
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Operators โ€บ Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
In this example, we will provide default values but keep values other than null or undefined. ... const nullValue = null; const emptyText = ""; // falsy const someNumber = 42; const valA = nullValue ?? "default for A"; const valB = emptyText ?? "default for B"; const valC = someNumber ?? 0; console.log(valA); // "default for A" console.log(valB); // "" (as the empty string is not null or undefined) console.log(valC); // 42
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-check-for-null-in-javascript
JS Check for Null โ€“ Null Checking in JavaScript Explained
November 7, 2024 - As you can see, it only returns true when a null variable is compared with null, and an undefined variable is compared with undefined.