In the following javascript function what does the || operator do? [duplicate]
Taken from a box2djs sample.
I'm trying to understand the library, but I do not understand the line:
ballSd.radius = rad || 10;
what does it mean?
Here's the full definition
createBall2 = function(world, x, y, rad, fixed) {
var ballSd = new b2CircleDef();
if (!fixed) ballSd.density = 1.0;
// what does the next line do?
ballSd.radius = rad || 10;
ballSd.restitution = 0.2;
var ballBd = new b2BodyDef();
ballBd.AddShape(ballSd);
ballBd.position.Set(x,y);
return world.CreateBody(ballBd);
};
ballSd.radius = rad || 10;
means: if rad == true
(or truthy
) return the value of rad, otherwise return 10
A boolean expression in JavaScript does not return false
or true
†, but the first operand (from left to right) that determines the outcome of the expression.
When using logical OR ||
, this is the first operand that evaluates to true
(similarly the first operand that evaluates to false
for &&
).
As others already noted, if rad
evaluates to false
(e.g. if it is 0
), then the second operand is returned.
This "trick" is often used to set a default value.
Read more about logical operators.
†: That is only 66.6% correct. The NOT operator !
will always return a boolean value.
All the answers are correct, but they are missing an explanation of the &&
and ||
operators in JavaScript. The trick is that they don't return a boolean, they return the value where the comparison short-circuited.
For example
// Returns the first truthy value (2) since after looking at 0 and 2, we already
// know the expression is true and we don't need to evaluate the last component (3)
alert (0 || 2 || 3)
// Returns the first falsy value (""), the comparison doesn't even
// evaluate "Hello" and "Dog"
alert( "" && "Hello" && "Dog" );
// No short circuiting, so the last value ("fun") is returned
alert( "string" && "fun" )
if rad is false or 0, set ballSd.radius to 10
Set the circle radius to either the given argument "rad" if it was given and bigger than zero otherwise to 10, which makes it the default radius.
see this... so if the value of rad variable converted to a boolean is true, then the rad is returned, otherwise it will return 10; any variable can be converted to a boolean value: null, 0, undefined will be converted to false; not undefined will be converted to true; see implicit boolean conversions in javascript
精彩评论