1

Possible Duplicate:
&& operator in Javascript

In the sample code of the ExtJS web desktop demo there is the following call:

this.setActiveButton(activeWindow && activeWindow.taskButton);

to method:

setActiveButton: function(btn) {
    if (btn) {
        btn.toggle(true);
    } else {
        this.items.each(function (item) {
            if (item.isButton) {
                item.toggle(false);
            }
        });
    }
}

What is the purpose of the && in the function call?

Community
  • 1
  • 1
Joseph Victor Zammit
  • 14,760
  • 10
  • 76
  • 102
  • @TheZ not really accurate in JavaScript. The value of an `&&` is not necessarily a boolean value. It can be anything. – Pointy Jul 02 '12 at 16:34

2 Answers2

3

It's to make sure that, before trying to find a property on an object referenced by the variable "activeWindow", the variable actually does reference something. If it's null (or a few other things; we'll assume the code knows that it's either an object reference or null), that would cause an exception. This way, the function is passed either the button reference (whatever that is), or null.

To put it another way, it's the same as this:

this.setActiveButton(activeWindow != null ? activeWindow.taskButton : null)

The && operator in JavaScript is kind-of special compared to the && in C or Java or other languages like that. In JavaScript, the left side is evaluated first. If that value is "falsy" (null, undefined, false, zero, or an empty string), then that's the value of the expression. Otherwise, the value of the expression is the value of the right-hand side.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    except that activeWindow or activeWindow.taskButton can also be `undefined`, `false`, empty string, or `0` and it will pass false. – jbabey Jul 02 '12 at 16:30
  • @jbabey yes that's true - that's what I meant by "or a few other things", and by that qualifying assumption that the code knows it's either an object reference or null. – Pointy Jul 02 '12 at 16:31
1

See Short-circuit evaluation for additional information regarding this method.

The short-circuit expression x Sand y (using Sand to denote the short-circuit variety) is equivalent to the conditional expression if x then y else false; the expression x Sor y is equivalent to if x then true else y.

Robert
  • 8,717
  • 2
  • 27
  • 34
  • Not true in JavaScript - it's not really a **boolean** operator. The *value* of the overall expression is either the value of the left side or the value of the right side, as determined by the "truthiness" of the left side. – Pointy Jul 02 '12 at 16:33
  • Not that it matters since it has been closed but I have updated my answer to avoid any confusion. – Robert Jul 02 '12 at 16:36
  • @RobB Thank you, but the Pointy's reply arrived earlier, so I'll mark his as the correct one. Still +1ed you. – Joseph Victor Zammit Jul 02 '12 at 16:53