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

时间:2018-08-30 17:15:59

标签: javascript

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?

2 个答案:

答案 0 :(得分:1)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Description

  

运算符:逻辑与(&&)

     

用法:expr1 && expr2

     

如果expr1可以转换为false,则返回它;否则,返回expr2。因此,当与布尔值一起使用时,&&如果两个操作数都为true,则返回true;否则,返回false。

答案 1 :(得分:0)

如果所有其他值均为真,则&&运算符将返回最后一个值,否则将返回第一个非真值。因此,就像在<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>This is a heading</h1> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>Add a class name to the first p element</button>中一样,0 && 2是不真实的,它会返回。