Should I use `void 0` or `undefined` in JavaScript [duplicate] - javascript

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.

Related

Is !!!foo the same as !foo? [duplicate]

This question already has answers here:
The use of the triple exclamation mark
(4 answers)
What is an exclamation point in JavaScript?
(2 answers)
Closed 3 years ago.
Knowing that !!foo gives you the Boolean value of foo, I have seen some programmers say that it's better to use !!!foo instead of !foo because you are changing it to its Boolean value first and then negating the value.
So my question is,
Is !!!foo always equals !foo? (!!!foo === !foo)
Yup. Just for clarity:
!!x === x is not generally true, but it is true if x is already a boolean: "not (not true)" is true, and "not (not false)" is false.
!foo is always a boolean; if foo is truthy, it's false, otherwise it's true.
So if you substitute !foo in for x you get that !!(!foo) === (!foo) is always true. Removing the parentheses doesn't change the meaning, so !!!foo === !foo is always true.
Which means there's no good reason to write !!!foo in actual code. Just use !foo instead.
I've never seen !!!foo used in actual code, but yes, they are always strictly equal.
The extra two exclamation marks just negate the boolean value twice, which always gives the same result.
If foo is set as boolean then !foo will be equal to !!!foo , See the example and screenshot given below
var foo = true;
console.log('foo => '+foo);
console.log('!foo => '+!foo);
console.log('!!foo => '+!!foo);
console.log('!!!foo => '+!!!foo);
console.log('!!!!foo => '+!!!!foo);
if(!!!foo === !foo){
console.log("Equals");
}else{
console.log("Not Equals");
}
While you are correct, !!!foo would equal to !foo, I've never seen JS script using !!!foo before, and I can't think of a good reason to do that. You're gonna create code smell if you write this in your own code.
In other words, don't do that.

Javascript - succinct way to assign another value to variable if first value is not truthy [duplicate]

This question already has answers here:
Is there a "null coalescing" operator in JavaScript?
(19 answers)
Closed 4 years ago.
I have a function that may return a value or may return null and I want to assign it to a variable. So at the moment I've got
someVar = (someFun())
? someFun()
: "foo";
Is there a shorterer way of doing it, where I don't have to call the function twice, or add an extra variable like:
funResult = someFun();
someVar = (funResult)
? funResult
: "foo";
Basically, something like:
someVar = someFun() | "foo"
The idiomatic way is
someVar = someFun() || "foo";
The || operator will yield the value of the left-hand expression if it's truthy. If not, it will move on to evaluate the right-hand side, and return its value.
For those unfamiliar with the term "truthy", in JavaScript it means values that are not considered by the language to be implicitly false. The implicitly false values are 0, NaN, false (of course), "", null, and undefined. Any reference to an object, even if it's completely empty, is considered to be "truthy".
In your specific example, the || approach is to be preferred because it means you only call someFun() once.

Why does Javascript cast null to string at variable assignment? [duplicate]

This question already has answers here:
Using the variable "name" doesn't work with a JS object
(4 answers)
Closed 6 years ago.
In Firefox 45 on OSX, when I fetch an item from localStorage from a key that does not exist, the function call returns null. I tested this in the console.
If I instead assign the call result to a variable, and print its value in the console, I get "null", i.e. a string.
Why does a variable assignment of a previously not defined variable cast a call result to a String?
Used code (in the console):
localStorage.getItem("non-existing-key"); // returns null
var x = localStorage.getItem("non-existing-key");
x // returns "null"
Edit: both versions seem to behave correctly on Chrome 50.0.2661.86 on OSX (both return null)
Edit2: my mistake. I used another variable name in my tests (specifically: var name). Now, if I let the console return the value of the variable name, it returns window.name, which is a property of window of the type String, defaulting to "null". So, it's not an assignment that causes a cast, but instead its that I got a String property defined by window.
I made a mistake. The specific code I used was the following:
var name = localStorage.getItem("non-existing-key");
name
Now, getItem does return null and not a String. What then happens is that by letting the console print the value of name it does in fact get window.name (see window.name on MDN), which by default is "null" (a String).

Why is the !! preferable in checking if an object is true? [duplicate]

This question already has answers here:
What is the difference between if(!!condition) and if(condition)
(3 answers)
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 8 years ago.
Some JavaScript examples use !! to check if an object is available
// Check to see if Web Workers are supported
if (!!window.Worker) {
// Yes, I can delegate the boring stuff!
}
Why is this preferred to just if (window,Worker) and in what context would this fail?
It isn't preferable, or even different, in this case. The double-bang converts the variable that follows it into a Boolean value (similar to wrapping in the Boolean() constructor). Gets around potential problems with truthy and falsey variables.
However, putting the variable alone in an if() clause does the same thing (it also resolves the contents of the if's parens to a hard Boolean).
The double-bang can prove helpful in other cases, such as if you want to return a true or false at the end of a function based on a variable's truthiness/falsiness. That would be rather than:
if(condition) {
return true;
} else {
return false;
}
You could simply write:
return !!condition;
It isn't.
!! is useful when you are passing an object into a function that (like jQuery's toggle()) checks to see if its argument is a boolean, or when the function might stash its argument and thereby prevent the object from being collected.
The case you cite is neither of those. Use a bare if.
In the condition of an if statement both versions will do the same thing and its a stylistic choice. Some people prefer use !! to highlight that Worker is not a boolean and is being converted tto boolean.

Javascript: What is additional Zero in the if syntax? [duplicate]

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. :-)

Categories

Resources