Assign null to javascript var - ends as String

I have initialized my variable like this:

var name = null;


If I checked its value like this, it doesn't do anything:

if(name == null) {
    alert("Name = null");


But if I change the if clause to this, it works:

if(name == "null") {
    alert("Name = null");


Glad for any help.


source to share

1 answer

You are probably using this in the global scope, in which case it name

refers to a property

. Assigning a value to this property automatically converts the value to a string, for example try opening the browser console and enter the following:

var name = 123;
alert(typeof name); 


You will most likely get a warning that reads string


However, if you put this in an IIFE (and make sure you have a declaration var

), it behaves as expected:

(function() {
    var name = null;
    if(name == null) {
        alert("Name = null"); // shows alert




All Articles