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();
xhttp.open("GET", "NewServlet", false);
xhttp.send();
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");
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.
EDIT3:
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 (https://mothereff.in/js-variables) it says it's legit.
That's what is happening in the console:
var name = null;
undefined
var test = null;
undefined
name
"null"
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.