JavaScript:JavaScript Operators: Arithmetic, Comparison & Strict Equality
JavaScript•Operators

JavaScript Operators: Arithmetic, Comparison & Strict Equality

Understanding operators, especially strict equality (===) versus loose equality (==) and short-circuit evaluation.

Syntax

const result = a === b ? "equal" : "not equal";

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
===Strict EqualityChecks value and data type without implicit coercion.
??Nullish CoalescingReturns right operand only if left is null or undefined.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// Strict Equality vs Loose Equality
console.log("5 == '5': ", 5 == "5");   // true (type coercion)
console.log("5 === '5':", 5 === "5");  // false (strict check)

// Nullish Coalescing (??) vs Logical OR (||)
const userConfig = { timeout: 0, title: "" };
const timeout1 = userConfig.timeout || 3000;  // 3000 (0 is falsy)
const timeout2 = userConfig.timeout ?? 3000;  // 0 (preserves 0)

console.log("Timeout with ||:", timeout1);
console.log("Timeout with ??:", timeout2);
Expected Output:
5 == '5':  true
5 === '5': false
Timeout with ||: 3000
Timeout with ??: 0

How It Works: Step-by-Step

  • Lines 2-3: Compares loose equality (coercion) against strict type-checking.
  • Lines 6-8: Illustrates why ?? is safer than || when dealing with numeric 0 or empty strings.

Key Concepts

  • Always use === and !== instead of == and != to avoid subtle coercion bugs.
  • Nullish coalescing (??) only falls back on null or undefined, preserving 0 and false.
  • Logical operators evaluate expressions left-to-right with short-circuiting.

Common Mistake: Using loose equality == which triggers implicit type coercion

0 == "" evaluates to true and false == "0" evaluates to true under loose equality.

❌ Incorrect
if (value == 0) { /* matches "" and false! */ }
✅ Correct
if (value === 0) { /* matches only number 0 */ }

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler