DEV Community

Hacker Pro
Hacker Pro

Posted on

πŸ”₯ 10 JavaScript Tips with Code Snippets You Should Know

Hey devs! πŸ‘‹

Whether you're just starting with JavaScript or already knee-deep in frameworks, it's always a good idea to keep your core JS skills sharp.

Here are 10 simple but powerful JavaScript tips, each with an example you can copy-paste and play with right away.
Let’s dive in! πŸ§ πŸ’»


βœ… 1. map() vs forEach() β€” Know When to Use

const numbers = [1, 2, 3, 4];

const mapped = numbers.map(num => num * 2);   // returns new array
const forEachResult = [];

numbers.forEach(num => forEachResult.push(num * 2));

console.log(mapped);        // [2, 4, 6, 8]
console.log(forEachResult); // [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

🧠 Tip: Use map() when you want to return a new array. Use forEach() when you just want to run side effects (like logging or pushing).

βœ… 2. Optional Chaining Saves You from Errors

const user = {
  name: 'John',
  address: {
    city: 'Dhaka'
  }
};

console.log(user?.address?.city);     // 'Dhaka'
console.log(user?.contact?.email);    // undefined (no crash!)
Enter fullscreen mode Exit fullscreen mode

🧠 Tip: Use optional chaining (?.) to safely access deeply nested properties without throwing runtime errors.

βœ… 3. Nullish Coalescing vs Logical OR

const count = 0;

const result1 = count || 10;    // 10 ❌
const result2 = count ?? 10;    // 0 βœ…

console.log(result1); // 10
console.log(result2); // 0
Enter fullscreen mode Exit fullscreen mode

🧠 Tip: Use ?? when you want to preserve valid falsy values like 0, false, or "".

βœ… 4. Clean Object Access with Destructuring

const person = {
  name: "Alice",
  age: 28,
  location: "Chittagong"
};

const { name, age } = person;

console.log(name); // Alice
console.log(age);  // 28
Enter fullscreen mode Exit fullscreen mode

🧠 Tip: Destructuring makes your code more concise and readable, especially when dealing with props or API responses.

βœ… 5. setTimeout Inside Loops β€” Use let, Not var

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000); // 3 3 3 ❌
}

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000); // 0 1 2 βœ…
}
Enter fullscreen mode Exit fullscreen mode

🧠 Tip: Use let in loops with async logic. var is function-scoped, let is block-scoped.

βœ… 6. Convert String to Number Quickly

const str = "42";

console.log(+str);          // 42
console.log(Number(str));   // 42
console.log(parseInt(str)); // 42
Enter fullscreen mode Exit fullscreen mode

🧠 Tip: The unary + operator is a fast and clean way to convert strings to numbers.

βœ… 7. Copy Objects Without Side Effects

const original = { name: "Dev", age: 25 };
const copy = { ...original };

copy.name = "Code";

console.log(original.name); // Dev
console.log(copy.name);     // Code
Enter fullscreen mode Exit fullscreen mode

🧠 Tip: Use the spread operator { ...obj } to create shallow copies and avoid unintended mutations.

βœ… 8. Filter Arrays Like a Pro

const numbers = [1, 2, 3, 4, 5, 6];

const even = numbers.filter(n => n % 2 === 0);

console.log(even); // [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

🧠 Tip: .filter() returns a new array containing only the values that match your condition.

βœ… 9. Check If an Object Is Empty

const obj = {};

const isEmpty = Object.keys(obj).length === 0;

console.log(isEmpty); // true
Enter fullscreen mode Exit fullscreen mode

🧠 Tip: A simple and effective way to validate API responses, form data, and configs.

βœ… 10. Default Parameters in Functions

function greet(name = "Developer") {
  return `Hello, ${name}!`;
}

console.log(greet());        // Hello, Developer!
console.log(greet("Shaun")); // Hello, Shaun!
Enter fullscreen mode Exit fullscreen mode

🧠 Tip: Default parameters help you write cleaner functions without repetitive if checks.


These small, clean, and efficient JavaScript tips can have a big impact on your daily workflow.
They help write bug-free, readable, and maintainable code β€” whether you're building frontend UIs or backend services.

Got a favorite JS tip?
Let me know in the comments or share this with your fellow devs! πŸš€

Top comments (0)