JavaScript Tips & Tricks

Syntax Shortcuts and Essentials:

// Ternary Operator
const isAdult = age >= 18 ? "Yes" : "No";

// Default Parameters
function greet(name = "Guest") {
  return `Hello, ${name}`;
}

// Arrow Functions
const add = (a, b) => a + b;

// Destructuring Objects
const { name, age } = person;

// Destructuring Arrays
const [first, second] = colors;

// Template Literals
const message = `Hi, ${user.name}!`;

// Spread Operator
const newArray = [...oldArray, 4];

// Rest Parameters
function sum(...numbers) {
  return numbers.reduce((a, b) => a + b);
}

// Optional Chaining
const street = user?.address?.street;

// Nullish Coalescing
const username = inputName ?? "Anonymous";

Logic, Loops and Arrays:

// Short-circuit Evaluation
const status = isLoggedIn && "Welcome!";

// Logical OR Assignment
user.name ||= "Guest";

// Logical AND Assignment
settings.debug &&= false;

// Object Property Shorthand
const age = 30;
const person = { name, age };

// Computed Property Names
const key = "level";
const player = { [key]: 42 };

// For-of Loop
for (const item of items) {
  console.log(item);
}

// forEach Loop
items.forEach((item) => console.log(item));

// Map Function
const squared = nums.map((n) => n * n);

// Filter Function
const evens = nums.filter((n) => n % 2 === 0);

// Reduce Function
const total = nums.reduce((a, b) => a + b, 0);

Object & Array Utilities:

// Includes Check
const found = list.includes("apple");

// Set for Unique Values
const unique = [...new Set(array)];

// Object.entries
Object.entries(obj).forEach(([key, value]) => {
  console.log(key, value);
});

// Object.values
const vals = Object.values(obj);

// Object.keys
const keys = Object.keys(obj);

// Chaining Array Methods
const result = data.filter((a) => a.active).map((a) => a.name);

// Flatten Array
const flat = arr.flat();

// Trim String
const cleaned = str.trim();

// Pad String
const padded = "5".padStart(2, "0");

// Intl.NumberFormat
const price = new Intl.NumberFormat().format(1234567);

Modern Tricks & Utilities:

// Dynamic Import
const module = await import("./module.js");

// Promise.all
await Promise.all([fetchData(), loadUI()]);

// Async/Await
const fetchData = async () => {
  const res = await fetch(url);
  return res.json();
};

// Optional Parameters in Functions
function log(message, level = "info") {
  console[level](message);
}

// Number Conversion with Unary +
const num = +"42";

// Boolean Conversion with !!
const isTrue = !!value;

// Short Array Swap
[a, b] = [b, a];

// Quick String to Array
const chars = [..."hello"];

// Quick Object Clone
const copy = { ...original };

// Debounce Function (Utility)
const debounce = (fn, delay) => {
  let timeout;
  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn(...args), delay);
  };
};