1 && 0 && false // 0
1 && 2 && 3 // 3
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:
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.
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
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
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 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
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.