Why does 1 && 2 return 2? - javascript

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.

Related

Why 0 && true echo 0 in js?

As title
As I know
(if this part is true) && (this part will execute)
if(condition){
(this part will execute)
}
0 is false, so why not echo false but 0?
Because operator && return first falsey element otherwise they return last element
1 && 0 && false // 0
1 && 2 && 3 // 3
From 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.
expr1 || expr2 -- Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true.
!expr -- Returns false if its single operand can be converted to true; otherwise, returns true.
Some expressions that can be converted to false are:
null
NaN
0
empty string("" or '' or ``)
undefined
Short-circuit evaluation
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
false && (anything) is short-circuit evaluated to false.
true || (anything) is short-circuit evaluated to true.
The JavaScript documentation of logical operators explains:
Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
In javascript all except for null, undefined, false, 0, and NaN are Truthy.
In your case, why not echo false but 0?.
Javascript's ToBoolean function evaluates it to the first falsey value. i.e,
0 && true
=> 0
true && undefined
=> undefined
null && undefined
=> null
And if you need either strictly true or false, then go for not-not i.e, !!.
!!0 && true
=> false
!!true && undefined
=> false
!!null && undefined
=> false
(something falsy) && (anything) will always return false.
Also 0 is falsy and '0' (a non empty string) is truthy
a && b is equivalent to
if (a) {
return b;
} else {
return a;
}
So in your case a equals to 0, which is falsy, therefore you get a.
Unlike other languages, JavaScript does not return true or false on && and ||, it returns the first truthy operand for a || operator, or the last one, and the first falsy operand for the && operator, or the last one.
You can find more info here.
For && operator comparing with false is always FALSE.
0 && false => 0
false && 0 => false
for better understanding :-
In case of && operator (always start from left-right), when you get the value 0 (false) it will print 0(false); if start with false it will directly print false. it won't check the second operand when get false.
but in case
true && 1 => 1
1 && true => true
as it has to check till end and ultimately give the end operand as result if won't get false.
For || operator comparing with true is always TRUE.
1 || true => 1
true || 1 => true
for better understanding :-
In case of || operator (always start from left-right), when you get the value 1 (true) it will print 1(true).
Starting with true it will directly print true. it won't check the second operand when get true.
but in case
false || 1 => 1
0 || true => true

why the value of console.log(1 && 2) is 2 instead of true or 1 in javascript? [duplicate]

This question already has answers here:
Why don't logical operators (&& and ||) always return a boolean result?
(9 answers)
Closed 4 years ago.
I had checked for many test cases. It's looking if the first value is true and it's returning the second value.
Example:
2 && 5 // --> 5
5 && 10 // --> 10
0 && 2 // --> 0
Why doesn't it return either True or 1?
Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Description,
Operator: Logical AND (&&)
Usage: 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.
The && operator will return the last value if all other values are truthy, otherwise it will return the first non truthy value. So, as in 0 && 2, 0 is non-truthy, that gets returned.

Why does JavaScript choose the larger number in non-boolean && statements?

in JavaScript, 0 && 1 evaluates to 0, which is the lower of the two. Why, then, does 0.1 && 1 evaluate to 1, which is the higher of the two?
Similarly, why does 0 || 1 evaluate to 1, but 0.1 || 1 evaluate to 0.1
It has nothing to do with which value is larger, the operators will return the appropriate value for the spec.
In the case of && if the first parameter is false, it will be returned. Otherwise the second is returned. In your example 0.1 && 1, 0.1 is a truth-y value so 1 is returned. You could just as easily try 100000000 && 0.1 and see that 0.1 is returned. The reason that 0 && 1 returns 0 is because 0 is false-y so, per the spec, the first value gets returned.
Likewise, with || if the first parameter is true, it will be returned. Otherwise the second is returned.
You should check this out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators.
Basically the && will take the first of the two if it is falsey otherwise it will take the second.
The opposite is true for ||.
The && and || operators do not return values based on inequalities such as < or >.
a && b works as:
if (a) {
return b;
}
else {
return a;
}
a || b works as:
if (a) {
return a;
}
else {
return b;
}
The if statements are based on the concept of "truthy" and "falsey" values, where 0, NaN, null, undefined, '', and false are all "falsey". All other values are "truthy".
0 && 1 evaluates to 0 because 0 is falsey.
0.1 && 1 evaluates to 1 because 0.1 is truthy.
There are several different things going on:
0 is bitwise false, and any number other than 0 evaluates to true, so the expression 0 && 1 evaluates to false && true, which is of course false.
1 is bitwise true, and as per above any number <> 0 also evaluates to true, so 0.1 && 1 evaluates to true && true, which is true.
Using the information above:
0 || 1 evaluates to false || true, which is true
The final example is perhaps the most interesting one, and it has to do with operator short-circuiting.
The logical or operator (||) short-circuits, or stops evaluating, as soon as it encounters a value that evaluates to true. Thus, if you are using logical or in an assignment operation, it will return the first true value in the expression.
Thus, 0.1 || 1 returns 0.1. But, if you were to evaluate 1 || 0.1, it would instead return 1.
As a related aside, the logical and operator (&&) will short-circuit as soon as it encounters a value that evaluates to false.
You're specifically discussing logical operators, which actually do not care about the numbers themselves. Your code could be rewritten as
0 && 1 - false && true
0.1 && 1 - true && true
0 || 1 - false || true
0.1 || 1 - true || true
I assume you're setting this to a variable like x or something. When you set it, the variable is being assigned as the first portion of the test that "fully" passes.
So, your cases above work like this:
The result is 0 because the test fails at 0 (0 && anything will fail).
The result is 1 because the test "fully" passes after checking the right-hand side of the equation. It checks that 0.1 is "truthy" and then checks that 1 is "truthy" and returns 1 since that was the last piece checked.
The result is 1 because the boolean logic checks 0 first, and then says "or 1". The "or 1" piece passes, so it returns 1.
The result is 0.1 because that is "truthy" and it doesn't need to check the second side of the equation.
Since this has nothing to do with the size of the numbers, just whether or not they are 0 or not 0, you can actually show this more clearly with using something like the following:
0 && -1 - false && true
0.1 && -2 - true && true
0 || -3 - false || true
0.1 || -4 - true || true

