Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 0 && true echo 0 in js?

Tags:

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?

enter image description here

like image 429
qiuyuntao Avatar asked Jan 10 '19 07:01

qiuyuntao


People also ask

Why is it 0 and 1?

1. Binary is a base-2 number system invented by Gottfried Leibniz that's made up of only two numbers or digits: 0 (zero) and 1 (one). This numbering system is the basis for all binary code, which is used to write digital data such as the computer processor instructions used every day.

What is a 0 in math?

Zero is the integer denoted 0 that, when used as a counting number, means that no objects are present. It is the only integer (and, in fact, the only real number) that is neither negative nor positive. A number which is not zero is said to be nonzero. A root of a function is also sometimes known as "a zero of ."

What is a factorial of 0?

The Definition of a Zero Factorial This still counts as a way of arranging it, so by definition, a zero factorial is equal to one, just as 1! is equal to one because there is only a single possible arrangement of this data set.


3 Answers

Because operator && return first falsey element otherwise they return last element

1 && 0 && false // 0
1 && 2 && 3     // 3
like image 108
Vadim Hulevich Avatar answered Oct 10 '22 23:10

Vadim Hulevich


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.
like image 41
Rakesh Makluri Avatar answered Oct 10 '22 21:10

Rakesh Makluri


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.

like image 33
axiac Avatar answered Oct 10 '22 23:10

axiac