Skip to content

ES6 - Operators

An expression is a unit of code that evaluates to a value. Expressions are typically composed of:

  • Operands: The data or values that the operator acts upon.
  • Operator: A symbol or keyword that defines the operation to be performed on the operands.

For example, in the expression 5 + 10, 5 and 10 are operands, and + is the operator. JavaScript supports various types of operators.

Perform mathematical calculations. Assume let a = 10; let b = 5;

OperatorDescriptionExampleResult
+Additiona + b15
-Subtractiona - b5
*Multiplicationa * b50
/Divisiona / b2
%Modulus (Remainder)a % b0 (10 divided by 5 has a remainder of 0)
**Exponentiation (ES2016)a ** 2 (a to the power of 2)100
++Increment (adds 1)let c = a++; (c is 10, a becomes 11) or let d = ++a; (a becomes 11, d is 11)Varies
—Decrement (subtracts 1)let e = b--; (e is 5, b becomes 4) or let f = --b; (b becomes 4, f is 4)Varies

Compare two values and return a Boolean value (true or false). Assume let x = 10; let y = 20; let z = '10';

OperatorDescriptionExampleResult
>Greater thany > xTrue
<Less thanx < yTrue
>=Greater than or equal tox >= 10True
<=Less than or equal toy <= 10False
==Equality (Loose)x == z (performs type coercion)True (10 == ‘10’)
===Strict Equalityx === z (no type coercion)False (number 10 !== string ‘10’)
!=Inequality (Loose)x != yTrue
!==Strict Inequalityx !== zTrue

Best Practice: Prefer strict equality (===) and strict inequality (!==) to avoid unexpected behavior due to type coercion.

Combine or modify Boolean expressions. Assume let p = true; let q = false;

OperatorDescriptionExampleResult
&&Logical ANDp && qFalse (True if both operands are true)
||Logical ORp || qTrue (True if at least one operand is true)
!Logical NOT!pFalse (Inverts the Boolean value)

Logical operators often use short-circuiting. For example, in expr1 && expr2, if expr1 is false, expr2 is not evaluated.

Perform operations on the binary representation of numbers. These are less commonly used in typical web development but are important in certain low-level programming scenarios.

OperatorNameDescription
&Bitwise ANDReturns a 1 in each bit position where both operands have a 1.
|Bitwise ORReturns a 1 in each bit position where at least one operand has a 1.
^Bitwise XORReturns a 1 in each bit position where operands have different bits.
~Bitwise NOTInverts all bits of its operand.
<<Left ShiftShifts bits to the left, filling with zeros from the right.
>>Sign-propagating Right ShiftShifts bits to the right, preserving the sign bit.
>>>Zero-fill Right ShiftShifts bits to the right, filling with zeros from the left.
Example: `5 & 1` (binary `0101 & 0001`) results in `1` (binary `0001`).

Assign values to variables. Often combined with other operators for shorthand.

OperatorExampleEquivalent to
=x = yx = y (Simple assignment)
+=x += yx = x + y (Add and assign)
-=x -= yx = x - y (Subtract and assign)
*=x *= yx = x * y (Multiply and assign)
/=x /= yx = x / y (Divide and assign)
%=x %= yx = x % y (Modulus and assign)
**=x **= yx = x ** y (Exponentiation and assign)

Shorthand assignment also applies to bitwise operators (e.g., &=, |=).

A shorthand for an if-else statement. Syntax: condition ? exprIfTrue : exprIfFalse

let age = 20;
let status = (age >= 18) ? 'Adult' : 'Minor';
console.log(status); // Output: Adult

When used with strings, + concatenates them. If one operand is a string, the other is converted to a string.

let greeting = 'Hello, ' + 'World!';
console.log(greeting); // Output: Hello, World!
let message = 'Count: ' + 5;
console.log(message); // Output: Count: 5

Modern template literals (backticks `) are often preferred for string construction: let message = Count: ${5};

Returns a string indicating the type of an unevaluated operand.

TypeString Returned by typeof
Number"number"
String"string"
Boolean"boolean"
Object (includes null, array, object literal)"object" (Note: typeof null is an old bug, returns "object")
Function"function"
Undefined variable or value"undefined"
Symbol (ES6)"symbol"
BigInt (ES2020)"bigint"
console.log(typeof 42); // "number"
console.log(typeof 'hello'); // "string"
console.log(typeof undefined); // "undefined"

Checks if an object is an instance of a particular constructor or class. object instanceof Constructor

let arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true (Arrays are objects)
class Person {}
let p = new Person();
console.log(p instanceof Person); // true

Evaluates multiple expressions from left to right and returns the value of the last expression. Used rarely, sometimes in for loops.

let x = (1, 2, 3);
console.log(x); // Output: 3

Spread (...) and Rest (...) Operators (ES6)

Section titled “Spread (...) and Rest (...) Operators (ES6)”

Spread Operator: Expands an iterable (like an array or string) into individual elements, or an object into key-value pairs. Useful for copying arrays/objects, merging them, or passing array elements as function arguments.

const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

Rest Parameter: Collects multiple function arguments into a single array. Must be the last parameter in a function definition.

function sum(...numbers) {
return numbers.reduce((acc, current) => acc + current, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10

Returns its right-hand side operand when its left-hand side operand is null or undefined, otherwise returns its left-hand side operand. It’s a way to provide default values for potentially nullish variables.

const foo = null ?? 'default string'; // foo is 'default string'
const bar = 0 ?? 42; // bar is 0 (0 is not null or undefined)

Allows reading the value of a property located deep within a chain of connected objects without having to explicitly validate that each reference in the chain is valid. If a reference is null or undefined, the expression short-circuits and evaluates to undefined instead of throwing an error.

const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName); // undefined (adventurer.dog is undefined, no error)
const catName = adventurer.cat?.name;
console.log(catName); // Dinah