Skip to main content

Command Palette

Search for a command to run...

JS Fundamentals #7 — 🧪 Mastering JavaScript Operators

Updated
•8 min read•View as Markdown

In this article, we’ll demystify a range of important JS operators.

Assignment Operators

Assign values to variables.

OperatorDescriptionExampleEquivalent to
=Simple assignmentx = 5x = 5
+=Addition assignmentx += 3x = x + 3
-=Subtraction assignmentx -= 3x = x - 3
*=Multiplication assignmentx *= 3x = x * 3
/=Division assignmentx /= 3x = x / 3
%=Modulus assignmentx %= 3x = x % 3
**=Exponentiation assignmentx **= 3x = x ** 3

Comparison Operators

Compare values and return a boolean (true/false).

OperatorDescriptionExampleResult
==Loose Equal to (value)5 == "5"true
===Strict equal (value and type)5 === "5"false
!=Not equal to5 != "6"true
!==Strict not equal5 !== "5"true
>Greater than5 > 3true
<Less than5 < 3false
>=Greater than or equal to5 >= 5true
<=Less than or equal to5 <= 4false

Pre-Increment and Post-Increment

➕ Pre-Increment (++var)

Increments the variable before returning the value.

let a = 1;
let b = ++a; // b = 2, a =2
console.log(++a); // a =3

➕ Post-Increment (var++)

Returns the value before incrementing it.

let a = 1;
console.log(a++); // 1
console.log(a);   // 2

Same applies to -- for decrement.


Logical Operators (&&, ||, !)

&& (AND)

The && operator returns the first falsy value encountered or the last value if all operands are truthy.

true && 'Hello';    // "Hello"
false && 'Hello';   // false

// Basic usage
true && true    // returns true
true && false   // returns false
false && true   // returns false
false && false  // returns false

// Short-circuit evaluation
false && anything   // returns false without evaluating 'anything'

// With non-boolean values
5 && 7          // returns 7 (both are truthy, so last value is returned)
0 && "Hello"    // returns 0 (first falsy value)
"Hello" && ""   // returns "" (empty string is falsy)
[] && {}        // returns {} (both are truthy)

// Practical applications
function greetUser(user) {
  // Only access 'name' property if 'user' exists
  const message = user && user.name ? `Hello, ${user.name}!` : "Hello, guest!";
  return message;
}

|| (OR)

The || operator returns the first truthy value encountered or the last value if all operands are falsy.

null || 'Fallback'; // "Fallback"
0 || 'Hi';          // "Hi"

// Basic usage
true || true    // returns true
true || false   // returns true
false || true   // returns true
false || false  // returns false

// Short-circuit evaluation
true || anything   // returns true without evaluating 'anything'

// With non-boolean values
0 || 5          // returns 5 (first truthy value)
"" || "Hello"   // returns "Hello" (first truthy value)
null || undefined // returns undefined (both falsy, so last value)
false || 0 || "" || null || undefined // returns undefined (all falsy)

// Practical applications
function getUserDisplayName(user) {
  // Provide fallbacks with increasing specificity
  return user.displayName || user.username || user.email || "Anonymous";
}

! (NOT)

The ! operator converts the operand to a boolean and then negates it.

// Basic usage
!true     // returns false
!false    // returns true

// With non-boolean values (converts to boolean first, then negates)
!0        // returns true (0 is falsy)
!"Hello"  // returns false ("Hello" is truthy)
!""       // returns true (empty string is falsy)
!{}       // returns false (empty object is truthy)
![]       // returns false (empty array is truthy)
!null     // returns true (null is falsy)
!undefined // returns true (undefined is falsy)

// Double negation (!!) - converts a value to its boolean equivalent
!!0       // returns false
!!"Hello" // returns true
!!""      // returns false
!!{}      // returns true

// Practical applications
function isArrayEmpty(arr) {
  return !(arr && arr.length); // Returns true if array is null, undefined, or empty
}

Double Negation (!!)

Converts any value to its boolean equivalent.

!!0       // returns false
!!"Hello" // returns true
!!""      // returns false
!!{}      // returns true

Use it to check the truthiness of a value explicitly.


Nullish Coalescing Operator (??)

The ?? operator returns the right-hand operand when the left-hand operand is null or undefined, otherwise returns the left-hand operand.

