southerton southerton - 5 months ago 22
Ajax Question

Check if the response header is present in javascript, and why string is "null"?

Sorry for what maybe a very dumb javascript question (I'm from cpp/java background) but I can't find an answer to it. I'm writing a little js snippet that needs to check whether response header is present or not. That is how I do it:

var xhttp = new XMLHttpRequest();"GET", "NewServlet", false);
var name = xhttp.getResponseHeader("name");
if (name === "null") {...}

Now this part with "null" I feel it is plain wrong. Really, my servlet does not set this header, so it should be null, but not stringly-typed "null". Why do I get "null" instead of null? How to check the response header is empty from ajax response, or check if the string is empty?

EDIT: The thing is, that when I put

var name = xhttp.getResponseHeader("rhrhrhrhers");
if (!name) {...}

the condition (!name) surely doesn't hold, as name is "null", not null. There's no such response header for sure, so there's some hidden type conversion going on under the hood. It is converting the null to "null" when returning the result from getResponseHeader().

EDIT2: After some investigation in console:

> var name = null;
< undefined
> name
< "null"
> if (!name) console.log("f");
< undefined
> if (name) console.log("f");
< undefined

Now that doesn't make much sense to me, although I assign honest null to var it makes the sting with value "null", and condition doesn't hold.


It looks that the variable called name has some special meaning in js! Though I don't know which, as in JavaScript variable name validator ( it says it's legit.

That's what is happening in the console:

var name = null;
var test = null;

As you can see js interpreter somewhy deals with var name the other way than with other names (like test or whatever). The reason is still unclear to me.


Actually, the reason was that

var name = null;

was in global scope, and that effectively called property; property has a setter that convert anything I pass in into a string.


> var name = 2;
< undefined
> name
< "2"

The solution is not to touch global scope, as that is considered a bad practice. Instead:

   (function x() {
       var name = null;

This will produce the null output to console as we are in a auto-called closure this time, thus don't touch global window properties.