what does the "||" in a var statement mean? [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
null coalescing operator for javascript?
What does “options = options || {}” mean in Javascript?
Can someone explain me this expression? I stumbled accros the javascript line of code and I wondered what it means.
var node = element.node || element[element.length - 1].node;
node get's used like this below:
if (node.nextSibling) {
node.parentNode.insertBefore(this.node, node.nextSibling);
} else {
node.parentNode[appendChild](this.node);
}
At first i though node should be a boolean or something but it's not.
Am I correct if i think that the meaning is: node is element.node but if the node attribute is undefined node is the last element in the array of element?

Your understanding is along the right lines; be aware that even if element.node is defined, but is a falsey value (0, false etc.) that element[element.length - 1].node will be assigned to node instead.

It means, if element.node has a value represents True in boolean expressions, node will be element.node, otherwise it will be element[element.length - 1].node

Simple answer: it means OR :)
Reference: http://www.w3schools.com/js/js_operators.asp

It means OR
for example:
if this || that
means "if this or that"
So when the computer comes to the "||" part of your code, if the statement before it is true, it will stop reading that if statement and automatically execute the code underneath.
If the item before that "||" is false, then it will check the next one, and so on...

Related

Order of statement evaluation [duplicate]

This question already has answers here:
Does JavaScript have "Short-circuit" evaluation?
(3 answers)
Closed 5 years ago.
I have this code
if (!caught.includes("AreYouHuman") && !caught.includes("pfail=1") && caught.includes("Episode") && caught.includes("Anime")) {
var arraystring = caught.split("&s");
var updating = chrome.tabs.update({url: arraystring[0] + "&s=beta&pfail=1"});
}
"caught" is a URL which I get from the browser.
1)would JavaScript stop at the first false statement it counters ( assuming that it iterates over them linearly ( AreYouHuman --> pfail=1 --> Episode -->Anime)).
2)or does it evaluate all of the statements at once then decide whether the whole thing is true or false ?
Assuming that 1) is the correct option, placing the least likely condition to be true,on the first position, would theoretically increase my code execution speed right ?
About the "duplicate" flag non-veteran programmers (like me) won't know "Short-circuit” and probably are not looking for the difference between "&" and "&&", there search would be how does javascript evaluate booleans in an "if statement"
Because you are using the short-circuit logical AND operator &&, yes, the entire expression will return false when the first of the expressions fails.
If, however, you were using a single &, then it would be a bitwise operator not be short-circuited and would continue to test the remaining conditions even if one were to return false.
The conditions are tested according to order of operations, but barring any grouping operators, the expression is evaluated left to right.
Yes, javascript interpreter stops at first false statement, from left to right. If a false value is encountered, it stops the tests, as the expression will evaluates to FALSE whatever the other values are

Is there a shortcut to check nested property existence [duplicate]

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

Double-negation + logical and in Javascript [duplicate]

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.

What does "var app = app || {};" do? [duplicate]

This question already has answers here:
What does var x = x || {} ; [duplicate]
(6 answers)
Closed 9 years ago.
Im looking at some Backbone.js examples and they have var app = app || {}; at the top of all .js files. I understand the literal meaning of this, but what does it do in reference to everything else?
Edit: you guys are really really fast.
It will define the variable app to an empty object if it is not already defined.
This works because being undefined evaluates to false in Javascript.
If it is defined, it may still be re-defined as an empty object if it has a value which evalutes to false, such as an empty string.
The || operator in javascript will return the first operand if it is "truthy". If not, it will return the second operand. If app has not been assigned, it will be undefined, which is "falsey". Thus if it is not defined or is otherwise falsey, an empty object {} will be assigned to app.
This means "define app as an empty object if it's not already defined".
The OR operator in JavaScript does not necessarily yield a boolean. If the left-hand side of the expression yields false then the assignment takes the right-hand side of the expression.
If app is already defined, the it does nothing.
If app is not defined, then it's equivalent to var app = {};

difference between if (!!variable), and, if (variable)? [duplicate]

This question already has answers here:
Can someone explain this 'double negative' trick? [duplicate]
(9 answers)
Closed 9 years ago.
Is there any difference (in JS) between using the double negative !! and not using it at all?
For example
if (!!variable){... vs. if (variable){...
I know there are times where I've gotten a warning using the 2nd method..
When should each be used? and when will each throw a warning in the console? (for variables, objects, arrays etc.)
Thanks!!
There is a difference for assigning it, but not for using it in a conditional statement. The reason the !! is used is because the first ! will convert your variable to its truthy evaluation and then not it. So "hello" becomes true, is then negated, becomes false, and the second ! will negate the false, resulting in true. This can be desirable when trying to obtain the thruthy value from a variable. However, there is not much gained by doing it in an if statement.
In this particular case, there is no difference. In fact, !!variable is wasteful.
However in more general cases, it casts the variable to a boolean. Personally I've only found this useful when debugging, and to learn what values are truthy and falsy.

Categories

Resources