JavaScript Operators

Master arithmetic evaluation, implicit type coercion in equality, short-circuit evaluation mechanics, nullish coalescing, and safe optional chaining.

1. Operators & Unary Type Conversion

An operator is a reserved symbol that performs an operation on one or more operands (values or variables) and produces a result.

  • Unary Operators: Act on a single operand (e.g., Unary Plus +x, Logical NOT !x, typeof x).
  • Binary Operators: Act on two operands (e.g., a + b, a * b, a === b).
  • Ternary Operator: Acts on three operands (conditional condition ? a : b).
Operator Operation Example Result
+ / - Addition / Subtraction 10 + 5 / 10 - 5 15 / 5
* / / Multiplication / Division 4 * 3 / 12 / 4 12 / 3
% Modulus (Remainder) 10 % 3 1 (remainder after integer division)
** Exponentiation (Power) 2 ** 3 8 (equivalent to Math.pow(2, 3))
+val Unary Plus (Numeric Coercion) +"42" 42 (invokes ToNumber conversion)

💡 Engine Mechanics: How Unary Plus (+) Works

The Unary Plus (+) operator is the fastest way to convert a string or boolean into a number in JavaScript. Under the hood, it triggers the abstract ToNumber() operation. Unlike parseInt("42px") which extracts numbers until a letter is found, +"42px" strictly evaluates the whole string and returns NaN if any non-numeric character is present.

// Unary Plus vs parseInt:
console.log(+"42");          // 42 (Number)
console.log(+true);          // 1 (Booleans coerce: true -> 1, false -> 0)
console.log(+false);         // 0
console.log(+"");            // 0 (Empty string coerces to 0)
console.log(+"hello");       // NaN (Cannot convert to number)

// Exponentiation operator (ES2016):
console.log(5 ** 2);         // 25
Output
42
1
0
0
NaN
25

2. Strict Equality (===) vs Loose Equality (==)

JavaScript provides two comparison operators with fundamentally different evaluation algorithms:

  • Strict Equality (===): Follows the Strict Equality Comparison Algorithm. It checks data types first. If the types differ, it returns false immediately without modifying any value.
  • Loose Equality (==): Follows the Abstract Equality Comparison Algorithm. If the operands have different types, the JavaScript engine performs implicit type coercion behind the scenes, converting strings and booleans to numbers before comparing.

=== Strict Equality (Always Use ✅)

Compares both value AND data type without coercion.

5 === "5"          // ❌ false (number vs string)
0 === false        // ❌ false (number vs boolean)
null === undefined // ❌ false (different types)

== Loose Equality (Avoid ⚠️)

Performs hidden type coercion that leads to unexpected bugs.

5 == "5"          // ⚠️ true (coerces "5" -> 5)
0 == false        // ⚠️ true (coerces false -> 0)
null == undefined // ⚠️ true (special language rule)

💡 The Golden Rule of Modern JavaScript

Always use === and !==. Loose equality (==) introduces unpredictable edge cases (such as 0 == "" evaluating to true) that make code fragile and hard to debug.

3. Logical Operators & Short-Circuit Evaluation (&&, ||)

A critical concept in JavaScript: logical operators && and || do not necessarily return a boolean (true or false). Instead, they return the actual operand value that determined the outcome.

Short-circuiting means the engine stops evaluating as soon as the final result is guaranteed:

|| Logical OR (Fallback Pattern)

Evaluates left to right. Returns the first truthy value immediately. If all values are falsy, returns the last operand.

"Alex" || "Default" // ➔ "Alex"
"" || "Guest"        // ➔ "Guest"

&& Logical AND (Guard Pattern)

Evaluates left to right. Returns the first falsy value immediately. If all values are truthy, returns the last operand.

true && "Show UI"   // ➔ "Show UI"
false && "Show UI"  // ➔ false
// 1. Fallback pattern with ||
let username = "";
let greeting = username || "Anonymous User";
console.log(greeting); // "Anonymous User"

// 2. React Guard Pattern with &&
const user = { isLoggedIn: true, name: "Anshuman" };
const uiHeader = user.isLoggedIn && `Welcome back, ${user.name}!`;
console.log(uiHeader); // "Welcome back, Anshuman!"
Output
Anonymous User
Welcome back, Anshuman!

4. Nullish Coalescing (??) vs Logical OR (||)

