Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign null to javascript var - ends up as String [duplicate]

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.

like image 504
matthias Avatar asked Feb 13 '23 00:02

matthias


1 Answers

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
    }
})();
like image 196
p.s.w.g Avatar answered Feb 14 '23 17:02

p.s.w.g