The && and || operators are called short-circuit operators. They will return the value of the second operand based on the value of the first operand.

The && operator is useful for checking for null objects before accessing their attributes. For example...

var name = person && person.getName();

This code is the same as

if(person) {
	var name = person.getName();
}

The || operator is used for setting default values.

var name = persons_name || "John Doe";

The equalant code is

if(persons_name) {
	var name = persons_name;
} else {
	var name = "John Doe";
}

Comments

David Golightly at 12 Sep, 2007 02:38
Actually, that's not technically true:

var name = person && person.getName();

might work the same as

var name;
if (person) {
name = person.getName();
}

because, in the above example, "person" might have the value "undefined" (depending on your context, but in the most common example, for a parameter named "person" inside a function), in which case "name" is declared and gets assigned the value "undefined", but in the lower example, if "person" is not "truthy" (fails an "if" test), then the variable "name" does not get declared at all, in which case attempting to access its value it afterward is an error. Try it!
Reply to this.
Binny V A at 12 Sep, 2007 08:13
Yeah - you are right. Thanks
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.