typeof a === 'undefined' [duplicate] - javascript

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

Related

Preferred way to check object property is `null` or `undefined` [duplicate]

This question already has answers here:
Detecting an undefined object property
(50 answers)
Closed 5 years ago.
If I have some object that has a property that may or may not exist, is there a preferred way to check for its' existence?
// Good?
(someObj.property !== undefined && someObj.property !== null)
// Better?
(typeof someObj.property !== 'undefined')
// Best?
(someObj.property != null)
*The last != operator is on purpose:
Strict equality checks (===) must be used in favor of abstract equality checks (==). The only exception is when checking for undefined and null by way of null. The use of == null is also acceptable in cases where only one of null or undefined may be logically encountered, such as uninitialized variables.
I reckon you'd use obj.hasOwnProperty(prop)
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Undefined checking on variable practice [duplicate]

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.

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.

How do I check if an element is undefined? [duplicate]

This question already has answers here:
Detecting an undefined object property
(50 answers)
How can I determine if a variable is 'undefined' or 'null'?
(34 answers)
Closed 9 years ago.
I would like to check to see if a particular attribute of a DOM element is undefined - how do I do that?
I tried something like this:
if (marcamillion == undefined) {
console.log("Marcamillion is an undefined variable.");
}
ReferenceError: marcamillion is not defined
As you can see, the reference error is telling me that the variable is not defined, but my if check is clearly not working, because it is producing the standard js ReferenceError as opposed to the error message I am looking for in my console.log.
Edit 1
Or better yet, if I am trying to determine if the attribute of an element is undefined like this:
$(this).attr('value')
What would be the best way to determine if that is undefined?
Using typeof:
if (typeof marcamillion == 'undefined') {
console.log("Marcamillion is an undefined variable.");
}
Edit for the second question:
if ($(this).attr('value')) {
// code
}
else {
console.log('nope.')
}
if (typeof marcamillion === 'undefined') {
console.log("Marcamillion is an undefined variable.");
}
Note that using === instead of == is considered better style.

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