Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Javascript || operator

I am using a large JS library to perform certain drawing operations in canvas. Reviewing the library code (to make accommodating changes), I have ran into the '||' operator being used in a fashion which certainly should not evaluate to Boolean. Does this mean that this is a different operator or am I missing something obvious? An example follows:

var $time = Date.now || function(){
return +new Date;
};
Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

There is already an accepted answer, but I like to mention, that the OR-Operator is also called Default-Operator, because it doesn't return a boolean, but instead the left or right hand argument.

Same goes for the AND-Operator, which is also called guard-Operator.

Check out crockford's Survey of the JavaScript Programming Language for more details:

The && operator is commonly called logical and. It can also be called guard. If the first operand is false, null, undefined, "" (the empty string), or the number 0 then it returns the first operand. Otherwise, it returns the second operand. This provides a convenient way to write a null-check:

var value = p && p.name; /* The name value will only be retrieved from p if p has a value, avoiding an error. */

The || operator is commonly called logical or. It can also be called default. If the first operand is false, null, undefined, "" (the empty string), or the number 0, then it returns the second operand. Otherwise, it returns the first operand. This provides a convenient way to specify default values:

value = v || 10; /* Use the value of v, but if v doesn't have a value, use 10 instead. */


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...