Undefined checking on variable practice [duplicate] - javascript

This question already has answers here:
Should I use `void 0` or `undefined` in JavaScript [duplicate]
(3 answers)
How can I check for "undefined" in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
is
if( typeof myVar === "undefined" )
the same as
if( myVar===void(0) )
?
And what is the best pratice, if there is one between these ? Why ?

Quoting from MDN Docs for undefined,
One reason to use typeof is that it does not throw an error if the
variable has not been defined.
// x has not been defined before
if (typeof x === 'undefined') { // evaluates to true without errors
// these statements execute
}
if(x === undefined){ // throws a ReferenceError
}
However, this kind of technique should be avoided. JavaScript is a statically scoped language, so knowing if a variable is defined can be
read by seeing whether it is defined in an enclosing context. The only
exception is the global scope, but the global scope is bound to the
global object, so checking the existence of a variable in the global
context can be done by checking the existence of a property on the
global object (using the in operator, for instance).
From the same document's void section
var x;
if (x === void 0) {
// these statements execute
}
// y has not been defined before
if (y === void 0) {
// throws a ReferenceError (in contrast to `typeof`)
}
Conclusion
So, when you use typeof to check if the variable's value is undefined, it will not throw an exception. But direct comparison with undefined or comparison with void 0 will throw an exception.

Related

How can I check if a variable exists (at all) in JS? [duplicate]

This question already has answers here:
JavaScript check if variable exists (is defined/initialized)
(32 answers)
Closed 3 years ago.
Please read the question before marking duplicate. This isn't about an undefined variable. It's about variables which don't exist in the namespace.
I'm working on a codebase which is run in browser and in nativescript. The globals differ between the two. For instance, I'd like to check if window exists at all, but something like this:
if (!!window) {
}
will throw an error:
JS ERROR ReferenceError: Can't find variable: window
Is there a way to test whether or not a variable exists in js (not just undefined)?
You could use a try/catch statement.
try {
if (!!someVariable) {
console.log('yep');
}
} catch {
console.log('nope');
}
You need to use the typeof operator to see if a variable exist or no
you need to test if the variable you are concerned with is undefined of null like so :
if (typeof variable === 'undefined' || variable === null) {
// variable does not exist
}

JavaScript: what does "void 0" mean? [duplicate]

This question already has answers here:
What does `void 0` mean? [duplicate]
(3 answers)
Closed 6 years ago.
TypeScript transpiles certain code into this:
Animal.prototype.move = function (distanceInMeters) {
if (distanceInMeters === void 0) { distanceInMeters = 0; }
...
What's void 0? Is that the same trick as used for links void(0)? Why is not undefined used instead?
The void operator always evaluates as the undefined value.
The undefined variable, which defaults to holding the undefined value, can be overwritten.
The void operator evaluates the given expression and then returns undefined.
The void operator is often used merely to obtain the undefined primitive value, usually using “void(0)” (which is equivalent to “void 0”). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).

Why is the difference between the compiled javascript while using question mark operator [duplicate]

This question already has answers here:
How do I use the CoffeeScript existential operator to check some object properties for undefined?
(3 answers)
Closed 9 years ago.
Without #
alert("Even Number") if even?
Corresponding Javascript
if (typeof even !== "undefined" && even !== null) {
alert("Even Number");
}
With #
alert("Even Number") if #even?
Corresponding Javascript
if (this.even != null) {
alert("Even Number");
}
I want the check for undefined when I use the this operator along with ? Am I missing something?
Coffeecript is just being smart. The trick here is that comparing to null with != checks for undefined as well. You don't need to check for existence of the variable because this is already an object, and you can check if a property exists by just using a regular lookup like if (this.prop), but that would fail if the value is falsy (false, empty string, etc...), that's why you need the check for undefined or null which would be written like:
if (this.prop !== undefined && this.prop !== null)
But taking advantage of type casting we can use != to simplify:
if (this.prop != null) // checks null and undefined
Because null == undefined but null !== undefined.
If you refer to an undefined variable, JS throws a ReferenceError. If you refer to an undefined object member, you get undefined. That is why you don't need to check if the object member exists before testing it against null.
Consider:
var obj = {};
if( obj.foo != null ) { // this is fine because `obj.foo` is `undefined`
// ...
}
if( foo != null ) { // ReferenceError, script execution halts
// ...
}
In other words there is no need to safeguard against the object member not existing so CoffeeScript doesn't do it. You have to do it manually if you want to specifically check for the member not existing at all.

typeof a === 'undefined' [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
variable === undefined vs. typeof variable === “undefined”
Assuming that undefined has not been tampered with, are the following equivalent?
typeof a === 'undefined'
and
a === undefined
?
[The reason I ask is because the author of Parsley.js seems to love writing 'undefined' !== typeof someExpression.]
These two approaches are almost the same, except one: typeof won't raise ReferenceError: a is not defined in case if a variable was not defined as a variable.
Say, typeof approach is just more fool-proof.
Yes they are equivalent if undefined has not been tampered with. The only reason typeof is preferred over direct comparison with undefined is because undefined can be redefined to be anything else like undefined = 5. Also as pointed out by VisioN a can raise a ReferenceError when your not checking in the context of function parameter but rather whether a is defined globally. In order to not get a ReferenceError when comparing directly to undefined in the global context you need to perform:
window.a === undefined

How can I determine if a JavaScript variable is defined in a page? [duplicate]

This question already has answers here:
JavaScript check if variable exists (is defined/initialized)
(32 answers)
Closed 8 years ago.
How can i check in JavaScript if a variable is defined in a page? Suppose I want to check if a variable named "x" is defined in a page, if I do if(x != null), it gives me an error.
I got it to work using if (typeof(x) != "undefined")
To avoid accidental assignment, I make a habit of reversing the order of the conditional expression:
if ('undefined' !== typeof x) {
The typeof operator, unlike the other operators, doens't throws a ReferenceError exception when used with an undeclared symbol, so its safe to use...
if (typeof a != "undefined") {
a();
}
You can do that with:
if (window.x !== undefined) {
// You code here
}
As others have mentioned, the typeof operator can evaluate even an undeclared identifier without throwing an error.
alert (typeof sdgfsdgsd);
Will show "undefined," where something like
alert (sdgfsdgsd);
will throw a ReferenceError.
Assuming your function or variable is defined in the typical "global" (see: window's) scope, I much prefer:
if (window.a != null) {
a();
}
or even the following, if you're checking for a function's existence:
if (window.a) a();
try to use undefined
if (x !== undefined)
This is how checks for specific Browser features are done.

Categories