05 - JavaScript Tips and Tricks with Example Code
Learn essential JavaScript tips and tricks with example code, tips, and best practices in simple broken English.
2026-08-28 ยท 6 min read
Hello my friend! Today I show you super useful JavaScript tips and tricks with clear code examples! JavaScript have many cool features and shortcuts that help you write clean code, eliminate bugs, and code faster! Very easy to follow step-by-step. Let's get started!

Tip 1: Variable Declaration (const vs let)
Always declare variables using const by default. Only use let when you know value will change later! Never use var.
// Good practice!
const userName = "Sothea"; // Cannot reassign value, very safe!
let userScore = 10;
userScore = 20; // Can reassign when score changes
๐ก Tip: Using
constby default stops accidental reassignment bugs in your program!
Tip 2: Strict Comparison (=== vs ==)
Always prefer === (strict equality) over == (loose equality) for comparison in JavaScript.
console.log(5 === "5"); // false (Correct! Compare value AND data type)
console.log(5 == "5"); // true (Avoid! JavaScript auto converts type, can cause bug!)
๐ก Tip:
==does type coercion behind the scenes which leads to unexpected bugs! Always use===and!==!
Tip 3: Template Literals (String Interpolation)
Use backticks (``) instead of string concatenation with + sign.
const name = "Dara";
const age = 20;
// Old way
const message1 = "Hello " + name + ", you are " + age + " years old!";
// Modern way with Template Literals!
const message2 = `Hello ${name}, you are ${age} years old!`;
๐ก Tip: Template literals also allow you to create multi-line strings cleanly without using
\n!
Tip 4: Optional Chaining (?.)
Access nested object properties safely without crashing your application when object property is undefined or null.
const user = {
profile: {
name: "Bopha"
}
};
// Safe access! If profile is missing, it returns undefined instead of throwing error!
const name = user?.profile?.name;
๐ก Tip: Use
?.when fetching data from external APIs! It prevents "TypeError: Cannot read properties of undefined" crash!
Tip 5: Nullish Coalescing (??)
Use ?? to provide default fallback value when variable is null or undefined.
const count = 0;
// Nullish coalescing operator
const item1 = count ?? 10; // Result: 0 (0 is valid number!)
// Logical OR operator
const item2 = count || 10; // Result: 10 (0 treated as falsy, might not be what you want!)
๐ก Tip: Use
??instead of||when0or""(empty string) are valid values in your logic!
Tip 6: Destructuring Objects & Arrays
Unpack properties from objects or elements from arrays into distinct variables cleanly.
// Object Destructuring
const user = { name: "Vibol", age: 25, city: "Phnom Penh" };
const { name, age } = user;
// Array Destructuring
const colors = ["Red", "Green", "Blue"];
const [firstColor, secondColor] = colors;
๐ก Tip: Destructuring keeps code short so you don't need to write
user.nameanduser.agerepeatedly!
Tip 7: Spread Operator (...) for Copying & Merging
Use spread operator ... to clone or combine objects and arrays easily.
// Clone and update object
const originalUser = { name: "Kiri", role: "Dev" };
const updatedUser = { ...originalUser, age: 22 };
// Merge arrays
const arr1 = [1, 2];
const arr2 = [3, 4];
const combinedArray = [...arr1, ...arr2]; // [1, 2, 3, 4]
๐ก Tip:
...spread creates shallow copy without mutating original array or object in memory!
Tip 8: Modern Array Methods (map, filter, find, includes)
Transform and search array items without writing old school for loops.
const numbers = [1, 2, 3, 4, 5];
// map(): transform every item
const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]
// filter(): filter items matching condition
const evens = numbers.filter(num => num % 2 === 0); // [2, 4]
// find(): find 1st item matching condition
const found = numbers.find(num => num > 3); // 4
// includes(): check if value exists
const hasThree = numbers.includes(3); // true
๐ก Tip: Use
map()andfilter()for cleaner functional programming! They return new array without changing original array!
Tip 9: Object Helpers (Object.keys, Object.values, Object.entries)
Extract keys, values, or key-value pairs from objects into array format.
const user = { name: "Sok", age: 24 };
console.log(Object.keys(user)); // ["name", "age"]
console.log(Object.values(user)); // ["Sok", 24]
console.log(Object.entries(user)); // [["name", "Sok"], ["age", 24]]
๐ก Tip: Combine
Object.entries(obj)withforEach()loop to iterate over object keys and values together!
Tip 10: Arrow Functions for Short Callbacks
Write short and clean function syntax for callbacks.
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function (clean & concise!)
const add = (a, b) => a + b;
๐ก Tip: Single line arrow functions return result automatically without typing
returnkeyword!
Tip 11: async/await with try...catch Error Handling
Write clean asynchronous code for API requests and catch errors safely.
async function fetchUserData() {
try {
const response = await fetch("https://api.example.com/user");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Fetch failed my friend:", error);
}
}
๐ก Tip: Always wrap
awaitcalls intry...catchblock to handle network issues gracefully!
Tip 12: Developer Console Utilities & Type Checking
Use console.table() to display arrays of objects nicely, and check array types properly.
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
// Display pretty table in browser console!
console.table(users);
// Check if variable is Array
console.log(Array.isArray(users)); // true
๐ก Tip:
typeof []returns"object", which can confuse you! Always useArray.isArray()to check if variable is real array!
Tip 13: Modular Code & ES Modules
Keep functions small, focused on one task, and split code into modules.
// utils.js
export const add = (a, b) => a + b;
// main.js
import { add } from "./utils.js";
๐ก Tip: Avoid global variables! Keeping functions small and modular makes testing and debugging much easier!
Hope these JavaScript tips and tricks help you write clean and efficient code easily! Practice using these tips in your daily projects. Happy learning my friends! Sharing is caring!