🌱BeginnerJavaScript Fundamentals

Operators

Arithmetic, comparison, logical, and assignment operators the building blocks of expressions.

Overview

Operators are symbols that perform operations on values (called operands). JavaScript has a rich set of operators covering arithmetic, comparison, logical operations, assignment, and more. Arithmetic operators (+, -, *, /, %) work on numbers. The + operator is special: when used with strings it performs concatenation instead. This dual behavior is a common source of bugs when types are mixed unexpectedly. Comparison operators return a boolean (true or false). Always use strict equality (===) and strict inequality (!==) rather than loose equality (==, !=) which does type coercion. For example, 0 == false is true due to coercion, while 0 === false is false. Logical operators && (AND), || (OR), ! (NOT) combine boolean expressions. In modern JS they also have useful short-circuit behavior used for default values and conditional execution.

Key Points

  • •Arithmetic: + - * / % (modulo) ** (exponentiation)
  • •Always use === and !== for comparisons to avoid type coercion surprises
  • •&& returns the first falsy value, or the last value if all are truthy
  • •|| returns the first truthy value, or the last value if all are falsy
  • •?? (nullish coalescing) returns the right side only when the left is null or undefined useful for defaults
  • •Compound assignment: +=, -=, *=, /=, %= are shorthands for updating a variable

Examples

Arithmetic operators

console.log(10 + 3);   // 13
console.log(10 - 3);   // 7
console.log(10 * 3);   // 30
console.log(10 / 3);   // 3.3333...
console.log(10 % 3);   // 1  (remainder)
console.log(2 ** 8);   // 256 (exponentiation)

Comparison and strict equality

console.log(5 > 3);    // true
console.log(5 < 3);    // false
console.log(5 >= 5);   // true
console.log("5" == 5); // true  ← coercion, avoid
console.log("5" === 5);// false ← strict, use this
console.log(5 !== 3);  // true

Logical operators and short-circuiting

console.log(true && false);  // false
console.log(true || false);  // true
console.log(!true);          // false

// Short-circuit uses:
const name = null;
console.log(name ?? "Guest");    // "Guest" (null/undefined fallback)
console.log(name || "Guest");    // "Guest" (any falsy fallback)

?? only falls back for null/undefined. || falls back for any falsy value (0, "", false, NaN too).

Common Mistakes

  • Using = (assignment) where you meant === (comparison) inside conditions
  • Using + to add a number and a string "5" + 3 gives "53", not 8
  • Using || for defaults when 0 or "" should be valid values use ?? instead

Exercises

Write JavaScript code to solve each exercise. Run it and check your output.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What does "5" + 3 evaluate to in JavaScript?