When writing this in javascript, I have seen it written in two different ways:
if (typeof x === "undefined") {
// execute code here
}
if (typeof x === undefined) {
// execute code here
}
my question here is:
what is the difference between "undefined" and undefined. One is enclosed in quotes and the other is not.
Can anybody clarify this for me?
Thanks!
undefined is a value, 'undefined' is a string literal. The typeof operator returns a string that gives you the type. So typeof x returns the string name of the type of x.
Use if( x === undefined ) or if( typeof x === 'undefined' ) but never if( typeof x === undefined ) because typeof x will always return a string (which will never equal undefined).
"undefined" is a string, and undefined is a variable containing the primitive value undefined (Thank you elclanrs).
if(typeof x === undefined) should only ever be able to return true if undefined is reassigned to a string matching the type of x.
Related
I encountered this difference between undefined and "undefined" and I am trying to understand it.
I was checking whether properties in objects are defined or not.
In first example I checked whether property is not undefined. All the test below evaluates to true. It doesn't matter whether I use "undefined" or undefined.
var test = {
x: 1,
y: 2
};
if (test.x != "undefined") console.log('test.x != "undefined"'); //TRUE
if (test.x !== "undefined") console.log('test.x !== "undefined"'); //TRUE
if (test.x != undefined) console.log('test.x != undefined'); //TRUE
if (test.x !== undefined) console.log('test.x !== undefined'); //TRUE
Then I tried it with property which is not defined.It only evaluates to true if i use undefined (not string literal) or with typeof.
var test = {
x: 1,
y: 2
};
if (test.z === undefined) console.log("test.z === undefined"); //TRUE
if (test.z == undefined) console.log("test.z == undefined"); //TRUE
if (test.z === "undefined") console.log("test.z === 'undefined'"); //FALSE
if (test.z == "undefined") console.log("test.z == 'undefined'"); //FALSE
if (typeof test.z === "undefined") console.log("typeof test.z === 'undefined'"); //TRUE
So my question is: why the difference (I guess I don't understand something ...). Is it bad practice that I used comparison to "undefined"/undefined rather than .hasOwnProperty()?
undefined and "undefined" are different values. The former is undefined, the latter is a string.
What you've probably seen isn't x === "undefined" and x === undefined, but rather typeof x === "undefined" and x === undefined. Note the typeof. One of the reasons you see the former (with typeof) is historic and no longer relevant, but not all of the reasons are.
Assuming a declared identifier x and that undefined has not been shadowed, these two statements are effectively the same other than the first one has to do a teensy bit more work:
typeof x === "undefined"
x === undefined
But if x isn't declared, the former will evaluate true, and the latter will fail with a ReferenceError. (In the general case, you probably want the ReferenceError as it alerts you to the undeclared idenfier, but there are use cases for the former.)
But undefined is, unfortunately, not a keyword (like null); it's a global constant. That means that undefined can be shadowed:
function foo(undefined) {
var x; // x defaults to the value undefined
console.log(typeof x === "undefined"); // true
console.log(x === undefined); // false?!?!
}
foo(42);
In practice, if you find someone shadowing undefined and giving it a value other than undefined, take them out back and beat them about the head and shoulders with a wet noodle until they see sense. But...
Historically, there was many years ago a problem with the undefined value in one window not being === to the undefined value. And so if you had code that might be dealing with values from across windows, comparing with === undefined wasn't a reliable way to check for undefined. A couple of years back I checked all even vaguely-recent browsers and that wasn't an issue (I suspect it hasn't been for much longer than that).
When you are checking for "undefined" (in quotes) then you are checking for string with value "undefined".
Whereas when you are checking for undefined then it is checked if the property or the variable is defined or not. Therefore you can use this to check if the property is defined.
I want to check that a variable exists and that it its length is greater than a particular number within a single if statement. I can achieve the desired result by doing:
if(v){
if(v.length>3)
//do thing
}
But if I try to just do:
if(v.length>3)
// do thing
I bug out when v is not declared. Similarly if I try to do:
if(v&&v.length>3)
I bug out. How do I achieve the desired result most readably?
A final answer depends on how generic you want the solution. While .length is shorthand notation for looking up an object property named "length", it must be applied to an object value. But the typeof operator returns "function" for a function object, and "object" for null - which is not an object data type and will crash if you attempt to look up a property on it. Oh, and primitive string values promote to a String object with a length property.
So, a generic solution could look like
if(v && typeof v == "object" || typeof v == "function" || typeof v == "string" && v.length > 3)
{ // do stuff
}
where the test for v being truthy excludes v having a value of null. But notice that if you can exclude function objects (which have a length property giving the number of arguments they expect) and string values you could shorten this to
if(v && typeof v == "object" && v.length > 3)
Note that if the length property does not exist it will return a value of undefined and undefined > 3 is false.
Update after question comment:
if(v)
can fail in strict mode if v has never been defined. This could be the result of defining v using a let or const statement executed after the if statement. Either execute the let or const statement first or declare v using a var statement in scope of the testing code.
In my Javascript code I'm checking if a variable is undefined (not the value undefined but the variable not defined) or null. To trim the code I'm using an operator. This is how I do it:
if (myVariable === (undefined || null)) {
// Do something.
}
A friend of mine told me once, that I should rather split the checks into:
if (myVariable === undefined || myVariable === null) {
// Do something.
}
Is there really any difference between these two approaches? If yes, which one should I use and why?
Is there really any difference between these two approaches?
Yes.
myVariable === (undefined || null)
is equivalent to
myVariable === null
which is only true if myVariable is null, and false if myVariable is undefined. Whereas:
myVariable === undefined || myVariable === null
returns true if myVariable is either undefined or null.
If yes, which one should I use and why?
Neither (probably), even if the answer was yes. If you are trying to determine whether a variable exists or not, you can only test for global variables as they are properties of the global object:
// In global code
var window = this;
// Later…
if (varname in window) {
// varname is a global variable or property
}
Within a function execution context, you can only reliably test for a variable using try..catch:
try {
var blah = foo;
} catch (e) {
// foo is probably not a variable in scope
}
But that is almost certainly not a good idea. See JavaScript check if variable exists (is defined/initialized) - Which method is better?.
You should probably be doing:
if (typeof varname == 'undefined' || varname === null) {
// varname either does't exist or has a value of undefined or null.
}
The tests need to be in that order so that if varname hasn't been declared or otherwise created, the typeof test fails before the null test, which would otherwise throw an error.
Prefere : if (typeof myVariable === "undefined" || myVariable === null) {.
variable === undefined vs. typeof variable === "undefined"
Because with if (myVariable === undefined) { your console can be return an error or warning.
Like this :
ReferenceError: myVariable is not defined
if (myVariable === undefined) {
PS : (undefined || null) is always null (because undefined return false).
=== operator in JS compares 2 operands (values).
In case of myVariable === (undefined || null) the operands are: myVariable, which represents the value it holds, and (undefined || null) which represents the value null, because operands (expressions) must be evaluated before comparison. And the (undefined || null) expression is evaluated to null.
So effectively your solution is identical to myVariable === null.
If you follow the same idea and evaluate your friend proposal you will see that his advice is correct.
It's because (undefined || null) always evaluates to null so your first expression always false when myVariable is undefined. The second variant is do what you want correctly.
Yes, it is. For your example, undefined is equal false then null is equal false too and this last value returns from expression. So this is why first approach is equal to if (myVariable === null) { ... }. The second approach is preferable, but if you not a 'JavaScript: The Good Parts' guy, you can stick with if (myVariable == null) { ... } or if (myVariable == undefined) { ... }.
I want to set a Value in a javascript object only when it is not set. My (test) function looks like:
var test = function(){
this.value = {};
this.setValue = function(seperator, newValue){
console.log((this.value[seperator] === "undefined")); //Why both times false?
if(typeof(this.value[seperator] === "undefined")){
this.value[seperator] = newValue;
}else{
//noop
}
console.log(this.value[seperator]);
}
}
var blubb = new test();
blubb .setValue("foo","bar");
blubb .setValue("foo","notme");
in the js console it returns
false
bar
false
notme
Can someone tell me why both time my test of "undefined" told me that is not defined?
thanks in advance
Because undefined in JS is not a string, it's a property of global object and you comparing by type using ===.
=== will compare not only values but their types too:
1 === "1" // false
1 == "1" // true
Try this:
console.log(( typeof this.value[seperator] === "undefined"));
typeof operator transforms variable type to string and only then you can check if your variable is equal to string undefined.
In your second piece of code:
if(typeof(this.value[seperator] === "undefined")){
you use typeof operator outside of the variable so your code first checks if this.value[seperator] === "undefined" then it returns false to you and then you check by "typeof false", it will return boolean for you.
In final step your code converts to:
if( "boolean" ){
And this is always true as string is not empty.
Short answer:
"undefined" !== undefined
Check for undefined instead.
> var foo = { foo: 'foo' };
> foo['bar']
undefined
> typeof(foo['bar'])
"undefined"
Also note that typeof(this.value[seperator] === "undefined") means typeof(boolean) as it'd first evaluate your expression (this.value[seperator] === "undefined") and then get the type of that.
You probably meant typeof(this.value[seperator]) === "undefined".
Your brackets are in the wrong place in this line:
if(typeof(this.value[seperator] === "undefined")){
You're doing the typeof of (this.value[seperator] === "undefined") - that's a boolean condition (will return true or false) so I'd expect typeof to give you "boolean". Then your if statements condition is the string "boolean" which, since it's not zero length, is considered true in JavaScript.
What you wanted is:
if((typeof this.value[seperator]) === "undefined") {
If Not (oResponse.selectSingleNode("BigGroupType") Is Nothing) Then
End If
I need to convert this to javascript. Is that enough to check null?
This was my lead's answer, plz verify this,
if(typeof $(data).find("BigGroupType").text() != "undefined" && $(data).find("BigGroupType").text() != null) {
}
JavaScript has two values which mean "nothing", undefined and null. undefined has a much stronger "nothing" meaning than null because it is the default value of every variable. No variable can be null unless it is set to null, but variables are undefined by default.
var x;
console.log(x === undefined); // => true
var X = { foo: 'bar' };
console.log(X.baz); // => undefined
If you want to check to see if something is undefined, you should use === because == isn't good enough to distinguish it from null.
var x = null;
console.log(x == undefined); // => true
console.log(x === undefined); // => false
However, this can be useful because sometimes you want to know if something is undefined or null, so you can just do if (value == null) to test if it is either.
Finally, if you want to test whether a variable even exists in scope, you can use typeof. This can be helpful when testing for built-ins which may not exist in older browsers, such as JSON.
if (typeof JSON == 'undefined') {
// Either no variable named JSON exists, or it exists and
// its value is undefined.
}
You need to check for both null and undefined, this implicitly does so
if( oResponse.selectSingleNode("BigGroupType") != null ) {
}
It is the equivalent of:
var node = oResponse.selectSingleNode("BigGroupType");
if( node !== null &&
node !== void 0 ) {
}
void 0 being a bulletproof expression to get undefined
In JavaScript equvalent for Nothing is undefined
if(oResponse.selectSingleNode("BigGroupType") != undefined){
}
This logic:
If Not (oResponse.selectSingleNode("BigGroupType") Is Nothing)
Can be written like this in JavaScript:
if (typeof oResponse.selectSingleNode("BigGroupType") != 'undefined')
Nothing would equal undefined, but checking against undefined is not recommended for several reasons, it’s generally safer to use typeof.
However, if the selectSingleNode can return other falsy values such as null, it’s probably OK to just do a simple check if it is truthy:
if (oResponse.selectSingleNode("BigGroupType"))
JavaScript:-
(document.getElementById(“BigGroupType”) == undefined) // Returns true
JQuery:-
($(“#BigGroupType”).val() === “undefined”) // Returns true
Note in above examples undefined is a keyword in JavaScript, where as in JQuery it is just a string.