JavaScript null

JavaScript null is a primitive datatype which has only one value null.

If we reference to an object that is not present in the HTML document, then the object holds the value null.

The syntax to assign a null value to a variable x is

</>
Copy
var x = null;

null value is equivalent to undefined and the following expression returns true.

</>
Copy
null == undefined

Initialization with null

In the following example, we define a variable x with null value.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var x = null;
        document.getElementById('output').innerHTML += x;
    </script>
</body>
</html>

Object Not Present in HTML Doc

In the following example, we try to get an Element that is not present in the HTML Document using JavaScript. As the element is not present, the object/value would be undefined.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var x = document.getElementById('not_prsent');
        document.getElementById('output').innerHTML += x;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned what a null value is in JavaScript.