JavaScript Tips & Tricks
Syntax Shortcuts and Essentials:
const isAdult = age >= 18 ? "Yes" : "No";
function greet(name = "Guest") {
return `Hello, ${name}`;
}
const add = (a, b) => a + b;
const { name, age } = person;
const [first, second] = colors;
const message = `Hi, ${user.name}!`;
const newArray = [...oldArray, 4];
function sum(...numbers) {
return numbers.reduce((a, b) => a + b);
}
const street = user?.address?.street;
const username = inputName ?? "Anonymous";
Logic, Loops and Arrays:
const status = isLoggedIn && "Welcome!";
user.name ||= "Guest";
settings.debug &&= false;
const age = 30;
const person = { name, age };
const key = "level";
const player = { [key]: 42 };
for (const item of items) {
console.log(item);
}
items.forEach((item) => console.log(item));
const squared = nums.map((n) => n * n);
const evens = nums.filter((n) => n % 2 === 0);
const total = nums.reduce((a, b) => a + b, 0);
Object & Array Utilities:
const found = list.includes("apple");
const unique = [...new Set(array)];
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value);
});
const vals = Object.values(obj);
const keys = Object.keys(obj);
const result = data.filter((a) => a.active).map((a) => a.name);
const flat = arr.flat();
const cleaned = str.trim();
const padded = "5".padStart(2, "0");
const price = new Intl.NumberFormat().format(1234567);
Modern Tricks & Utilities:
const module = await import("./module.js");
await Promise.all([fetchData(), loadUI()]);
const fetchData = async () => {
const res = await fetch(url);
return res.json();
};
function log(message, level = "info") {
console[level](message);
}
const num = +"42";
const isTrue = !!value;
[a, b] = [b, a];
const chars = [..."hello"];
const copy = { ...original };
const debounce = (fn, delay) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
};