JS Operators Cheat Sheet

?.
Optional Chaining
Checks each part of the property chain; if any part is null or undefined, it immediately returns undefined instead of continuing.
// object with nested data
const user = { profile: { age: 30 } };

const result = user?.profile?.age;

// result: 30
  
??
Nullish Coalescing
Returns the right-hand value only when the left-hand value is null or undefined.
const value = null;
const result = value ?? 5;

// result: 5
  
??=
Nullish Assignment
Checks whether the left-hand value is null or undefined; if it is, the right-hand value is assigned to it. Otherwise, nothing changes.
let count = null;
count ??= 10;

// result: count = 10
  
||=
Logical OR Assignment
Assigns the right-hand value when the left-hand value is falsy (“”, 0, false, null, undefined).
let title = "";
title ||= "Untitled";

// result: title = "Untitled"
  
&&=
Logical AND Assignment
Assigns the right-hand value only when the left-hand value is truthy.
let isActive = true;
isActive &&= checkStatus();

// result: isActive now depends on checkStatus()
  
!!
Boolean Conversion
Converts any value into a strict boolean true or false.
const value = 0;
const result = !!value;

// result: false
  
&& / ||
Short-Circuit Evaluation
Returns one of the operands based on truthiness instead of just true or false.
const a = "hello" && "world";
const b = "" || "fallback";

// a: "world"
// b: "fallback"
  
Spread Operator
Expands an array or object into individual elements or properties.
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];

// merged: [1, 2, 3, 4]
  
Rest Operator
Collects the remaining arguments or items into a new array.
function sum(...nums) {
  return nums.reduce((a, b) => a + b, 0);
}

// sum(1, 2, 3) returns 6
  
~~
Double Tilde
Quickly truncates a number toward zero (similar to Math.trunc).
const result = ~~3.99;

// result: 3
  
,
Comma Operator
Evaluates each expression from left to right; earlier expressions run but are discarded, and only the value of the final expression is returned.
let x = (console.log("A"), 10);

// logs "A", then x becomes 10
  
void
void Operator
Evaluates an expression but always returns undefined.
const result = void 0;

// result: undefined
  

Leave a Reply

Discover more from Daily Learning

Subscribe now to keep reading and get access to the full archive.

Continue reading