20 JavaScript Tricks Every Developer Must Know 🚀
Jagroop Singh

Jagroop Singh @jagroop2001

About: 👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views

Location:
India
Joined:
Apr 5, 2022

20 JavaScript Tricks Every Developer Must Know 🚀

Publish Date: Oct 28 '24
516 71

JavaScript is a powerful, flexible language, and knowing a few cool tricks can make your code cleaner, faster, and more efficient. Below are 20 practical JavaScript tips and tricks that you can use in real-world applications to enhance your development process.


1. Destructure and Rename in One Step

You can rename variables during object destructuring, which is helpful when there are naming conflicts.

const user = { name: 'Alice', age: 25 };
const { name: userName, age: userAge } = user;
console.log(userName); // Alice
console.log(userAge);  // 25
Enter fullscreen mode Exit fullscreen mode

2. Optional Chaining with Function Calls

Optional chaining can be used with functions, ensuring the function exists before it’s called.

const user = {
  getName: () => 'Alice',
};
console.log(user.getName?.());   // Alice
console.log(user.getAge?.());    // undefined
Enter fullscreen mode Exit fullscreen mode

3. Use ||= Operator for Default Assignment

The logical OR assignment (||=) assigns a value only if the variable is null or undefined or falsey value like 0.

let count;
count ||= 10;
console.log(count); // 10
Enter fullscreen mode Exit fullscreen mode

4. Convert NodeList to Array Using Spread Operator

The spread operator provides a quick way to convert a NodeList to an array.

const divs = document.querySelectorAll('div');
const divArray = [...divs];
console.log(Array.isArray(divArray)); // true
Enter fullscreen mode Exit fullscreen mode

5. Array/Object Destructuring with Default Values

Assign default values during destructuring to avoid undefined when keys are missing.

const user = { name: 'Alice' };
const { name, age = 25 } = user;
console.log(age); // 25
Enter fullscreen mode Exit fullscreen mode

6. Remove Falsy Values from an Array

Use filter() to remove falsy values (like 0, null, undefined, false) from an array.

const arr = [0, 'hello', null, 42, false, 'world'];
const filtered = arr.filter(Boolean);
console.log(filtered); // ["hello", 42, "world"]
Enter fullscreen mode Exit fullscreen mode

7. Sorting Arrays of Objects by Property

Easily sort an array of objects by a specific property.

const users = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 20 }];
users.sort((a, b) => a.age - b.age);
console.log(users); // [{ name: 'Bob', age: 20 }, { name: 'Alice', age: 25 }]
Enter fullscreen mode Exit fullscreen mode

8. Dynamic Imports for Lazy Loading

Dynamic imports allow you to load modules only when needed, reducing initial load time.

const loadModule = async () => {
  const module = await import('./myModule.js');
  module.default(); // Calls the default export function
};
loadModule();
Enter fullscreen mode Exit fullscreen mode

9. Default Parameters with Object Destructuring

When using default parameters, you can also destructure and set defaults for specific properties.

function createUser({ name = 'Guest', age = 18 } = {}) {
  console.log(name, age);
}
createUser();               // Guest 18
createUser({ name: 'Alice' }); // Alice 18
Enter fullscreen mode Exit fullscreen mode

10. Use Object.assign() for Shallow Copying

Object.assign() is handy for shallow-copying objects without changing the original.

const original = { a: 1, b: 2 };
const copy = Object.assign({}, original);
copy.a = 3;
console.log(original.a); // 1 (unchanged)
Enter fullscreen mode Exit fullscreen mode

Follow me on github:

Jagroop2001 (Jagroop) · GitHub

👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire - Jagroop2001

favicon github.com

11. Memoize Functions for Performance

Memoization caches results of expensive function calls based on arguments, useful for computationally heavy functions.

const memoize = (fn) => {
  const cache = {};
  return (...args) => {
    const key = JSON.stringify(args);
    if (!cache[key]) {
      cache[key] = fn(...args);
    }
    return cache[key];
  };
};
const slowSquare = (n) => n * n;
const memoizedSquare = memoize(slowSquare);
console.log(memoizedSquare(4)); // 16 (cached on second call)
Enter fullscreen mode Exit fullscreen mode

12. Using reduce to Group Array Items

reduce() can group array items based on a property, often needed in data processing.

const people = [
  { name: 'Alice', role: 'admin' },
  { name: 'Bob', role: 'user' },
  { name: 'Charlie', role: 'admin' },
];
const grouped = people.reduce((acc, person) => {
  (acc[person.role] = acc[person.role] || []).push(person);
  return acc;
}, {});
console.log(grouped);
// { admin: [{ name: 'Alice' }, { name: 'Charlie' }], user: [{ name: 'Bob' }] }
Enter fullscreen mode Exit fullscreen mode

13. Flatten Nested Arrays with Array.flat(Infinity)

Flattening multi-level nested arrays becomes straightforward with Array.flat(Infinity).

const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

14. Toggle Boolean Value with !

Toggling a boolean value is as easy as applying the NOT operator twice.

let isVisible = false;
isVisible = !isVisible;
console.log(isVisible); // true
Enter fullscreen mode Exit fullscreen mode

15. Merge Multiple Arrays with concat()

concat() is helpful for merging multiple arrays in a single statement.

const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
const merged = arr1.concat(arr2, arr3);
console.log(merged); // [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

16. Asynchronous Array Iteration with for...of and await

When iterating over an array of promises, for...of with await ensures that each promise resolves before the next one runs.

const fetchData = async () => {
  const urls = ['url1', 'url2'];
  for (const url of urls) {
    const response = await fetch(url);
    console.log(await response.json());
  }
};
Enter fullscreen mode Exit fullscreen mode

17. Get the Last Item in an Array Quickly

Retrieve the last item in an array without needing to know the length.

const arr = [1, 2, 3, 4];
console.log(arr.at(-1)); // 4
Enter fullscreen mode Exit fullscreen mode

18. Use Intl for Date Formatting

Intl.DateTimeFormat offers a powerful way to format dates across locales.

const date = new Date();
const formatted = new Intl.DateTimeFormat('en-GB', {
  dateStyle: 'full',
}).format(date);
console.log(formatted); // e.g., "Monday, 25 October 2021"
Enter fullscreen mode Exit fullscreen mode

19. Round Numbers with Math.round() and Template Literals

Template literals can format rounded numbers directly.

const num = 3.14159;
console.log(`${Math.round(num * 100) / 100}`); // 3.14
Enter fullscreen mode Exit fullscreen mode

20. Convert Array-Like Objects to Arrays Using Array.from()

Use Array.from() to convert array-like objects (e.g., arguments) into real arrays.

function example() {
  const argsArray = Array.from(arguments);
  console.log(argsArray);
}
example(1, 2, 3); // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Each of these tricks simplifies common coding patterns in JavaScript. Integrate them into your workflow to write code that is both efficient and expressive.

Happy coding! 🚀

Comments 71 total

  • sewiko
    sewikoOct 28, 2024

    This one is very new to me :

    let count;
    count ||= 10;
    console.log(count); // 10
    
    Enter fullscreen mode Exit fullscreen mode

    I really want such kind of functionality and till now I thought it doesn't exist but thanks to use. Now I don't require extra check for undefined or null value.

    This is very very useful to me and also other tips as well.
    Thanks for sharing @jagroop2001

    • Jagroop Singh
      Jagroop SinghOct 28, 2024

      Thanks @hraifi , I also learn this from one of my senior.

      • sewiko
        sewikoOct 28, 2024

        I find your all blogs to be quite informative.

    • Samuel Rouse
      Samuel RouseOct 28, 2024

      I recommend using ??= Nullish Coalescing Assignment rather that Logical OR assignment unless you specifically want to exclude falsy values rather than just nullish.

      • Jagroop Singh
        Jagroop SinghOct 29, 2024

        @oculus42 ,
        Great recommendation! Using ??= (Nullish Coalescing Assignment) is indeed a better choice when you want to assign values only if the left-hand side is null or undefined, excluding other falsy values. It helps avoid unintended overrides when falsy values like 0 or '' are present. Thanks for highlighting that distinction! If you have more tips, feel free to share!

    • Nick A
      Nick AOct 29, 2024

      Yeah, I actually have never use that before either, I usually use ?? for a fallback value if I expect something maybe undefined/null.

      • Jagroop Singh
        Jagroop SinghOct 29, 2024

        @jovian ,
        That makes sense! The ?? operator is great for providing fallback values, especially when you want to handle undefined or null specifically

    • anirudh7065
      anirudh7065Oct 30, 2024

      Same here i have never seen this ||= or this ??=

    • Berat Yilmaz
      Berat YilmazNov 1, 2024

      This is ninja code; you should avoid such practices in projects. Writing code that is easily readable at a glance is important.

    • Erij Maherzia BEN BRAHIM
      Erij Maherzia BEN BRAHIMJan 22, 2025

      you can use this also
      count ?? 10

  • john
    johnOct 28, 2024

    What's the use of this Dynamic Imports for Lazy Loading?. Is it provide any benefit ?

    • Jagroop Singh
      Jagroop SinghOct 28, 2024

      Hey @john12 ,
      Dynamic imports allows us to load modules only when needed, reducing the initial load time and improving app performance.
      This on-demand loading enhances user experience by ensuring faster interactions and reducing the overall bundle size.
      It also enables code splitting, making it easier to manage and optimize your application efficiently.

      • john
        johnOct 28, 2024

        ohh okay, got it.
        Thank you for this wonderful explanation.

    • huiguang xian
      huiguang xianOct 28, 2024

      improve performance

  • Robert James
    Robert JamesOct 28, 2024

    Thanks for sharing @jagroop2001 Your function is really new for me , and it's also helpful ,

    If I need a background removal service color code which one is perfect for me

    • Jagroop Singh
      Jagroop SinghOct 28, 2024

      Thanks @robertjameszenith for the kind words! 😊 ,
      As per my understanding,
      If you want something with background removal in JavaScript, a tip is to use canvas to manipulate images—applying ctx.clearRect on areas you want transparent works well. You can also use libraries like fabric.js or remove.bg API for more complex removals.

      If it's not what you are looking for please explain your query in detail ?

      • Robert James
        Robert JamesOct 28, 2024

        @jagroop2001 thank you for trying to understand my problem, yes remove bg is automatically remove any kind of photo, but remove.bg do not remove hair photo smoothly. I want to know you how can i implement remove background transparent background with color code in Zenith Clipping front page .

        Image description

        what is the latest code

        • Jagroop Singh
          Jagroop SinghOct 28, 2024

          Okay, I understand your problem however I haven't collide with such type of issue before. remove bg works in my case but you can try pix2pix with TensorFlow.js if remove bg doesn't work. @robertjameszenith

      • Red Ochsenbein (he/him)
        Red Ochsenbein (he/him)Oct 29, 2024

        Look at those bots go... 🤣

  • Roland Csősz
    Roland CsőszOct 28, 2024

    Isn’t the new copy in trick 10 is a deep copy instead of a shallow copy? Shallow copies have the references to the original objects. Deep copies are deep cause there is no reference left in them and you can modify them without changing the originals.

    • Jagroop Singh
      Jagroop SinghOct 29, 2024

      @rolandcsosz ,
      Great observation! The new copy in Trick 10 does indeed create a deep copy, as it avoids references to the original objects. Shallow copies only replicate the first level, retaining references to nested objects. Thanks for clarifying that distinction! It’s an important detail for understanding how data is managed in JavaScript. If you have any more thoughts, I’d love to hear them!

    • Red Ochsenbein (he/him)
      Red Ochsenbein (he/him)Oct 29, 2024

      Try

      const original = { a: { c: 1 }, b: 2 };
      const copy = Object.assign({}, original);
      copy.a.c = 3;
      console.log(original.a.c); // 3 (changed!)
      
      Enter fullscreen mode Exit fullscreen mode

      It's a shallow copy because nested objects stay referenced. For deep copies you should use structuredClone()

      • Roland Csősz
        Roland CsőszOct 29, 2024

        Yes, you are totally right. With nested objects the result will be shallow copy but the example is still a deep copy. Object.assign can create deep and shallow copy based on the original object. The article has beginner hashtag on it and by the context of the trick I felt that the description is not showing example what it originally aimed for. 😅

        • Red Ochsenbein (he/him)
          Red Ochsenbein (he/him)Oct 29, 2024

          You're wrong.

          For deep cloning, we need to use alternatives like structuredClone(), because Object.assign() copies property values.
          If the source value is a reference to an object, it only copies the reference value.

          Source: developer.mozilla.org/en-US/docs/W...

          • Roland Csősz
            Roland CsőszOct 29, 2024

            Nope. I think the problem here is that the example show the deep copy side of this new object with primitive properties. It's clearly says "without changing the original" but it can change the original if it had nested property. Yes, it's a useful trick if someone want to modify the primitive properties of a copy but the statement is not true for all use cases. For an article with the #beginner tag it's not so straightforward in my opinion.

            The copy of an object whose properties all have primitive values fits the definition of both a deep copy and a shallow copy.

            Source: developer.mozilla.org/en-US/docs/G...

  • Himanshu Sorathiya
    Himanshu Sorathiya Oct 28, 2024

    Great list and covering all essentials tricks for any js developer

  • KhanKudo
    KhanKudoOct 28, 2024

    The ||= Operator from Trick 3 would be perfect for Trick 12, really a missed opportunity and classic example of "Do as I say, not as I do" hahaha

    • Jagroop Singh
      Jagroop SinghOct 29, 2024

      @khankudo ,
      Haha, that's a great point! The ||= operator would definitely fit well in Trick 12. It’s a classic case of learning from our own mistakes, right? Thanks for the feedback! If you have any other ideas or tweaks, I’m all ears!

  • Mike Oliver
    Mike OliverOct 28, 2024

    On number 12, you can now just use Object.groupBy, developer.mozilla.org/en-US/docs/W... - however, reduce is extremely powerful and that example is a good example where you need to perform other operations on the grouped data.

    • Jagroop Singh
      Jagroop SinghOct 29, 2024

      @olivergrimsley ,
      Absolutely! With Object.groupBy, it’s become much simpler to group data in one line. But you're right—using reduce allows for more complex operations on the grouped data, making it a valuable tool in many situations. Both approaches have their merits, depending on the use case. Thanks for pointing that out! If you have more insights, I’d love to hear them!

  • Mike 🐈‍⬛
    Mike 🐈‍⬛Oct 28, 2024

    For 19 you don't need to use a template literal, you can just console.log(Math.round(num * 100) / 100); directly

    • Jagroop Singh
      Jagroop SinghOct 29, 2024

      @skhmt ,
      You're absolutely right! Using console.log(Math.round(num * 100) / 100); is a straightforward way to round the number without the extra complexity of a template literal. Thanks for pointing that out! Always good to streamline the code. If you have more insights, feel free to share!

      • Iain Simmons
        Iain SimmonsOct 29, 2024

        Can't you just do num.toFixed(2)?

        • Jagroop Singh
          Jagroop SinghOct 29, 2024

          Yes, using num.toFixed(2) is definitely an option. I prefer this in TypeScript, but keep in mind that it changes the number to a string. If you need to convert it back to a number, you'll have to do that separately, which can be a bit cumbersome.

    • Bondt
      BondtNov 10, 2024

      Also you can allow for decimal precision:

      const round = (num, dec = 2) => { return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec) }```
      
      
      Enter fullscreen mode Exit fullscreen mode
  • Nozibul Islam
    Nozibul IslamOct 29, 2024

    I'm glad you found the JavaScript shortcuts helpful! If you need more specific shortcuts or tricks, especially for any particular task in JavaScript or a particular framework, feel free to ask. It’s a pleasure to share helpful insights!

  • Tracy Gilmore
    Tracy GilmoreOct 29, 2024

    On item 11, it is worth noting that function memorisation only really works for pure functions. If external state is modified and has the potential to impact the output, the cached values cannot be trusted.
    Pure functions: same input => same output.

  • Serhiy
    SerhiyOct 29, 2024

    some of them are new to me! thanks!!!

  • Web
    WebOct 30, 2024

    High quality content for java-script !!

  • Ciphernutz
    CiphernutzOct 30, 2024

    Great list

  • Liyakat Pathan
    Liyakat PathanOct 30, 2024

    Informative content

  • jocedeo
    jocedeoOct 30, 2024

    Great tips from ChatGPT...

    (tip: try and change the name ChatGPT gives, Alice is reserved for ChatGPT examples)

    • Jagroop Singh
      Jagroop SinghOct 31, 2024

      Olay @jocedeo1 but it's not taken from ChatGPT it's from my experience.

      About why I choose name Alice because recently I am doing leetcode basically dynamic programming questions and name Alice is frequently used in a series of it.

      Also nowadays, it's easy to say it's GPT based blogs but in reality I dedicated time to this and put my all efforts to list it down with my full time job and other do's.

  • Idan Entin
    Idan EntinOct 31, 2024

    Thanks! Must save as kind of a cheat-sheet.
    I have this one coming up in PRs to turn big arrays to maped object (or a Map):

    const mapped = Object.fromEntries(
      array.map((item) => [item.id, item])
    )
    
    Enter fullscreen mode Exit fullscreen mode

    Also, for 12 (grouping an array) we have Object.groupBy() coming up 🎉

    • Jagroop Singh
      Jagroop SinghOct 31, 2024

      Nice @idanen , sounds like you've got some great refactoring going on!

    • Rich Winter
      Rich WinterNov 1, 2024

      There's a difference between a Map and an Object.

      • Jagroop Singh
        Jagroop SinghNov 2, 2024

        Yes there is !!

      • Idan Entin
        Idan EntinNov 2, 2024

        Of course. I meant that creating a Map would look pretty similar: const mapped = new Map(array.map((item) => [item.id, item]));

  • Lutfur rahman
    Lutfur rahmanOct 31, 2024

    thanks for sharing

  • Andrew Baisden
    Andrew BaisdenOct 31, 2024

    So many of these are useful I use a few all the time.

  • Greg, The JavaScript Whisperer
    Greg, The JavaScript WhispererOct 31, 2024

    3) is cool but it feels like a code smell.

    Everything else is gold!

  • caga
    cagaNov 1, 2024

    Each tip is very useful.

  • Mehmet Yasin AKAR
    Mehmet Yasin AKARNov 1, 2024

    Nice points, some of them has more modern alternatives like using spreading instead of Object.assign and array concat or Object.groupBy instead of using reduce workaround.

    Using ||= for default values can cause unintended misbehaviors so mentioning ??= is would be nice 👍🏻

  • Tracy Gilmore
    Tracy GilmoreNov 11, 2024

    I have a few more points on this article.

    15. Merge Multiple Arrays with concat()

    There are a couple of alternatives to using Array.concat to combine the values from multiple arrays. There is little to pick between them as they all achieve the same result.

    Alternative 1: Using the spread syntax: const merged = [...arr1, ...arr2, ...arr3];

    Alternative 2: Using the Array.flat method: const merged = [arr1, arr2, arr3].flat();

    11. Memoize Functions for Performance

    I am sure the functions in this article are more for tutorial purposes and not necessarily for production, but there is an important point to make regarding the use of JSON methods (stringify and parse).

    Given what might otherwise appear to be valid input, both methods can throw exceptions. See the following MDN articles for specific details: JSON.stringify and JSON.parse. It is therefore important to guard against such hazards where the source of data is not absolutely known and trusted.

    While we are considering JS tricks, I have one for accessing values (properties) from similar objects. I.e., Object with the same property.

    There is a technique that can help when dealing with object properties called lenses. This is a simple nested function that first takes the name of the property of interest and returns a new function. The second function expects an object and returns the value of the property for the given object.

    // This is a very simple implementation
    function lens(propertyName) {
    return obj => obj[propertyName];
    }
    
    Enter fullscreen mode Exit fullscreen mode

    So how can this help?
    A more sophisticated version would take more than just a top-level property name but could provide an easy method of consistently referencing a deeply nested value from multiple objects..

    const PROPERTY_DECONSTRUCTION = /\]?\??\.\[?|\]?\[|\]/;
    const PROPERTY_STRING_OR_ARRAY_DIGITS = /^(\"([^"]{1,1000})\")|(\d{1,10})$/;
    const removeWrappingDoubleQuites = str => str.replaceAll(/^"|"$/g, '');
    const lensReducer= (ob, pr) =>
        PROPERTY_STRING_OR_ARRAY_DIGITS.exec(pr)
          ? ob[removeWrappingDoubleQuites(pr)]
          : ob?.[pr];
    
    
    function lens(...props) {
      const _props = props
        .join('.')
        .split(PROPERTY_DECONSTRUCTION)
        .filter(item => item !== '');
      return obj => _props.reduce(lensReducer, obj);
    }
    
    Enter fullscreen mode Exit fullscreen mode
Add comment