JavaScript/Operators

From Wikibooks, open books for an open world
Jump to navigation Jump to search



String concatenation[edit | edit source]

The + operator acts in two different ways depending on the type of its two operands. If one or both of them are strings, it acts as a string concatenator. If both are numeric, it acts as an arithmetic addition.

An example of string concatenation is "one " + "world" resulting in "one world". If one of the two operands isn't a string, it is implicitly converted to a string before the + operation takes place.

"use strict";

// regular concatenation
const word_1 = "one";
const word_2 = "world";
let   result = word_1 + " " + word_2;
alert(result);        //  "one world"

// implicit type conversion
const arr = [41, 42, 43];
result = word_1 + arr + word_2;   // first, the array is converted to a string
alert(result);        //  "one41,42,43world"

// dito
const x = 1;
result = x + word_2;
alert(result);        //  "1world"

Arithmetic operators[edit | edit source]

JavaScript has the arithmetic operators +, -, *, /, % (remainder), and ** (exponentiation). These operators work the way you learned in mathematics. Multiplication and division will be calculated before addition and subtraction. If you want to change such precedence, you can use parenthesizes.

Hint: In opposite to some other languages, the division operation may result in a floating point number - it's not always a pure integer.

const a = 12 + 5;       // 17
const b = 12 - 5;       // 7
const c = 12 * 5;       // 60
const d = 12 / 5;       // 2.4   Division results in floating point numbers
const e = 12 % 5;       // 2     Remainder of 12/5 is 2
const f = 12 - 2  * 5;  // 2     Multiplication is calculated first
const g =(12 - 2) * 5;  // 50    Parenthesis are calculated first

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

The return value of the remainder 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.

"use strict";
const a = 42;
const b = +a;    // b is 42
const c = -a;    // c is -42

As noted above, + is also used as the string concatenation operator: If any of its arguments is a string or is otherwise not a number, all arguments are converted to strings and concatenated together. All other arithmetic operators works the other way round: They attempt to convert their arguments into numbers before evaluating.

"use strict";
const a = 42;
const b = "2";
const c = "3";
alert(a + b);   //  "422"  (a string)
alert(a * b);   //  84     (a number)
alert(b * c);   //  6      (a number)

Bitwise operators[edit | edit source]

There are seven 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 that 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 operators[edit | edit source]

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 array_A was passed to the alert, but array_B was changed. This is because they are two references to the same object.

"use strict";
const array_A = [0, 1, 2];
const array_B = array_A;
array_B[2] = 0;
alert(array_A);  // 0, 1, 0

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

"use strict";
const z = [5];
const x = z;
z.pop();
alert (x);

If the result of any of the above-shown arithmetic or bitwise operators shall be assigned to its first operand, you can use a shorter syntax. Combine the operator, e.g., +, directly with the assignment operator = resulting in +=. As an example x = x + 5 can be abbreviated as x += 5.

The abbreviated operator/assignment syntax reads:

Arithmetic Logical Shift
+= &= >>=
-= |= <<=
*= ^= >>>=
/=
%=

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

"use strict";
const arr = [1, 2, 3];
let sum = 0;
for (let i = 0; i < arr.length; i++) {
  sum += arr[i];  // same as: sum = sum + arr[i];
}
alert(sum);

Increment operators[edit | edit source]

Increment and decrement operators are a particular form of arithmetic 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 acts similarly but reduces the variable instead.

As an example, the next operations all perform the same task:

"use strict";
let a = 1;
alert(a);     // 1

a = a + 1;
alert(a);     // 2

a += 1;
alert(a);     // 3

a++;
alert(a);     // 4

++a;
alert(a);     // 5

// but this SHOWS something different; see next chapter
alert(a++);   // shows 5 again
alert(a);     // nevertheless, 'a' was incremented to 6

Pre and post-increment operators[edit | edit source]

Increment operators may be written before or after a variable. The position decides whether they are pre-increment or post-increment operators, respectively. That affects the operation.

"use strict";

// increment occurs before a is assigned to b
let a = 1;
let b = ++a;  // a = 2, b = 2;

// increment occurs to c after c is assigned to d
let c = 1;
let d = c++;  // c = 2, d = 1;