Why was the Nullish Coalescing Operator (??) added in ES2020?

The || operator treats all falsy values (0, false, "", NaN, null, undefined) as missing. This creates critical bugs when 0 is a completely valid value (such as a game score, zero balance, or quantity).

In contrast, ?? checks only for nullish values: strictly null and undefined.

The Zero / False Bug with || ❌

Treats valid 0 and false as falsy, accidentally overwriting them.

let userScore = 0;
let finalScore = userScore || 50;
console.log(finalScore);
// ➔ 50 (Bug! Overwrote valid 0 score)

Safe Default with ?? ✅

Preserves 0, false, and "". Only defaults on null/undefined.

let userScore = 0;
let finalScore = userScore ?? 50;
console.log(finalScore);
// ➔ 0 (Correct! Preserved legitimate 0)

5. Safe Deep Navigation: Optional Chaining (?.)

In JavaScript, attempting to access a property on null or undefined throws a runtime exception: TypeError: Cannot read properties of undefined, which crashes web applications.

Optional Chaining (?.) safely short-circuits property access. If the value before ?. is null or undefined, JavaScript stops evaluation and immediately returns undefined without throwing an error.

const student = {
    name: "Alex",
    address: {
        city: "Bangalore"
    }
};

// 1. Safe Property Access
console.log(student.address?.city);     // "Bangalore"
console.log(student.contact?.phone);    // undefined (Safe! Does NOT crash)

// 2. Combining Optional Chaining (?.) with Nullish Coalescing (??)
const email = student.contact?.email ?? "No email provided";
console.log(email);                     // "No email provided"

// 3. Safe Method Calls (?.)
console.log(student.calculateGPA?.());  // undefined (Does not crash if method missing)

// 4. Safe Array Indexing (?.[index])
const userList = null;
console.log(userList?.[0]);             // undefined
Output
Bangalore
undefined
No email provided
undefined
undefined

6. Modern Logical Assignment Operators (??=, ||=, &&=)

Introduced in ES2021, logical assignment operators combine short-circuiting logic with variable assignment:

Operator Name Underlying Logic When It Assigns
a ??= b Nullish Assignment a = a ?? b Assigns b only if a is null or undefined
a ||= b Logical OR Assignment a = a || b Assigns b if a is any falsy value ("", 0, false)
a &&= b Logical AND Assignment a = a && b Assigns b only if a is truthy
// Practical Example: Setting default configuration
const serverConfig = {
    port: 8080,
    timeout: null
};

serverConfig.port ??= 3000;    // Remains 8080 (already defined)
serverConfig.timeout ??= 5000; // Updated to 5000 (was null)

console.log(serverConfig);     // { port: 8080, timeout: 5000 }
Output
{ port: 8080, timeout: 5000 }

7. Operators Interview Deck

Test your understanding of JavaScript operator quirks and tricky interview evaluation scenarios:

🎯 Operators Interview Deck
Question 1 of 5
⭐ Easy • Zero Fallback Bug || vs ??
const count = 0;
console.log(count || 50, count ?? 50);
What will be printed to the console?
A) 0, 0
B) 50, 0
C) 0, 50
D) 50, 50
⭐ Easy • Type Coercion == vs ===
console.log("5" == 5, "5" === 5);
What will be printed to the console?
A) true, true
B) false, false
C) true, false
D) false, true
⚡ Medium • Optional Chaining ?. Operator
const settings = {};
console.log(settings.theme?.fontSize);
What will be printed to the console?
A) TypeError: Cannot read properties of undefined
B) undefined
C) null
D) false
⚡ Medium • Short-Circuiting && Evaluation
let score = 0;
const result = false && (score += 10);
console.log(result, score);
What will be printed to the console?
A) false 0
B) 10 10
C) false 10
D) 0 0
⭐ Easy • Logical Assignment ??= Assignment
let port = 8080;
port ??= 3000;
console.log(port);
What will be printed to the console?
A) 3000
B) null
C) 8080
D) undefined

8. Practice Challenge

🎯 Coding Challenge: Modern Operators

1. Create a variable score = 0 and use ?? to set a fallback of 50. Print it.
2. Safely read user.details?.email using optional chaining and nullish coalescing to print "No email provided" if missing.
3. Use ??= to assign 10 to count = null.

Your output will appear here.