In JavaScript, is it possible to place a Conditional statement after an Or operator? If so, why is the following fails for me?
var value = 1 || true ? 2 : 3; // equals to 2
When I set value to be equals to [1 || true ? 2 : 3], I get an unexpected result.
The result that get is that:
value == 2
I've expected value to be equals to 1 (value= = 1), since 1 is truthy, and the Or statement should have return 1. The conditional statement is not even supposed to be executed.
The only way val can be equals to 2 (val == 2) is if the Or operator is behaving not as expected, and runs the second part of the Or statement and the Conditional statement that is in it.
Why is it behaving that way?
I've expected value to be equals to 1 (value = 1), since 1 is truthy
To get that, you need parens:
var value = 1 || (true ? 2 : 3);
// --------------^------------^
Without them, the || is between 1 and true, and then the conditional operator's first operand is the result of that (which is 1).
This is because || has higher precedence than the conditional operator (just); here's a table on MDN.
Because Logical OR has precedence over the Conditional operator. Then your statement is actually interpreted as:
(1 || true) ? 2 : 3;
Which obviously evaluates to 2.
See MDN
Related
Why does the expression 1 && 2 evaluate as 2?
console.log("1 && 2 = " + (1 && 2));
&& (and operator) returns the last (right-side) value as long as the chain is "truthy".
if you would try 0 && 2 -> the result would be 0 (which is "falsy")
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators
According to MDN:
expr1 && expr2 returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
Because 1 can be evaluated to true, 1 && 2 returns 2.
According to this page:
Why 1 && 2 == 2
AND returns the first falsy value or the last value if none were found.
OR returns the first truthy one.
For multiple operators in same statement:
precedence of the AND && operator is higher than OR ||, so it executes before OR.
alert( 5 || 1 && 0 ); // 5
Because its and, all the values need to be evaluated only up to the first 0, and the value of the last evaluation is returned, and it's the last one.
Although not directly relevant here, note that there's a difference between bitwise and logical operators. The former tests bits that are the same and only return those, the latter reduces to only true (!=0) or false (=0), so contrary to intuition, bitwise AND and AND are not interchangable unless the values are exactly 0 or 1.
I am getting different outputs for the following code. please tell me the difference
var y = 1;
var c = "anything";
var d = 5;
console.log(y == 1 && "anything"); // Output is anything
console.log( "anything" && y == 1 ); // Output is true
&& and || are surprisingly powerful in JavaScript as compared to some other languages: They don't necessarily return a boolean.
&& evaluates its first operand and, if that's falsy*, uses that as its return value; if the first operand evalutes truthy*, && evaluates its second operand and uses that as its result value. In your y == 1 && "anything", since y == 1 is true (which is, of course, truthy), the result is the result of evaluating "anything" (which is "anything"). In your "anything" && y == 1, "anything" is truthy, and so the result is the result of evaluating y == 1 (which is true).
|| works in a similar manner: It evaluates its first operand and, if that's truthy, uses that as its result value; otherwise, || evaluates its second operand uses uses that as its result value.
* falsy and truthy:
falsy - A value that coerces to false when used as a boolean. The falsy values are: "", 0, NaN, null, undefined, and of course, false. (On browsers, document.all is also falsy, for complicated reasons. If you're really curious, I cover it in Chapter 17 of my book JavaScript: The New Toys. Links in my profile if you're interested.)
truthy - A value that coerces to true when used as a boolean. Any non-falsy value is truthy, incl. "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays, and empty objects.
In the condition portion of the following ternary statement, does playlist.length equal playlist.length >= 1 ?
var playlist = ["video1", "video2", "video3", "video4", "video5"];
// some code here
alert ((playlist.length) ?
playlist.length + "video(s) remain in the playlist: " + playlist.join (", ") + "."
: "No videos remain in the playlist");
Likewise, in the following snippet of code, does ! playlist.length equal playlist.length === 0 ?
alert ((! playlist.length) ?
"No videos in the playlist."
: playlist.length + " video(s) remain in the playlist: " + playlist.join(", ") + ".");
This is the first time I've seen an example where the condition portion of a ternary or if statement does not include such a notation as === or >=. So I'm not sure how to interpret this.
0 is implicitly converted to false in boolean comparisons in JavaScript. So when the length is 0, that is false. Conversely, any other number is implicitly converted to true in boolean comparisons in JavaScript. So when the length is anything but 0 it is true.
An easy test is to use !! to see the "truthy" value
!!1 === true
!!0 === false
!!6 === true
The part to the left of the ? is simply evaluated for "truthiness". The value 0 is "falsy" so evaluates as false for the purposes of the test. Numeric values other than 0 are "truish" and therefore for this purpose evaluate to true.
All other behaviors of the ternary are the same.
The === and !== simply add the additional constraint that the L-value and R-value must also be the same type.
The two are very similar: !playlist.length and playlist.length === 0.
However, they are not exacty the same. In fact, here:
var playlist1 = [];
var playlist2 = {};
!playlist1.length // true
!playlist2.length // true
playlist1.length === 0 // true
playlist1.length === 0 // false
In that sense !playlist.length also can be used on all kinds of objects, not just arrays.
In any case, when using this on an array, it is a way to check if the array is empty, and works as you have suggested, the same as playlist.length === 0.
In javascript 0 equals false, and any other number value equals true, but if you use === it compare value types too.
Given a number the program should return a sequence of operations using only *3 or +5 to get to the number, thus there are two paths to take. How do this program know which function call to make when it calls itself? And how does it know how many times to call each path. In other words I dont understand how the OR operator is being used to determine which call to find() to use and how many of each.
function findSequence(goal) {
// we start at 1, and history is a string that will keep track of the operations
function find(start, history) {
// case when start and goal is 1.
if (start == goal)
return history; // return string containg 1
// case when we build start past what we needed
else if (start > goal)
return null;
else
// Dont understand this part!
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
document.write(findSequence(13));
The || operator checks the truth value of the left operand. Interestingly, the || expression does not evaluate to true or false. If the truth value is true, the expression evaluates to that left operand. If it is not, then it evaluates to the right operand. Example:
> 5 || 10
5
> 5 || 0
5
> 0 || 10
10
> 0 || undefined
undefined
Thus a || b is actually equivalent to a ? a : b. Similarly, a && b is actually equivalent to a ? b : a:
> 0 && 10
0
> 0 && undefined
0
> 5 && 10
10
> 5 && undefined
undefined
Truth value for non-boolean values is determined in the JavaScript specification:
Undefined -> False
Null -> False
String -> False if empty string, True otherwise
Object > True
EDIT: Oh, as mattedgod points out, as soon as the expression evaluates to a result, the rest of the expression does not get evaluated at all. For example:
> function fail() { throw "I failed!"; }
> fail()
XXX "I failed!"
> 5 || fail()
5
> 0 && fail()
0
No failure happens in the above cases, but in the following they do:
> 0 || fail()
XXX "I failed!"
> 5 && fail()
XXX "I failed!"
Thus, if you have two calls to find() like find(...) || find(...), if the result of the first call has a true truth value, then its result will be returned and the second one won't execute at all. If the result of the first call has a false truth value, then the second call will execute and the expression evaluates to whatever that result is.
This is relying on a property of JavaScript (and many other languages) called "short-circuiting."
If you think about it, if you are evaluating something to be true and it is A || B, if A is true, then the whole expression will be true, there's no sense checking B. The opposite is true for &&, if A is false and you are evaluating A && B, the whole expression is false so no sense to bother with B.
In your example, if the first call to find succeeds, it will not execute the second one. However, if the first call does not succeed (I am guessing it returns false or null or something that evaluates to JS false), the second call will get executed.
This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
Closed 7 years ago.
Taken from a box2djs sample.
I'm trying to understand the library, but I do not understand the line:
ballSd.radius = rad || 10;
what does it mean?
Here's the full definition
createBall2 = function(world, x, y, rad, fixed) {
var ballSd = new b2CircleDef();
if (!fixed) ballSd.density = 1.0;
// what does the next line do?
ballSd.radius = rad || 10;
ballSd.restitution = 0.2;
var ballBd = new b2BodyDef();
ballBd.AddShape(ballSd);
ballBd.position.Set(x,y);
return world.CreateBody(ballBd);
};
ballSd.radius = rad || 10;
means: if rad == true (or truthy) return the value of rad, otherwise return 10
A boolean expression in JavaScript does not return false or true†, but the first operand (from left to right) that determines the outcome of the expression.
When using logical OR ||, this is the first operand that evaluates to true (similarly the first operand that evaluates to false for &&).
As others already noted, if rad evaluates to false (e.g. if it is 0), then the second operand is returned.
This "trick" is often used to set a default value.
Read more about logical operators.
†: That is only 66.6% correct. The NOT operator ! will always return a boolean value.
All the answers are correct, but they are missing an explanation of the && and || operators in JavaScript. The trick is that they don't return a boolean, they return the value where the comparison short-circuited.
For example
// Returns the first truthy value (2) since after looking at 0 and 2, we already
// know the expression is true and we don't need to evaluate the last component (3)
alert (0 || 2 || 3)
// Returns the first falsy value (""), the comparison doesn't even
// evaluate "Hello" and "Dog"
alert( "" && "Hello" && "Dog" );
// No short circuiting, so the last value ("fun") is returned
alert( "string" && "fun" )
if rad is false or 0, set ballSd.radius to 10
Set the circle radius to either the given argument "rad" if it was given and bigger than zero otherwise to 10, which makes it the default radius.
see this... so if the value of rad variable converted to a boolean is true, then the rad is returned, otherwise it will return 10;
any variable can be converted to a boolean value:
null, 0, undefined will be converted to false;
not undefined will be converted to true;
see implicit boolean conversions in javascript