最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What does the || operator do? - Stack Overflow

programmeradmin1浏览0评论
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?

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?

Share Improve this question edited Apr 7, 2010 at 2:12 Jon Seigel 12.4k8 gold badges60 silver badges93 bronze badges asked May 6, 2009 at 16:55 SupernovahSupernovah 2,04512 gold badges35 silver badges51 bronze badges 2
  • 4 Wow it took 7 attempts to get the title right... – Pool Commented May 6, 2009 at 17:06
  • stackoverflow.com/questions/21367903/… – UtkarshPramodGupta Commented Jul 5, 2018 at 5:40
Add a comment  | 

4 Answers 4

Reset to default 21

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.

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.

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

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.

发布评论

评论列表(0)

  1. 暂无评论