Due to the possibly confusing nature of pre and post-increment behavior, code can be easier to read if you avoid increment operators.

"use strict";

// increment occurs before a is assigned to b
let a = 1;
a += 1;
let b = a;  // a = 2, b = 2;

// increment occurs to c after c is assigned to d
let c = 1;
let d = c;
c += 1;     // c = 2, d = 1;

Comparison operators[edit | edit source]

Comparison operators determine whether their two operands meet the given condition. They return true or false.

Concerning the 'equal' and 'not-equal' operators, you must take care. == is different from ===. The first one tries to adapt the data type of the two types to each other and then compares the values. The second one compares the types as well as their values and returns only true if type and value are identical: 3 == "0003" is true and 3 === "3" is false.

Op. Returns Notes
== true, if the two operands are equal May change an operand's type
(e.g. a string as an integer).
=== true, if the two operands are strictly equal Does not change operands' types.
Returns true if they are the same type and value.
!= true, if the two operands are not equal May change an operand's type
(e.g. a string as an integer).
!== true, if the two operands are not strictly equal Does not change the operands' types.
Returns true if they differ in type or value.
> true, if the first operand is greater than the second one
>= true, if the first operand is greater than or equal to the second one
< true, if the first operand is less than the second one
<= true, if the first operand is less than or equal to the second one

We recommend using the strict versions (=== and !==) because the simple versions may 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

... although you might want:

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

Logical operators[edit | edit source]

The logical operators are and, or, and not — written as &&, ||, and !. The first two take two boolean operands each. The third takes one and returns its logical negation.

Operands are boolean values or expressions that evaluate to a boolean value.

"use strict";
const a = 0;
const b = 1;

if (a === 0 && b === 1) {  // logical 'and'
  alert ("a is 0 AND b is 1");
}

if (a === 1 || b === 1) {  // logical 'or'
  alert ("a is 1 OR b is 1");
}

&& and || are short circuit operators: if the result is guaranteed after the evaluation of the first operand, it skips the evaluation of the second operand. Due to this, the && operator is also known as the guard operator, and the || operator is known as the default operator.

"use strict";

// declare 'myArray' without initialization
let myArray;

// runtime error!
if (myArray.length > 0) {
  alert("The length of the array is: " + myArray.length);
}

// no error because the part after '&&' will not be executed!
if (myArray && myArray.length > 0) {
  alert("The length of the array is: " + myArray.length);
}

The ! operator determines the inverse of the given boolean value: true becomes false and false becomes true.

Note: JavaScript represents false by either a Boolean false, the number 0, NaN, an empty string, or the built-in types undefined or null. Any other value is treated as true.

Concerning the precedence of the three operators, ! is evaluated first, followed by &&, and lastly ||.

      a  ||   b  &&   !c

    |       |       |    |
    |       |       └ 1. ┘
    |       └───── 2. ───┘
    └───────── 3. ───────┘

More details on the relationship between precedence and short-circuiting are explained at MDN

Other operators[edit | edit source]

? :[edit | edit source]

The ? : operator (also called the "ternary" operator) is an abbreviation of the if statement. First, it evaluates the part before the question mark. Then, if true, the part between the question mark and the colon is evaluated and returned, else the part behind the colon.

const target = (a == b) ? c : d;

However, be careful when using it. 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.

Instead, it is better to 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;
}

delete[edit | edit source]

delete obj.x unbinds property x from object obj.

The delete keyword deletes a property from an object. It deletes both the value of the property and the property itself. After deletion, the property cannot be used before it is added back again. The delete operator is designed to be used on object properties. It has no effect on variables or functions.

new[edit | edit source]

new cl creates a new object of type cl. The cl operand must be a constructor function.

instanceof[edit | edit source]

o instanceof c tests whether o is an object created by the constructor c.

typeof[edit | edit source]

typeof x returns a string describing the type of x. Following values may be returned.

Type returns
boolean "boolean"
number "number"
string "string"
function "function"
undefined "undefined"
null "object"
others (array, ...) "object"

Exercises[edit | edit source]

... are available on another page (click here).

See also[edit | edit source]