Why 0 && true echo 0 in js? - javascript

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

Related

Why does this return a number instead of boolean [duplicate]

I happened to know the following code
Here is the code, and very simple:
var test = 0 || -1 ;
console.log(test);
then the output in the console is -1
and somehow i am really new into the javascript,
all i think of is that the 0 stands for Boolean False in JS ,and so || operator seems to ignore the 0 and assign the value -1 to the variable
so am i right ?
i just want a confirm
|| — expr1 || expr2 (Logical OR)
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; if both are false, returns false..
&& — expr1 && expr2 (Logical AND)
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.
All values in Javascript are either "truthy" or "falsy".
The following values are equivalent to false in conditional statements:
false
null
undefined
The empty string "" (\ '')
The number 0
The number NaN
All other values are equivalent to true.
So... var test = 0 || -1 ; returns -1.
If it was var test = 0 || false || undefined || "" || 2 || -1 it would return 2
Logical operator on MDN
You can use Nullish coalescing operator (??)
The nullish coalescing operator (??) is a logical operator that
returns its right-hand side operand when its left-hand side operand is
null or undefined, and otherwise returns its left-hand side operand.
Only null and undefined will be falsey. 0 will be considered true. But take care: an empty string will be considered true too!
console.log('0 ?? 1 ->', 0 ?? 1) // expected output: 0
console.log('null ?? 1 -> ', null ?? 1) // expected output: 1
console.log('undefined ?? 1 ->', undefined ?? 1) // expected output: 1
console.log('"" ?? 1 ->', "" ?? 1) // expected output: ""

Why does an exclamation mark before a variable return 'true' if the variable value is zero? [duplicate]

This question already has answers here:
What does "!" operator mean in javascript when it is used with a non-boolean variable?
(5 answers)
Closed 2 years ago.
I looked a lot, but I couldn't find an answer for this especific case.
Why does this expression return true?
let variable = 0
!variable // true
I understand that the ! mark checks if a value is null or undefined, but in this case variable is defined. This is tricking me.
Isn't 0 really considered a valid value?
! is known as the logical NOT operator. It reverses the boolean result of the operand (or condition)
0 is also considered as the boolean false, so when you use !variable you are using the logical operator and saying it to change the value of the variable to its opposite, that in boolean is true
0 == false == !1 == !true
1 == true == !0 == !false
in Javascript are considered false:
false, null, undefined, "", 0, NaN
are considered true:
true, 1, -0, "false". <- the last one is a not empty string, so its true
if( false || null || undefined || "" || 0 || NaN) //never enter
if( true && 1 && -1 && "false") //enter
https://developer.mozilla.org/en-US/docs/Glossary/Falsy
To quote MDN Web docs, the Logical NOT !:
Returns false if its single operand can be converted to true; otherwise, returns true
So in your case it returns true because 0 can be converted to false
You can check out this link:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

! next to a number in a conditional prints true on strict comparison

