search ]

Understanding JavaScript Operators

JavaScript operators are symbols used to perform operations on variables and values. They are the backbone of any logic and arithmetic in your scripts. This post will explore different types of JavaScript operators with examples to illustrate their use.

Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations, such as addition, subtraction, multiplication, and division.

OperatorDescriptionExample
+Additionlet sum = 10 + 5; // 15
Subtractionlet difference = 10 – 5; // 5
*Multiplicationlet product = 10 * 5; // 50
/Divisionlet quotient = 10 / 5; // 2
%Modulus (Remainder)let remainder = 10 % 3; // 1
**Exponentiationlet power = 2 ** 3; // 8

Arithmetic Operators in Detail

1. Addition (+)

Adds two values. Note that when used with strings, the + operator performs concatenation instead of addition:

let sum = 10 + 5; // 15
let greeting = 'Hello' + ' ' + 'World'; // 'Hello World'
let mixed = '5' + 3; // '53' (string concatenation, not addition)

2. Subtraction (-)

Subtracts one value from another.

let difference = 10 - 5; // 5

3. Multiplication (*)

Multiplies two values.

let product = 10 * 5; // 50

4. Division (/)

Divides one value by another.

let quotient = 10 / 5; // 2

5. Modulus (%)

Returns the remainder of a division. Useful for checking if a number is even or odd:

let remainder = 10 % 3; // 1
let isEven = (4 % 2 === 0); // true

6. Exponentiation (**)

Raises the left operand to the power of the right operand. This is equivalent to Math.pow():

let power = 2 ** 3; // 8
let squareRoot = 9 ** 0.5; // 3

Assignment Operators

Assignment operators assign values to variables, allowing you to set or update the value of a variable.

OperatorDescriptionExample
=Assignmentlet x = 10;
+=Addition Assignmentx += 5; // x = x + 5
-=Subtraction Assignmentx -= 3; // x = x – 3
*=Multiplication Assignmentx *= 2; // x = x * 2
/=Division Assignmentx /= 2; // x = x / 2
**=Exponentiation Assignmentx **= 3; // x = x ** 3
%=Remainder Assignmentx %= 3; // x = x % 3

Assignment Operators in Detail

1. Assignment (=)

Assigns a value to a variable.

let x = 10;

2. Addition Assignment (+=)

Adds and assigns a value to a variable.

x += 5; // x = x + 5; // 15

3. Subtraction Assignment (-=)

Subtracts and assigns a value to a variable.

x -= 3; // x = x - 3; // 7

4. Multiplication Assignment (*=)

Multiplies and assigns a value to a variable.

x *= 2; // x = x * 2; // 20

5. Division Assignment (/=)

Divides and assigns a value to a variable.

x /= 2; // x = x / 2; // 5

Comparison Operators

Comparison operators compare two values and return a boolean result, allowing you to evaluate conditions in your code. They are commonly used in if…else statements and loops.

OperatorDescriptionExample
==Equal to (loose)5 == ‘5’ // true
===Strict Equal to5 === ‘5’ // false
!=Not Equal to (loose)5 != ‘5’ // false
!==Strict Not Equal to5 !== ‘5’ // true
>Greater than10 > 5 // true
<Less than10 < 5 // false
>=Greater than or equal to10 >= 10 // true
<=Less than or equal to10 <= 5 // false

Comparison Operators in Detail

1. Equal to (==) vs. Strict Equal to (===)

The loose equality operator (==) performs type coercion before comparing, meaning it converts operands to the same type. The strict equality operator (===) checks both value and type without conversion:

5 == '5';   // true  (string '5' is coerced to number 5)
5 === '5';  // false (different types: number vs. string)

0 == false;  // true  (false is coerced to 0)
0 === false; // false (different types)

Best practice: always prefer === and !== over == and !=. Strict equality avoids unexpected type coercion bugs and makes your intentions clear.

2. Not Equal to (!=) and Strict Not Equal to (!==)

These work like the equality operators but check for inequality:

5 != '5';   // false (values are equal after coercion)
5 !== '5';  // true  (different types)

3. Relational Operators (>, <, >=, <=)

Compare two values numerically or alphabetically:

10 > 5;    // true
10 < 5;    // false
10 >= 10;  // true
10 <= 5;   // false
'b' > 'a'; // true (alphabetical comparison)

Logical Operators

Logical operators are used to combine multiple boolean expressions, enabling complex condition evaluations.

OperatorDescriptionExample
&&Logical AND(true && false) // false
||Logical OR(true || false) // true
!Logical NOT!true // false

Logical Operators in Detail

1. Logical AND (&&)

Returns the first falsy value, or the last value if all are truthy. Commonly used to combine conditions:

let andResult = (true && false); // false
let both = (10 > 5 && 20 > 10); // true

// Short-circuit: if the first operand is falsy, the second is not evaluated
let user = null;
let name = user && user.name; // null (doesn't throw an error)

2. Logical OR (||)

Returns the first truthy value, or the last value if all are falsy. Often used to set default values:

let orResult = (true || false); // true
let value = '' || 'default'; // 'default' (empty string is falsy)

3. Logical NOT (!)

Inverts the boolean value of an expression:

let notResult = !true; // false
let isFalsy = !0; // true
let isString = !!'hello'; // true (double NOT to convert to boolean)

Nullish Coalescing and Optional Chaining

These modern operators (ES2020) help handle null and undefined values more safely and concisely.