How does the OR operator work in this javascript?

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.

What's the difference between ( | ) and ( || )?

What's the difference between | and || in Javascript?
Furthermore, what's the difference between & and &&?
| is a bitwise or, || is a logical or.
A bitwise or takes the two numbers and compares them on a bit-by-bit basis, producing a new integer which combines the 1 bits from both inputs. So 0101 | 1010 would produce 1111.
A logical or || checks for the "truthiness" of a value (depends on the type, for integers 0 is false and non-zero is true). It evaluates the statement left to right, and returns the first value which is truthy. So 0101 || 1010 would return 0101 which is truthy, therefore the whole statement is said to be true.
The same type of logic applies for & vs &&. 0101 & 1010 = 0000. However 0101 && 1010 evaluates to 1010 (&& returns the last truthy value so long as both operands are truthy).
& is the bitwise AND operator
| is the bitwise OR operator
&& is the logical AND operator
|| is the logical OR operator
The difference is that logical operators only consider each input at face value, treating them as whole, while bitwise operators work at the bit level:
var thetruth = false;
var therest = true;
var theuniverse = thetruth && therest; //false
var theparallel = thetruth && thetruth; //true
var theindifferent = thetruth || therest; //true
var theideal = thetruth || thetruth; // false
var thematrix = 5346908590;
var mrsmith = 2354656767;
var theoracle = thematrix & mrsmith; //202445230
var theone = thematrix | mrsmith; //7499120127
Another difference is that || uses shortcut evaluation. That is, it only evaluates the right side if the left side is false (or gets converted to false in a boolean context, e.g. 0, "", null, etc.). Similarly, && only evaluates the right side if the left side is true (or non-zero, non-empty string, an object, etc.). | and & always evaluate both sides because the result depends on the exact bits in each value.
The reasoning is that for ||, if either side is true, the whole expression is true, so there's no need to evaluate any further. && is the same but reversed.
The exact logic for || is that if the left hand side is "truthy", return that value (note that it is not converted to a boolean), otherwise, evaluate and return the right hand side. For &&, if the left hand side is "falsey", return it, otherwise evaluate and return the right hand side.
Here are some examples:
false && console.log("Nothing happens here");
true || console.log("Or here");
false || console.log("This DOES get logged");
"foo" && console.log("So does this");
if (obj && obj.property) // make sure obj is not null before accessing a property
To explain a little more in layman's terms:
&& and || are logical operators. This means they're used for logical comparison;
if (a == 4 && b == 5)
This means "If a equals to four AND b equals to five"
| and & are bitwise operators. They operate on bits in a specific fashion which the wiki article explains in detail:
http://en.wikipedia.org/wiki/Bitwise_operation
In Javascript perspective, there is more to it.
var a = 42;
var b = "abc";
var c = null;
a || b; // 42
a && b; // "abc"
c || b; // "abc"
c && b; // null
Both || and && operators perform a boolean test on the first operand (a or c). If the operand is not already boolean (as it's not, here), a normal ToBoolean coercion occurs, so that the test can be performed.
For the || operator, if the test is true, the || expression results in the value of the first operand (a or c). If the test is false, the || expression results in the value of the second operand (b).
Inversely, for the && operator, if the test is true, the && expression results in the value of the second operand (b). If the test is false, the && expression results in the value of the first operand (a or c).
The result of a || or && expression is always the underlying value of one of the operands, not the (possibly coerced) result of the test. In c && b, c is null, and thus falsy. But the && expression itself results in null (the value in c), not in the coerced false used in the test.
Single | is bit wise OR operator .
If you do 2 | 3 , it converts to binary and performs OR operation.
01
11
Results in 11 equal to 3.
Where as || operator checks if first argument is true, if it is true it returns else it goes to other operator.
2 || 3 returns 2 since 2 is true.
one more point i want to add is || operator is used to assign default value in case the value you are assigning is undefined. So for Exapmle you are assigning a obj to some object test and if you dont want test to be undefined then you can do the following to ensure that value of test wont be undefined.
var test = obj || {};
so in case obj is undefined then test's value will be empty object.
So it is also being used for assigning default value to your object.

Categories