JavaScript/Operators

Previous: Arrays Index Next: Control Structures

Arithmetic OperatorsEdit

Javascript has the arithmetic operators +, -, *, /, and %. These operators function as the addition, subtraction, multiplication, division, and modulus operators, and operate very similarly to other languages.

var a = 12 + 5; // 17
var b = 12 - 5; // 7
var c = 12 * 5; // 60
var d = 12 / 5; // 2.4 - division results in floating point numbers.
var e = 12 % 5; // 2 - the remainder of 12/5 in integer math is 2.

Some mathematical operations, such as dividing by zero, cause the returned variable to be one of the error values - for example, infinity, or NaN.

The return value of the modulus operator maintains the sign of the first operand.

The + and - operators also have unary versions, where they operate only on one variable. When used in this fashion, + returns the number representation of the object, while - returns its negative counterpart.

var a = "1";
var b = a;  // b = "1": a string
var c = +a;  // c = 1: a number
var d = -a;  // d = -1: a number

+ is also used as the string concatenation operator: If any of its arguments is a string or is otherwise not a number, any non-string arguments are converted to strings, and the 2 strings are concatenated. For example, 5 + [1,2,3] evaluates to the string "51,2,3". More usefully, str1 + " " + str2 returns str1 concatenated with str2, with a space between.

All other arithmetic operators will attempt to convert their arguments into numbers before evaluating. Note that unlike C or Java, the numbers and their operation results are not guaranteed to be integers.

Bitwise OperatorsEdit

There are 7 bitwise operators, &, |, ^, ~, >>, <<, and >>>.

These operators convert their operands to integers (truncating any floating point towards 0), and perform the specified bitwise operation on them. The logical bitwise operators, &, |, and ^, perform the and, or, and xor on each individual bit and provides the return value. The ~ (not operator) inverts all bits within an integer, and usually appears in combination with the logical bitwise operators.

Two bit shift operators, >>, <<, move the bits in one direction which has a similar effect to multiplying or dividing by a power of two. The final bit-shift operator, >>>, operates the same way, but does not preserve the sign bit when shifting.

These operators are kept for parity with the related programming languages but are unlikely to be used in most JavaScript programs.

Assignment operatorsEdit

The assignment operator = assigns a value to a variable. Primitive types, such as strings and numbers are assigned directly, however function and object names are just pointers to the respective function or object. In this case, the assignment operator only changes the reference to the object rather than the object itself. For example, after the following code is executed, "0,1,0" will be alerted, even though setA was passed to the alert, and setB was changed. This is because they are two references to the same object.

setA = [ 0, 1, 2 ];
setB = setA;
setB[2] = 0;
alert(setA);

Similarly, after the next bit of code is executed, x is a pointer to an empty array.

z = [5];
x = z;
z.pop();

All the above operators have corresponding assignment operators of the form operator=. For all of them, x operator= y is just a convenient abbreviation for x = x operator y.

  • +=
  • -=
  • *=
  • /=
  • %=
  • &=
  • |=
  • ^=
  • >>=
  • <<=
  • >>>=

For example, a common usage for += is in a for loop

var els = document.getElementsByTagName('h2');
var i;
for (i = 0; i < els.length; i += 1) {
  // do something with els[i]
}

Increment operatorsEdit

There are also the increment and decrement operators, ++ and --. a++ increments a and returns the old value of a. ++a increments a and returns the new value of a. The decrement operator functions similarly, but reduces the variable instead.

As an example, the last three lines all perform the same task:

var a = 1;
a = a + 1;
a += 1;
++a;

Pre and post-increment operatorsEdit

Increment operators may be applied before or after a variable. When they are applied before a variable they are pre-increment operators, and when they are applied after a variable they are post-increment operators.

The choice of which to use changes how they affect operations.

// increment occurs before a is assigned to b
var a = 1;
var b = ++a; // a = 2, b = 2;
 
// increment occurs to c after c is assigned to d
var c = 1;
var d = c++; // c = 2, d = 1;

Due to the possibly confusing nature of pre and post-increment behaviour, code can be easier to read if the increment operators are avoided.

// increment occurs before a is assigned to b
var a = 1;
a += 1;
var b = a; // a = 2, b = 2;
 
// increment occurs to c after c is assigned to d
var c = 1;
var d = c;
c += 1; // c = 2, d = 1;

Comparison operatorsEdit

The comparison operators determine if the two operands meet the given condition.

  • == - returns true if the two operands are equal. This operator may ignore an operand's type (e.g. a string as an integer).
  • === - returns true if the two operands are identical. This operator will not ignore the operands' types, and only returns true if they are the same type and value.
  • != - returns true if the two operands are not equal. This operator may ignore an operand's type (e.g. a string as an integer).
  • !== - returns true if the two operands are not identical. This operator will not ignore the operands' types, and only returns false if they are the same type and value.
  • > - Returns true if the first operand is greater than the second one.
  • >= - Returns true if the first operand is greater than or equal to the second one.
  • < - Returns true if the first operand is less than the second one.
  • <= - Returns true if the first operand is less than or equal to the second one.

Be careful when using == and != as the may ignore one of the terms type being compared. This can lead to strange and non-intuitive situations, such as:

0 == '' // true
0 == '0' // true
false == 'false' // false; (''Boolean to string'')
false == '0' // true (''Boolean to string'')
false == undefined // false
false == null // false (''Boolean to null'')
null == undefined // true

For stricter compares use === and !==

0 === '' // false
0 === '0' // false
false === 'false' // false
false === '0' // false
false === undefined // false
false === null // false
null === undefined // false

Logical operatorsEdit

  • && - and
  • || - or
  • ! - not

The logical operators are and, or, and not. The && and || operators accept two operands and provides their associated logical result, while the third accepts one, and returns it's logical negation. && and || are short circuit operators. If the result is guaranteed after evaluation of the first operand, it skips evaluation of the second operand.

Technically, the exact return value of these two operators is also equal to the final operand that it evaluated. Due to this, the && operator is also known as the guard operator, and the || operator is also known as the default operator.

function handleEvent(evt) {
    evt = evt || window.event;
    var targ = evt.target || evt.srcElement;
    if (targ && targ.nodeType === 1 && targ.nodeName === 'A') {
        // ...
    }
}

The ! operator determines the inverse of the given value, and returns the boolean: true values become false, or false values become true.

Note: Javascript represents false by either a boolean false, the number 0, an empty string, or the built in undefined or null type. Any other value is treated as true.

Other operatorsEdit

  • ? :

The ? : operator (also called the "ternary" operator).

var targ = (a == b) ? c : d;

Be cautious though in its use. Even though you can replace verbose and complex if/then/else chains with ternary operators, it may not be a good idea to do so. You can replace

if (p && q) {
    return a;
} else {
    if (r != s) {
        return b;
    } else {
        if  (t || !v) {
            return c;
        } else {
            return d;
        }
    }
}

with

return (p && q) ? a
  : (r != s) ? b
  : (t || !v) ? c
  : d

The above example is a poor coding style/practice. When other people edit or maintain your code (which could very possibly be you) it becomes much more difficult to understand and work with the code.

It is better to instead make the code more understandable. Some of the excessive conditional nesting can be removed from the above example.

if (p && q) {
    return a;
}
if (r != s) {
    return b;
}
if  (t || !v) {
    return c;
} else {
    return d;
}
  • typeof x returns a string describing the type of x.
  • o instanceof c tests whether o is an object created by the constructor c.
  • delete x unbinds x.
  • new cl creates a new object of type cl. The cl operand must be a constructor function.


Previous: Arrays Index Next: Control Structures
Last modified on 7 May 2013, at 19:03