All articles

Dev

10 JavaScript tricks for beginners

· 1 min read

JavaScript powers the modern web. Whether you are just starting out or already have some experience, these 10 tricks will help you write cleaner, safer code.

Trick 1: destructuring. Instead of const name = user.name, write const { name, email } = user. It saves time and improves readability. Trick 2: optional chaining. user?.address?.city safely reaches nested properties without throwing when something is undefined.

Trick 3: template literals. Backticks let you embed variables in strings: `Hello ${name}!`. Trick 4: the spread operator. Copy arrays and objects in one line: const newArr = [...oldArr, newItem]. Trick 5: array methods. map(), filter() and reduce() replace most loops: users.filter(u => u.active).map(u => u.name).

Trick 6: async/await. Forget callback hell and write asynchronous code like synchronous code, with try/catch for errors. Trick 7: the ?? operator (nullish coalescing). const port = config.port ?? 3000 falls back to 3000 only for null or undefined, not for 0 or an empty string as || does. Trick 8: Promise.all. Run independent requests in parallel instead of one after another.

const { name, email } = user;
const city = user?.address?.city ?? 'Unknown';
const greeting = `Hello ${name}!`;
const next = [...oldArr, newItem];
const names = users.filter(u => u.active).map(u => u.name);
const [a, b] = await Promise.all([getA(), getB()]);
const unique = [...new Set(list)];
const copy = structuredClone(obj);

Trick 9: Set for unique values: const unique = [...new Set(list)]. Trick 10: Object.entries and for...of for readable iteration over objects, and structuredClone(obj) for a true deep copy. These tricks are only the beginning. At Nettivo we use them daily to build fast, readable and maintainable web applications: nettivo.no/kontakt.

Free quote

Tell us about the project. We reply in Norwegian, Polish and English.

Free quote