Skip to content

Type of null in JavaScript

  • by

In JavaScript, null is a primitive value that represents the intentional absence of any object value. It is often used to explicitly represent the absence of a value.

Additionally, there is also the undefined value, which represents a variable or property that has been declared but has not been assigned a value. While both null and undefined are falsy values in JavaScript, they have different use cases.

To assign a variable or property to the null value, you can use the following syntax:

let myVar = null;

To check if a value is null, you can use a strict equality comparison (===) with the null value:

if (myVar === null) {
  // do something
}

You can also check if a value is null or undefined using a non-strict equality comparison (==):

if (myVar == null) {
  // do something
}

However, it’s generally recommended to use strict equality comparisons (=== and !==) in JavaScript to avoid the unexpected types of coercion.

Type of null in JavaScript example

A simple example use the null value in JavaScript:

<!DOCTYPE html>
<html>
  <body>    
    <script>
    let myVar = null;

    console.log(myVar); 

    if (myVar === null) {
        console.log("myVar is null");
    }

    if (myVar == null) {
        console.log("myVar is null or undefined"); 
    }

    </script>
  </body>
</html>

Output:

Type of null in JavaScript

Here are some examples to illustrate the difference between null and undefined in JavaScript:

let myVar1 = null;  // value null
let myVar2;        // undefined

console.log(myVar1);  // null
console.log(myVar2);  // undefined

console.log(myVar1 == null);   //true (null is equal to undefined only in non-strict equality comparisons)

console.log(myVar2 == null);   // false

console.log(myVar2 == undefined);  //true (undefined is equal to null only in non-strict equality comparisons)

Comment if you have any doubts or suggestions on this JS null topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading