Top 30 JavaScript Tricks Every Developer Should Know

shafayeat

Shafayet Hossain

Posted on October 25, 2024

Top 30 JavaScript Tricks Every Developer Should Know

Whether you’re new to JavaScript or have been coding for years, there are always new tricks and tips that can make your coding life easier. In this post, we’ll dive into 30 essential JavaScript tricks that will not only improve your code but also boost your productivity!

1. Use const and let Instead of var

Say goodbye to var! Using const and let helps prevent scope-related issues and makes your code more predictable.

2. Default Function Parameters

Set default values for function parameters to avoid undefined values.

function greet(name = "Guest") {
    console.log(`Hello, ${name}`);
}
Enter fullscreen mode Exit fullscreen mode

3. Arrow Functions for Cleaner Code

Arrow functions offer a cleaner syntax and handle this context more intuitively.

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

4. Destructuring Arrays and Objects

Destructuring simplifies extracting values from arrays and objects.

const [x, y] = [1, 2];
const { name, age } = { name: "John", age: 30 };
Enter fullscreen mode Exit fullscreen mode

5. Spread Operator for Merging Arrays/Objects

Spread syntax is great for copying and merging arrays or objects.

const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

6. Template Literals for Cleaner Strings

Use backticks for multi-line strings and variable interpolation.

const name = "Alice";
console.log(`Hello, ${name}!`);
Enter fullscreen mode Exit fullscreen mode

7. Optional Chaining (?.)

Access deeply nested object properties without worrying about errors.

const user = { address: { street: "Main St" } };
console.log(user?.address?.street); // Main St
Enter fullscreen mode Exit fullscreen mode

8. Nullish Coalescing Operator (??)

Use ?? to handle nullish values (null or undefined).

let name = null;
console.log(name ?? "Guest"); // Guest
Enter fullscreen mode Exit fullscreen mode

9. Array .map() Method

Easily transform array values.

const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // [2, 4, 6]
Enter fullscreen mode Exit fullscreen mode

10. Array .filter() Method

Filter elements based on a condition.

const numbers = [1, 2, 3, 4];
const evenNumbers = numbers.filter(n => n % 2 === 0); // [2, 4]
Enter fullscreen mode Exit fullscreen mode

11. Array .reduce() Method

Reduce an array to a single value, like sum or product.

const numbers = [1, 2, 3];
const sum = numbers.reduce((total, num) => total + num, 0); // 6
Enter fullscreen mode Exit fullscreen mode

12. Short-Circuit Evaluation

Use && and || for concise conditional logic.

const loggedInUser = user && user.name;
Enter fullscreen mode Exit fullscreen mode

13. Immediately Invoked Function Expressions (IIFE)

Run a function as soon as it's defined.

(function() {
    console.log("This runs immediately!");
})();
Enter fullscreen mode Exit fullscreen mode

14. Memoization for Performance Boosts

Store function results to improve performance in expensive operations.

const memoize = fn => {
    const cache = {};
    return (...args) => {
        if (cache[args]) return cache[args];
        const result = fn(...args);
        cache[args] = result;
        return result;
    };
};
Enter fullscreen mode Exit fullscreen mode

15. Debouncing and Throttling

Optimize event listeners to improve performance by limiting how often functions are called.

const debounce = (func, delay) => {
    let timeout;
    return (...args) => {
        clearTimeout(timeout);
        timeout = setTimeout(() => func(...args), delay);
    };
};
Enter fullscreen mode Exit fullscreen mode

16. Object Property Shorthand

Shorthand for defining object properties with the same name as variables.

const name = "Alice";
const user = { name };
Enter fullscreen mode Exit fullscreen mode

17. Object Method Shorthand

Use shorthand syntax for object methods.

const obj = {
    greet() {
        console.log("Hello!");
    }
};
Enter fullscreen mode Exit fullscreen mode

18. Set Timeout and Set Interval

Control function execution timing using setTimeout() and setInterval().

setTimeout(() => console.log("Runs once after 2 seconds"), 2000);
Enter fullscreen mode Exit fullscreen mode

19. Ternary Operator for Simple Conditions

Make simple if-else statements more concise.

const isAdult = age >= 18 ? "Yes" : "No";
Enter fullscreen mode Exit fullscreen mode

20. Object.freeze() to Make Immutable Objects

Prevent changes to an object.

const obj = Object.freeze({ name: "Alice" });
Enter fullscreen mode Exit fullscreen mode

21. Object.keys(), Object.values(), Object.entries()

Quickly retrieve keys, values, or key-value pairs from an object.

const user = { name: "John", age: 30 };
console.log(Object.keys(user)); // ["name", "age"]
Enter fullscreen mode Exit fullscreen mode

22. Async/Await for Clean Asynchronous Code

Handle asynchronous operations in a more readable way.

async function fetchData() {
    const data = await fetch('/api/data');
    return data.json();
}
Enter fullscreen mode Exit fullscreen mode

23. Promise.all() for Concurrent Async Tasks

Run multiple Promises in parallel and wait for all to resolve.

Promise.all([fetchData1(), fetchData2()]).then(results => console.log(results));
Enter fullscreen mode Exit fullscreen mode

24. Destructuring Function Arguments

Use destructuring directly in function parameters for cleaner code.

function display({ name, age }) {
    console.log(`${name} is ${age} years old`);
}
Enter fullscreen mode Exit fullscreen mode

25. The Power of this

Learn how this behaves in different contexts (functions, classes, arrow functions).

const obj = {
    name: "Alice",
    greet() {
        console.log(this.name);
    }
};
Enter fullscreen mode Exit fullscreen mode

26. Handling Asynchronous Loops

Async functions inside loops require careful handling with await.

for (const item of items) {
    await processItem(item);
}
Enter fullscreen mode Exit fullscreen mode

27. Dynamic Property Names

Use dynamic property keys in objects.

const key = "name";
const user = { [key]: "Alice" };
Enter fullscreen mode Exit fullscreen mode

28. Array .some() and .every() Methods

Check if some or all elements meet a condition.
javascript

const numbers = [1, 2, 3];
console.log(numbers.some(n => n > 2)); // true
console.log(numbers.every(n => n > 0)); // true
Enter fullscreen mode Exit fullscreen mode

29. Named vs Default Exports

Understand the difference between named and default exports in modules.

export default function() {}
export const myFunction = () => {};
Enter fullscreen mode Exit fullscreen mode

30. Debugging with console.table()

Use console.table() for visualizing objects or arrays in a table format.

console.table([{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }]);
Enter fullscreen mode Exit fullscreen mode

Conclusion

These 30 JavaScript tricks cover a wide range of techniques that every developer should have in their toolkit. Whether you’re looking to improve performance, clean up your code, or enhance readability, these tips will help you write better, more efficient JavaScript. Comment down below if you have any questions...


My website: https://shafayet.zya.me


A meme for you😉

Image description

💖 💪 🙅 🚩
shafayeat
Shafayet Hossain

Posted on October 25, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related