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?
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 ornull), that would cause an exception. This way, the function is passed either the button reference (whatever that is), ornull.To put it another way, it’s the same as this:
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.