Nullish Coalescing (??)

Returns the right-hand operand when the left side is null or undefined. Unlike ||, it does not treat 0, '', or false as reasons to fall through:

let count = 0;
let result1 = count || 10;  // 10 (0 is falsy)
let result2 = count ?? 10;  // 0  (0 is not null/undefined)

let text = '';
let result3 = text || 'default';  // 'default'
let result4 = text ?? 'default';  // ''

Optional Chaining (?.)

Safely access deeply nested properties without throwing an error if a reference is null or undefined:

const user = {
    profile: {
        address: { city: 'Tel Aviv' }
    }
};

// Without optional chaining - throws error if profile is undefined
// const city = user.profile.address.city;

// With optional chaining - returns undefined safely
const city = user?.profile?.address?.city; // 'Tel Aviv'
const zip = user?.profile?.address?.zip;   // undefined (no error)

// Works with methods too
const length = user?.profile?.getName?.(); // undefined (no error)

You can combine ?? with ?. for safe access with a fallback value: const city = user?.profile?.address?.city ?? 'Unknown';

Nullish Coalescing Assignment (??=)

The ??= operator assigns a value only if the variable is currently null or undefined. Similarly, ||= assigns if the variable is falsy, and &&= assigns if it is truthy:

let a = null;
a ??= 'default'; // a is now 'default'

let b = 0;
b ??= 42; // b is still 0 (0 is not null/undefined)
b ||= 42; // b is now 42 (0 is falsy)

The Ternary (Conditional) Operator

The ternary operator is the only JavaScript operator that takes three operands. It’s a concise alternative to an if…else statement:

// Syntax: condition ? expressionIfTrue : expressionIfFalse

let age = 20;
let canVote = (age >= 18) ? 'Yes' : 'No'; // 'Yes'

// Equivalent if...else:
let canVote2;
if (age >= 18) {
    canVote2 = 'Yes';
} else {
    canVote2 = 'No';
}

Keep ternary expressions simple. If the logic becomes complex, use a regular if...else block for readability.

Type Operators

JavaScript provides operators for checking and working with types:

typeof

Returns a string indicating the type of the operand:

typeof 42;          // 'number'
typeof 'hello';     // 'string'
typeof true;        // 'boolean'
typeof undefined;   // 'undefined'
typeof null;        // 'object' (historical bug, null is not an object)
typeof {};          // 'object'
typeof [];          // 'object' (arrays are objects)
typeof function(){};// 'function'

instanceof

Checks whether an object is an instance of a specific constructor or class:

let arr = [1, 2, 3];
arr instanceof Array;  // true
arr instanceof Object; // true (arrays inherit from Object)

let date = new Date();
date instanceof Date;  // true

Spread and Rest Operators (…)

The ... syntax serves two purposes depending on the context: spreading elements or collecting (rest) parameters.

Spread Operator

Expands an iterable (like an array) into individual elements:

let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

// Spread with objects
let obj1 = { a: 1, b: 2 };
let obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

Rest Operator

Collects remaining function arguments into an array:

function sum(...numbers) {
    return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4); // 10

// Rest in destructuring
let [first, ...rest] = [1, 2, 3, 4];
// first = 1, rest = [2, 3, 4]

FAQs

Common questions about JavaScript operators:

What is the difference between == and === in JavaScript?
The == (loose equality) operator compares values after performing type coercion, so 5 == '5' returns true. The === (strict equality) operator compares both value and type without conversion, so 5 === '5' returns false. Always prefer === to avoid unexpected behavior caused by implicit type conversion.
What is the difference between ?? and || in JavaScript?
The || (logical OR) operator returns the right-hand value when the left side is any falsy value (false, 0, '', null, undefined, NaN). The ?? (nullish coalescing) operator only returns the right-hand value when the left side is null or undefined. Use ?? when you want to preserve legitimate falsy values like 0 or empty strings.
What does the spread operator (...) do?
The spread operator (...) expands an iterable (like an array or object) into individual elements. For arrays, [...arr1, ...arr2] merges two arrays. For objects, {...obj1, ...obj2} merges objects. The same syntax is called the rest operator when used in function parameters to collect remaining arguments into an array.
Why does typeof null return 'object'?
This is a well-known bug from the earliest version of JavaScript. In the original implementation, values were stored with a type tag, and null had the same tag as objects (0). This was never fixed to maintain backward compatibility. To check for null specifically, use the strict equality check: value === null.
What is optional chaining (?.) and when should I use it?
Optional chaining (?.) lets you safely access nested object properties without checking each level for null or undefined. Instead of writing "if (user && user.profile && user.profile.name)", you can write "user?.profile?.name". If any part of the chain is null or undefined, the expression short-circuits and returns undefined instead of throwing an error.
What is the ternary operator in JavaScript?
The ternary operator (condition ? valueIfTrue : valueIfFalse) is a shorthand for an if...else statement. It takes three operands and returns one of two values based on a condition. For example, "let result = age >= 18 ? 'Adult' : 'Minor'" assigns 'Adult' if age is 18 or more, otherwise 'Minor'. Keep ternary expressions simple for readability.

Conclusion

JavaScript operators are essential tools for performing various operations in your code. From basic arithmetic and comparison to modern features like nullish coalescing (??) and optional chaining (?.), understanding these operators helps you write more efficient and readable scripts.

For more JavaScript fundamentals, explore the guides on variables and constants, strings, and arrays.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo