Skip to content

Operators

Rohan Singh edited this page Aug 29, 2014 · 30 revisions

The following operators are available, in order of precedence:

Category Operators
Postfix x.y, x[y], x(y), x++, x--
Prefix -x, !x, ++x, --x
Multiplication *, /, %
Addition +, -
Relational >, >=, <, <=
Equality ==, !=
Conditional And &&
Conditional Or ||
Ternary [[?:
Assign =, +=, -=, *=, /=, %=, [[|>

Equality

These are the rules the equality operators (==, !=) follow:

  1. Values of different types will never be equal.
  2. number and string types of the same value will always be equal.
  3. object, array, and function types will only be equal if they refer to the same instance, not value.
  4. true, false, null, and undefined are only equal with themselves.

Relational

The relational operators (>, >=, <, <=) can only be used on number and string values. When used on string values the result allows you to determine sort order.

Conditional And/Or

The conditional and/or operators (&&, ||) test if [[values evaluate to true|Conditionals#evaluation]]. The result of the operation will be the last evaluated value, which doesn't need to be true or false.

&& requires both values to evaluate to true while || only needs one value to evaluate to true.

Both operators support short circuiting. This means the right side of && will not be evaluated if the left side evaluates to false, or the right side of || will not be evaluated if the left side evaluates to true.

This behavior can used in many different ways, like providing default values:

fun square(num) {
    num = num || 100;
    return num * num;
}

var a = square(10); // 100
var b = square();   // 10000