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
265 views
in Technique[技术] by (71.8m points)

Logical operator || in javascript, 0 stands for Boolean false?

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

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)
  • ||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


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

...