// Basic usage
null ?? "default"      // returns "default"
undefined ?? "default" // returns "default"
0 ?? "default"         // returns 0 (0 is not null or undefined)
"" ?? "default"        // returns "" (empty string is not null or undefined)
false ?? "default"     // returns false

// Chaining multiple values
null ?? undefined ?? "default" // returns "default"

// Practical applications
function getConfig(options) {
  // Only use default if value is null or undefined
  // This allows falsy values like 0 or "" to be valid settings
  const timeout = options.timeout ?? 3000;
  const retries = options.retries ?? 5;
  return { timeout, retries };
}

Does not trigger on false, 0, or ''.


Logical Assignment Operators (||=, &&=, ??=)

Combine assignment with logical checks.

Logical AND assignment (&&=)

Assigns the right operand to the left only if the left operand is truthy.

// Equivalent to: x = x && y
let x = 10;
x &&= 5;  // x becomes 5 (since x was truthy)

let y = 0;
y &&= 5;  // y remains 0 (since y was falsy)

// Practical example
function updateUserSettings(settings) {
  // Only update if 'darkMode' setting exists
  settings.darkMode &&= { enabled: true, contrast: "high" };
}

Logical OR assignment (||=)

Assigns the right operand to the left only if the left operand is falsy.

// Equivalent to: x = x || y
let x = 0;
x ||= 5;  // x becomes 5 (since x was falsy)

let y = 10;
y ||= 5;  // y remains 10 (since y was truthy)

// Practical example
function ensureDefaultSettings(settings) {
  // Set defaults only if properties are falsy
  settings.theme ||= "light";
  settings.fontSize ||= "medium";
}

Nullish coalescing assignment (??=)

Assigns the right operand to the left only if the left operand is null or undefined.

// Equivalent to: x = x ?? y
let x = undefined;
x ??= 5;  // x becomes 5 (since x was undefined)

let y = 0;
y ??= 5;  // y remains 0 (since y was not null/undefined)

// Practical example
function initializeConfig(config) {
  // Only initialize if properties are null or undefined
  // This preserves falsy values like 0 or ""
  config.timeout ??= 3000;
  config.maxRetries ??= 5;
  config.autoSave ??= true;
}

Conditional (Ternary) Operator 🔀🤔

The only JavaScript operator that takes three operands.

condition ? valueIfTrue : valueIfFalse

// Example
let age = 20;
let status = age >= 18 ? 'adult' : 'minor';
// status = 'adult'
// Nested ternary operator
let result = age < 13 ? 'child' : (age < 18 ? 'teenager' : 'adult');

Bitwise Operators

Operate at the binary level.

Common ones:

  • & – AND

  • | – OR

  • ^ – XOR

  • ~ – NOT

  • << – Left Shift

  • >> – Right Shift

5 & 3;  // 1  => (101 & 011 = 001)
5 | 3;  // 7  => (101 | 011 = 111)
5 ^ 3;  // 6  => (101 ^ 011 = 110)
~5;     // -6 => Bitwise NOT

How to convert decimal to binary
15 / 2 = 7 (1)
7 / 2 = 3 (1)
3 / 2 = 1 (1)

15 = 1111 in binary. (See the remainders from top to bottom)

9 / 2 = 4(1)
4 / 2 = 2(0)
2 / 2 = 1(0)

9 = 1001 in binary (See the remainders from top to bottom)

 9 << 2 (left shift)
1001 << 2 = 100100 = 36

9 >> 2 
1001 >> 2 = 00010 = 2

Useful in performance optimization, flags, and low-level logic.

typeof Operator

Returns a string indicating the data type.

typeof 42;          // "number"
typeof 'hello';     // "string"
typeof undefined;   // "undefined"
typeof null;        // "object" (quirky but true)
typeof {};          // "object"
typeof (() => {});  // "function"
typeof function abc(){} // "function"
typeof [1,2,3]  // "object"

Great for type-checking in dynamic code.


instanceof Operator

Checks if an object is an instance of a constructor.

let date = new Date();
console.log(date instanceof Date);      // true
console.log([] instanceof Array);       // true
console.log({} instanceof Object);      // true

class Vehicle {}
const myCar = new Vehicle();
myCar instanceof Vehicle;  // true ✅

Note: Doesn’t work with primitives (42 instanceof Number is false).


✍️ Final Thoughts

JavaScript operators can feel overwhelming at first — but they’re your best friends once you understand how they behave under the hood. Use them wisely to write shorter, cleaner, and smarter code.