console.log(false === 0) // false
console.log(false === !1) // true, why does it equate to true using !?
and vice versa for
console.log(true === 1 ) // false
console.log(true === !0) // true
I understand the difference between equality and identity but couldn't understand this behaviour of JS . Please explain ?
The === requires that both values are the same type, no implicit coercion is performed.
When you compare a boolean to a number with triple ===, you will always get false, since they are not the same type.
But using ! in front of a number (or anything else) will convert it to Boolean first, (!x is same as !Boolean(x)) so the strict comparison can succeed. (actually, using ! on anything will coerce it to a Boolean in JS)
Rules of conversion number-to-boolean conversion :
For the number-to-boolean conversion, 0 and NaN are coerced to false, and any non-zero number is coerced to true. (FYI, null, undefined and the empty string '' are the only other falsy values in JS)
Now, you will have two boolean to compare, and === will return true or false accordingly.
So, to summarize :
in !1, 1 is non-zero, so it gets coerced to true, and !true gives false
so false === !1 is equivalent to false === false, which is a true statement.
You can work out the details for the other comparison.
As an additional resource, if you have time and are interested in learning more, I recommend the very good free ebook "You don't know JS".
Because !1 is treated as a boolean value in JS whereas 0 or 1 are interpreted as number.
You can use JS typeof !1 and typeof 0 to see the difference.
Since, false is also a boolean type, matching it with 0 (number) will result false.
Hope that clears it up.
When you do false === 0, it's comparing the boolean false to the integer 0. In contrast, when you do false === !1, javascript converts the integer 1 to a boolean and the unary ! acts as a "not" operation on what is effectively true. Since 1 is truthy in javascript, !1 converts to false. And vice-versa.
console.log(0) // 0
console.log(!0) // true
console.log(1) // 1
console.log(!1) // false
!1 is a Boolean (because of the logical NOT operator (!)).
true and false are also Boolean values.
0 is a Number.
Values of different types are never identical (===).
JavaScript will first convert your inverted numer to a boolean:
console.log(false === 0)
-> false
console.log(false === !1)
-> false === false
-> true
and vice versa for
console.log(true === 1 )
-> false
console.log(true === !0)
-> true === true
-> true
Do you understand the difference between an integer and a boolean?
console.log(false === 0) // false
console.log(false === !1) // true
console.log(true === 1 ) // false
console.log(true === !0) // true
console.log(!1) // false
console.log(!0) // true
Identity comparison checks that an object is exactly that, and 1 is not true, neither is 0 false.
Because ! operator convert any value to Boolean type and you are checking against another Boolean that's why false === !1 is giving you true.

why null is not converted to a boolean value in a conditional statement?

Having the following test case: (find fiddle here)
var a = new Date();
var b = null;
var c = {test: "test"};
if(a)
console.log(a); //--- prints the current date
if(b)
console.log('null'); //--- never reached
if(c)
console.log('test'); //--- prints 'test'
console.log(a && b); //--- prints null
Knowing that
console.log(typeof null); //--- prints "object"
console.log(typeof c); //--- prints "object"
I expect the result of
console.log(a && b);
to be false and not null as it shown in the example.
Any hint?
From the MDN:
expr1 && expr2 : Returns expr1 if it can be converted to false; otherwise, returns expr2
new Date can't be converted to false (it's not falsy), so b is returned.
I expect the result of
console.log(a && b);
to be false and not null as it shown in the example.
In many languages with && and || operators (or AND and OR), the result is always a boolean, yes.* But JavaScript's && and || are more useful than that: Their result is their left-hand operand's value or their right-hand operand's value, not coerced to boolean.
Here's how && works:
Evaluate the left-hand operand.
If the value is falsey (coerces to false when we make it a boolean), return the value (not the coerced value)
If the value from #2 is truthy, evaluate and return the right-hand value (uncoerced)
The falsey values are null, undefined, 0, "", NaN, and of course, false. Everything else is truthy.
So for instance
console.log(0 && 'hi'); // 0
...shows 0 because 0 is falsey. Note it resulted in 0, not false. Similarly, the result here:
console.log(1 && 'hello'); // hello
...is 'hello' because the right-hand side isn't coerced at all by &&.
|| works similarly (I call it the curiously-powerful OR operator): It evaluates the left-hand side and, if that's truthy, takes that as its result; otherwise it evaluates the right-hand side and takes that as its result.
The only time you get true or false from && or || is if the selected operand is already a boolean.
* Of course, many (but not all) of those languages (Java, C#) also require that the operands to && and || already be booleans. C's an exception, it does some coercion, but still has the result of the operands as a boolean (or if you go back far enough, an int that will be 1 or 0).
From MDN:
Logical AND (&&) 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.
MDN Documentation

Why does `1 && true` get a bool value `true`, but `0 && true` get a number `0`?

Why does 1 && true get a bool value true, but 0 && true get a number 0?
I tested it in Chrome Console and Firebug.
Because expr1 && expr2 will return expr1 if it is false, otherwise it will return expr2.
Because that is how logical operators in Javascript are defined to behave.
Additional reference: ECMA 262, page 83.
The && operator is commonly called logical and. If the first operand is false, null, undefined, "" or the number 0 then it returns the first operand. Otherwise, it returns the second operand

Categories