Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

numbers - JavaScript type conversion: (true && 1) vs (true | | 1)

JavaScript is non-strictly typed language as Java,for example.

As we know, it converts value of result dependently upon context:

"2" + "3" results "23"

"2" * "3" results 6

This is quite clear and OK for understanding.

I just tried following expressions and got confused:

true && 1 results 1
true || 1 results true

Why the first gives Number and the second gives boolean?

Considering JavaScript conversion rules,I expect to get boolean values in both cases,due to boolean context of expression.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To quote MDC;

&&; 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.
||; 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.

So in the first example, 1 is being returned because expr1 cannot be converted to false.

In the second example, true can be converted to true, so it's returned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...