Monday, April 4, 2011

Javascript operators

In Javascript, there are some seldom used operators:
  1. ++ Increment
  2. -- Decrement
  3. = = = Exactly equal to (both value and type)
  4. || Logical Or
Here are some examples:
  1. x = y++  => {x = y; y = y + 1;}
  2. x = ++ y => {y = y + 1; x = y;}
  3. "5" === 5 => returns false, as type is not same.
  4. The Logical OR operator (||) will short-circuit and return the first truthy value.

There is a common usage for Logical Or operator, which is to setting default values to function arguments, e.g.

function doSomething(e) {
    e = e || window.event
    alert(e.type);
}
=>
function doSomething(e) {
    if (!e) e = window.event;
    alert(e.type);
}

The Logical OR || operator will return its second operand if the first one is falsy
Falsy values are: 0, null, undefined, an empty string, NaN, and false

No comments:

Post a Comment