Thursday 30 August 2018

JavaScript: null Vs undefined

Both null and undefined are used to represent a variable with no value. But there is a small difference between these two.

undefined
If you declare a variable without assigning any value, then it is treated as undefined.

null
You can assign null to any variable to specify that variable has no value, but you can’t assign undefined to any variable.

One more difference is type of null return object, where as type of undefined return undefined.

Comparison of null and undefined
 null === undefined // Strict comparison operator return false
 null == undefined // true
 null == null // true
undefined == undefined //true

undefined.html
<!DOCTYPE html>

<html>

<head>
    <title>null Vs undefined</title>
</head>

<body>
    <script>
        var a;
        var b = null;

        document.write("a = " + a + " Type of a = " + (typeof a) + "<br />");
        document.write("b = " + b + " Type of b = " + (typeof b) + "<br />");
        document.write("a == b : " + (a == b) + "<br />");
        document.write("a === b : " + (a === b) + "<br />");
        document.write("a == a : " + (a == a) + "<br />");
        document.write("b == b : " + (b == b) + "<br />");
    </script>
</body>

</html>

Open above page in browser, you can able to see following text.

a = undefined Type of a = undefined
b = null Type of b = object
a == b : true
a === b : false
a == a : true
b == b : true


Previous                                                 Next                                                 Home

No comments:

Post a Comment