views:

239

answers:

4
Attacklab.wmd_env.buttons=Attacklab.wmd_env.buttons||_4;

what does the || do in this case?
Adds _4 to the array which is Attacklab.wmd_env.buttons?

+7  A: 

If Attacklab.wmd_env.buttons is null or undefined, it will be set to the default value _4.

John Millikin
+12  A: 

The || operator in JavaScript returns the value on the left if that value does not evaluate to false, otherwise it returns the value on the right.

From Mozilla's Core JavaScript 1.5 Reference:

expr1 || expr2
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 this case, if Attacklab.wmd_env.buttons doesn't have a value, it sets the value to _4.

bdukes
It's strange that MDC uses rather ambiguous "Returns expr1 if it **can be converted** to true". It's not really about "able to be converted", it's about which value expression returns.
kangax
+6  A: 

It's a fancy way of writing

if(!Attacklab.wmd_env.buttons)
    Attacklab.wmd_env.buttons = _4;

It's nice for providing default values. Keep in mind that not only null and undefined will trigger the conditional, but also 0, false and '', ie everything which is considered false in boolean contexts.

Christoph
+1 for explicitly listing what values evaluate to false
Grant Wagner
And, of course, `NaN` ;)
kangax
@kangax: yup, that was the only thing missing in the list (see ECMA-262, section 9.2)
Christoph
A: 

The || operator checks whether the value provided on the left side of the expression is false (in a boolean context). If so it returns an alternate value indicated by the right side of the expression. Otherwise it returns the original value.

So for example the following code would set 'Foo' to a default value if it is null:

Foo = Foo || "Default Value" 

This is sometimes called the Coalescing operator. It is supported in other languages such as Ruby and Perl. C# has the ?? operator which does the same thing.

Justin Ethier
So, with this answer he knows what it's called, and what other langagues use it, and even the different syntax in C#...and he still doesn't know what it does.
Beska
Good point, I probably should have just left a comment. Anyway, my answer has been updated.
Justin Ethier