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

Why does the || (or) and && (and) operator in JavaScript behave differently than in C (returning non boolean value)?

Consider the following code.

console.log("All" && 1); // 1
console.log("All" || 1); // "All" 
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The logical operators in C always evaluate to boolean values. In C, the int 1 represents true and the int 0 represents false. That's the reason why both the expressions, "All" && 1 and "All" || 1, evaluate to 1. Both of them are logically true. For clarification, consider the following program.

#include <stdio.h>

int main() {
    printf("%d
", 20 && 10); // 1
    printf("%d
", 20 || 10); // 1
    return 0;
}

In the above program, the expressions 20 && 10 and 20 || 10 still evaluate to 1 even though there is no 1 in those expressions. This makes sense because both those expressions are logically true. Hence, they evaluate to 1 which is equivalent to true in JavaScript.

If JavaScript behaved the way C did then the expressions "All" && 10 and "All" || 10 would evaluate to the boolean value true. However, that's not the way the logical operators behave in JavaScript. That's not to say that they are buggy.

Values in JavaScript have a notion of truthiness and falsity. For example, the values true, "All", 10, [10, 20], { foo: 10 }, and x => 2 * x are all truthy. On the other hand, the values false, "", 0, undefined, and null are falsy.

The logical operators of JavaScript don't always evaluate to boolean values like C does. Instead, they evaluate to one of their operands. The && operator evaluates to its left operand if it's falsy. Otherwise, it evaluates to the right operand. Similarly, the || operator evaluates to its left operand if it's truthy. Otherwise, it evaluates to the right operand.

Now, the value "All" is truthy. Hence, "All" && 1 evaluates to the right operand (i.e. 1) whereas "All" || 1 evaluates to the left operand (i.e. "All"). Notice that both 1 and "All" are truthy values, which means that they are equivalent to 1 (which represents truthiness) in C.

Hence, no. JavaScript is not buggy.


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

...