4

I have initialized my variable as the following:

var name = null;

If I check it's value like this it doesnt do anything:

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

But if I change the if-clause to that, it works:

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

Happy for every help.

matthias
  • 47
  • 5

1 Answers1

8

It's likely that you're running this is in global scope, in which case name refers to the Window.name property. Assigning a value to this property automatically causes the value to be converted to a string, for example, try opening up your browser's console and typing this:

var name = 123;
alert(typeof name); 

You'll most likely get an alert that reads string.

However, if you place this in an IIFE (and ensure that you have a var declaration), it behaves as expected:

(function() {
    var name = null;
    if(name == null) {
        alert("Name = null"); // shows alert
    }
})();
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331