This question already has answers here:
What does `void 0` mean? [duplicate]
(3 answers)
Closed 8 years ago.
I have been reading the javascript source of my company project and came across this
if (options.parse === void 0) options.parse = true;
Not sure what 0 does here?
The void operator is very interesting: It accepts an operand, evaluates it, and then the result of the expression is undefined. So the 0 isn't extraneous, because the void operator requires an operand.
People use void 0 sometimes to avoid the fact that the undefined symbol can be overridden (if you're not using strict mode). E.g.:
undefined = 42;
Separately, the undefined in one window is not === the undefined in another window.
So if you're writing a library and want to be a bit paranoid, either about people redefining undefined or that your code may be used in a multi-window situation (frames and such), you might not use the symbol undefined to check if something is undefined. The usual answer there is to use typeof whatever === "undefined", but === void 0 works (well, it may not work in the multi-window situation, depending on what you're comparing it to) and is shorter. :-)
Related
This question already has answers here:
Detecting an undefined object property
(50 answers)
Closed 3 years ago.
I had been checking for undefined values myself like:
if(variable !== 'undefined')
then I came across the following code:
if(typeof variable1 !== 'undefined' || typeof variable2 !== 'undefined')
I followed the same convention knowing it's safer when variable goes undeclared. While in my code reviews, it was pointed I could simple write:
if(variable1 || variable2)
Which of these is the most standard way to check undefined?
There are various use case as following
if (variable) is standard way to check truthiness of any variable in javascript. You can examples of what values will be truthy on Truthy | MDN Web Docs. Also, Falsy | MDN Docs
The cases where you explicitly would check for undefined is when a variable has been declared but not assigned value or explicitly assigned undefined.
In that case use if (variable !== undefined).
If you are receiving response from an API which might consist of stringified value of undefined, which you are sure of, then only do the check if (variable !== 'undefined')
This question already has answers here:
How can I determine if a variable is 'undefined' or 'null'?
(34 answers)
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Closed 3 years ago.
I currently have a variable that can be null as well as undefined. In both cases I want to leave the function:
if (myvar==null) return;
this works fine but I retrieve warnings from my IDE (VS) because == does not care about the type while === does. I am aware that == is generally be seen as bad style because of this.
Is this the exception from the rule? Should I simply ignore this warning and stick to the better readability or would the following be the recommend action?
if (myvar===null || myvar===undefined) return;
The problem is the lack of clarification.
If you're writing the code for yourself, it's fine as you know exactly what you're doing. But if a contributor find this code, they could either:
Not knowing how == works in case of null / undefined
Knowing how it works but not knowing if the use was intentional (if you actually want to check both null or undefined, or you wanted just check for null but used ==)
The code should be clear, so often you find programmers adding comments before this check to specify that yes, they know what they're doing, and yes, it was intentional.
Eventually you get tired of that and start to use myvar === null || myvar === undefined.
It's more verbose, but it's clearer, and doesn't give room to misunderstanding.
Another thing I notice is creating custom fuction for such things, e.g. isNil(myvar) but despite the verbosity I prefer checking both values.
== has very specific rules, and it normally recommended against because those rules are not intuitive. I would only condone using it if you have memorized the rules related to its behavior, as have all other devs who could possibly have to deal with your code (which most have not).
In this case, a == null returns true if a is one of null, undefined, or document.all, but not the other 4 falsely JS values (MDN, including why document.all is falsely). So unless you want it to match document.all, I would use ===.
Additionally, using === in all places adds consistency to your code.
This question already has answers here:
Null-safe property access (and conditional assignment) in ES6/2015
(11 answers)
JS checking deep object property existence [duplicate]
(2 answers)
Closed 6 years ago.
I dont know if a.b is set. I want to do something only if a.b[0].c is true. I can do something like this:
if (a.b && a.b[0] && a.b[0].c) {
// ...
}
Is there a shortcut to check nested existence? Can I simplify this kind of condition?
I used to code golf, and one of the tricks we used is the following.
(myArray || [])[0] || 0
First, myArray || [] is evaluated, if myArray exists, this returns it, if it doesn't, then it returns an empty array. Let's say myArray isn't defined. Next, the [][0] || 0 expression gets evaluated ans because [][0] is undefined, this returns 0.
In your case it could be used the following way:
((a.b || [])[0] || {}).c || {}
This returns an empty object if something's undefined.
I'm not saying you should use this (in fact, you shouldn't), I just want to show you, that there is a smaller solution.
Update:
If tc39 gets through, then you'll have a much better solution using optional chaining:
a.b?[0]?.c
This question already has answers here:
Why don't logical operators (&& and ||) always return a boolean result?
(9 answers)
Closed 7 years ago.
I just ran across this code
var someBool = !!(o.a && o.a.t);
I was about to remove the double-negation, then realized it forces someBool to be a boolean value... Looking on the MDN, I find this example
a5 = "Cat" && "Dog"; // t && t returns "Dog"
This seems atypical based on my experience in other languages. I'd expect the logical and operation to always return a boolean value. Can anyone explain why this use case is supported in Javascript?
Also, is the code that sent me in this direction the best way to force a bool around logical and? I'm aware of new Boolean, but that doesn't return a primitive type like the double-negation, so perhaps that's the way to go?
The && and || operators have an effect similar to boolean AND and OR, but they don't affect the expression value. The expressions are evaluated and the values tested with the JavaScript "truthiness" rules, but the overall expression value is that of the actual operand expressions (well, one of them).
Yes, that's different from C and Java and etc. JavaScript is a different language with its own rules.
The Boolean constructor can be called without new to perform a "truthiness" test and return a boolean primitive. Using !! is fairly idiomatic however.
This question already has answers here:
JavaScript `undefined` vs `void 0`
(4 answers)
Closed 9 years ago.
Should I use void 0 or undefined in JavaScript to unassign a value, for example:
event.returnValue = void 0;
or
event.returnValue = undefined;
If you are using a modern browser, (which supports JavaScript 1.8.5) using undefined and void 0 would most likely yield the same result (since undefined is made not writable), except that the void can accept an expression as parameter and evaluate it.
In older browsers, (which do not support JavaScript 1.8.5) it is better to use void 0. Look at this example:
console.log(undefined);
var undefined = 1;
console.log(undefined);
It will print
1
undefined is actually a global property - it's not a keyword. So, undefined can be changed, where as void is an operator, which cannot be overridden in JavaScript and always returns the value undefined. Just check this answer which I gave earlier today for a similar question, Why does void in Javascript require an argument?.
Conclusion:
So, if you are concerned about compatibility, it is better to go with void 0.
"void 0" is safer. "undefined" is a value, like any other. It's possible to overwrite that value with another:
undefined = 3;
That would change the meaning of your event.returnValue had you used undefined. "void" is a keyword, though, and its meaning can't be changed. "void 0" will always give the value 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).
https://stackoverflow.com/a/1291950/2876804
Just use undefined, since they will both evaluate to it.