🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › null
null - JavaScript - MDN Web Docs
The null keyword refers to the null primitive value, which represents the intentional absence of any object value. function getVowels(str) { const m = str.match(/[aeiou]/gi); if (m === null) { return 0; } return m.length; } console.log(getVowels("sky")); // Expected output: 0
🌐
DevX
devx.com › home › null
Null - Glossary
January 17, 2024 - In programming languages such as JavaScript, C, and Java, a null value can be assigned to variables to indicate that they do not have a valid object reference or lack any value or data.
🌐
W3Schools
w3schools.com › c › c_null.php
C NULL
Tip: Always check if a pointer is NULL before using it. This helps avoid crashes caused by accessing invalid memory. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an error, or if you want to make a suggestion, send us an e-mail: help@w3schools.com · HTML Tutorial CSS Tutorial JavaScript ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › null
null - JavaScript | MDN
May 23, 2022 - The null keyword refers to the null primitive value, which represents the intentional absence of any object value. function getVowels(str) { const m = str.match(/[aeiou]/gi); if (m === null) { return 0; } return m.length; } console.log(getVowels("sky")); // Expected output: 0
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Glossary › Null
Null - Glossary - MDN Web Docs
In computer science, a null value represents a reference that points, generally intentionally, to a nonexistent or invalid object or address. The meaning of a null reference varies among language implementations. In JavaScript, null is marked as one of the primitive values, because its behavior ...
🌐
Computer Hope
computerhope.com › jargon › n › nullchar.htm
What Is a Null Character?
January 6, 2025 - A null character is programming code representing a character with no value, a missing value, or used to denote the end of a character string. In databases and spreadsheets, a null character can also be used as padding.
🌐
GeeksforGeeks
geeksforgeeks.org › null-in-javascript
Null in JavaScript | GeeksforGeeks
June 5, 2024 - In JavaScript, both undefined and null represent the absence of a meaningful value, but they have different purposes and are used in distinct contexts. Knowing when and how to use each can help you write clearer, more predictable code.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing
Nullish coalescing operator (??) - JavaScript - MDN Web Docs
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
🌐
JavaScript Tutorial
javascripttutorial.net › home › an essential guide to javascript null
An Essential Guide to JavaScript null
September 29, 2020 - In JavaScript, null is a primitive value, not an object. It turns out that this is a historical bug from the first version of JavaScript that may never be fixed. In JavaScript, you often call a function to get an object.
🌐
Programiz
programiz.com › javascript › null-undefined
JavaScript null and undefined
The code above suggests that the number variable is empty at the moment and may have a value later. Note: null is not the same as NULL or Null. In JavaScript, undefined and null are treated as false values.
Find elsewhere
🌐
ScienceDirect
sciencedirect.com › topics › computer-science › null-character
Null Character - an overview | ScienceDirect Topics
The null character is defined as the numerical value 0 (the ASCII null character), which is distinct from the character “0” that has the ASCII code value 48. 1 In computer science, the null character is commonly represented as '\0' and is used as a string terminator in many programming ...
🌐
Dmitri Pavlutin
dmitripavlutin.com › javascript-null
Everything about null in JavaScript - Dmitri Pavlutin
September 21, 2020 - In this post, you'll learn everything about null in JavaScript: its meaning, how to detect it, the difference between null and undefined, and why using null extensively creates code maintenance difficulties.
🌐
DEV Community
dev.to › sduduzog › null-vs-undefined-what-to-choose-what-to-use-11g
null vs undefined? What to choose? What to use? - DEV Community
August 23, 2023 - I'm not quiet sure yet if that's also an exact equivalent to null, but it's worth checking out. undefined is a primitive value used when a variable has not been assigned a value. This is just a JavaScript thing.
🌐
Scaler
scaler.com › home › topics › javascript › null and undefined in javascript
Null and Undefined in JavaScript - Scaler Topics
April 4, 2024 - There is a subtle difference between null and undefined, but as a programmer, it is important that we understand it clearly. As the name suggests, undefined means "not defined". So we declare a variable but do not assign a value to it, the variable becomes undefined. Unlike null, the value of an undefined variable is set by JavaScript as undefined.
Top answer
1 of 9
985

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

Is the variable null:

Copyif (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:

Copyif (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:

Copyif (!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:

Copyvar 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:

Copyfunction 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:

Copynull === 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:

Copyfunction test(val) {
    return val == null;
}
test(null);       # => true
test(undefined);  # => true
🌐
freeCodeCamp
freecodecamp.org › news › how-to-check-for-null-in-javascript
JS Check for Null – Null Checking in JavaScript Explained
November 7, 2024 - Null is a primitive type in JavaScript. This means you are supposed to be able to check if a variable is null with the typeof() method. But unfortunately, this returns “object” because of an historical bug that cannot be fixed. let userName ...
🌐
web.dev
web.dev › learn › javascript › data-types › null-undefined
null and undefined | web.dev
The null keyword represents an intentionally defined absence of value. null is a primitive, although the typeof operator returns that null is an object. This is an error that has carried over from the first version of JavaScript and been left ...
🌐
The Valley of Code
thevalleyofcode.com › lesson › c-advanced › null
C Advanced: NULL values
#include <stdio.h> int main(void) { int * p_some_variable = NULL; } ... hello.c:3:26: error: use of undeclared identifier 'NULL' int * p_some_variable = NULL; ^ 1 error generated.
Top answer
1 of 5
7

Actually, you can use a literal 0 anyplace you would use NULL.

Section 6.3.2.3p3 of the C standard states:

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

And section 7.19p3 states:

The macros are:

CopyNULL

which expands to an implementation-defined null pointer constant

So 0 qualifies as a null pointer constant, as does (void *)0 and NULL. The use of NULL is preferred however as it makes it more evident to the reader that a null pointer is being used and not the integer value 0.

2 of 5
5

NULL is used to make it clear it is a pointer type.

Ideally, the C implementation would define NULL as ((void *) 0) or something equivalent, and programmers would always use NULL when they want a null pointer constant.

If this is done, then, when a programmer has, for example, an int *x and accidentally writes *x = NULL;, then the compiler can recognize that a mistake has been made, because the left side of = has type int, and the right side has type void *, and this is not a proper combination for assignment.

In contrast, if the programmer accidentally writes *x = 0; instead of x = 0;, then the compiler cannot recognize this mistake, because the left side has type int, and the right side has type int, and that is a valid combination.

Thus, when NULL is defined well and is used, mistakes are detected earlier.

In particular answer to your question “Is there a context in which just plain literal 0 would not work exactly the same?”:

  • In correct code, NULL and 0 may be used interchangeably as null pointer constants.
  • 0 will function as an integer (non-pointer) constant, but NULL might not, depending on how the C implementation defines it.
  • For the purpose of detecting errors, NULL and 0 do not work exactly the same; using NULL with a good definition serves to help detect some mistakes that using 0 does not.

The C standard allows 0 to be used for null pointer constants for historic reasons. However, this is not beneficial except for allowing previously written code to compile in compilers using current C standards. New code should avoid using 0 as a null pointer constant.