Skip to main content

Command Palette

Search for a command to run...

15+ Most Popular JavaScript Code Snippets

Updated
โ€ข8 min readโ€ขView as Markdown
15+  Most Popular JavaScript Code Snippets
M

Software Engineer ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป. Part Time Open-Source Developer ๐Ÿ›

This blog contains 15+ of the most popular ones with an explanation and ready to apply in your next project ๐Ÿš€

  1. Avoid Unnecessary async-await

    ๐Ÿ‘‡๐ŸปโŒ

     const getUsers = async () => {
       return await fetch("https://yourendpoint.com")
     }
    

    ๐Ÿ‘‡๐Ÿปโœ…

     const getUsers = () => {
       return fetch("https://yourendpoint.com")
     }
    

    Avoid unnecessary async-await. If the function returns a Promise directly, there's no need to await it.Avoid Unnecessary async-await

  2. Stop Using IIFEs

    ๐Ÿ‘‡๐ŸปโŒ

     (async function doSomething(){
       const foo = await bar();
       const baz = foo.qux();
    
       return baz;
     })();
    

    ๐Ÿ‘‡๐Ÿปโœ…

     async function doSomething(){
       const foo = await bar();
       const baz = foo.qux();
    
       return baz;
     }
    
     doSomething();
    

    IIFEs died when modules were born. Let them rest in peace ๐Ÿ™‚
    You don't need them (at least 99% of the cases).

  3. Scroll to a Specific Element (smooth animation)

    Scroll to a specific element with a smooth scrolling animation without CSS ๐Ÿ˜€

    ๐Ÿ‘‡๐Ÿป

     const element = document.getElementById("elem")
    
     element.scrollIntoView({
       behavior: "smooth"        // That simple ๐Ÿ˜Ž
     })
    
  4. Using the Nullish Coalescing Operator

    ๐Ÿ‘‡๐ŸปโŒ

     let price_1 = 0;
     let price_2;
    
     // Assign a default if "price" is not set.
     const defaultPrice_1 = price_1 || 10;
     const defaultPrice_2 = price_2 || 5;
    
     console.log(defaultPrice_1); // 10  ๐Ÿ‘ˆ๐Ÿป๐Ÿ˜ญ (should give 0)
     console.log(defaultPrice_2); // 5
    

    ๐Ÿ‘‡๐Ÿปโœ…

     let price_1 = 0;
     let price_2;
    
     // Assign a default if "price" is not set.
     const defaultPrice_1 = price_1 ?? 10;
     const defaultPrice_2 = price_2 ?? 5;
    
     console.log(defaultPrice_1); // 0  ๐Ÿ‘ˆ๐Ÿป๐Ÿ˜Ž
     console.log(defaultPrice_2); // 5
    

    The second approach is better as it uses the nullish coalescing operator (??) to check if the value is strictly null or undefined instead of falsy.
    In the first approach, if the value price_1 is 0, which is falsy, the default value 10 will be assigned, even though 0 is a valid value. This may lead to incorrect results.

    Using the nullish coalescing operator (??) ensures that the default value is only assigned when the value is strictly null or undefined, which is what we usually intend when setting a default value. This makes the code more reliable and easier to understand.

  5. Avoid the 'Delete' Keyword

    ๐Ÿ‘‡๐ŸปโŒ Don't use the delete keyword

     const browny = {
       age: 21,
       profession: 'Developer'
     }
    
     delete browny.age;
    
     console.log(browny);
     // { profession: 'Developer' }
    

    ๐Ÿ‘‡๐Ÿปโœ… instead, use the rest operator to create a copy without the given property

     const browny = {
       age: 21,
       profession: 'Developer'
     }
    
     const { age, ...newBrowny } = browny
    
     console.log(newBrowny);
     // { profession: 'Developer' }
    
  6. Object Destructuring on Arrays[]

    You can destructure elements from an array using the same syntax as when destructuring objects.

    It's a convenient way to pull out specific elements from an array in a single, clean line of code.

    ๐Ÿ‘‡๐Ÿป

     const countries = [
       'Germany',
       'Switzerland',
       'Amsterdam',
       'Norway'
     ]
    
     const { 0: gm, 3: nw} = countries;
    
     console.log(dk) // Germany
     console.log(nw) // Norway
    
  7. Format the output of JSON.stringify

    ๐Ÿ‘‡๐ŸปโŒ

     const someObject = {
       name: 'Browny',
       age: 32,
       online: true
     };
    
     JSON.stringify(someObject);
     // {"name":"Browny","age":"32","online":"true"}
    

    ๐Ÿ‘‡๐Ÿปโœ… Passing 2 as the third argument will format the output with 2 spaces of indentation.

     const someObject = {
       name: 'Browny',
       age: 32,
       online: true
     };
    
     JSON.stringify(someObject, null, 2);
     // {
     // "name":"Browny",
     // "age":"32",
     // "online":"true"
     // }
    
  8. Pass Arguments as an Object

    ๐Ÿ‘‡๐ŸปโŒ

     const createUser = (username, birthDate, isAdmin, isMod) => {
       // Create User
     }
    
     createUser('Simon', '06-03-2001', false, true)
    

    ๐Ÿ‘‡๐Ÿปโœ…

     const createUser = ({username, birthDate, isAdmin, isMod}) => {
       // Create User
     }
    
     createUser({
       username: 'Browny',
       date: '06-03-2001',
       isAdmin: true,
       isMod: false
     })
    

    Object destructuring allows you to extract specific properties from an object and use them as separate variables. In the second example, the function expects a single object argument with specific properties, and destructuring is used to extract those properties.

    This approach has a few advantages over the first example:

    1. It makes the code more readable and easier to understand because the properties are named in the function call. It is clear what each parameter represents, even without looking at the function definition.

    2. It provides flexibility in the order in which the arguments are passed. In the first example, you have to pass the arguments in a specific order, which can be confusing and error-prone. With object destructuring, the order of the properties doesn't matter, as long as the correct property names are used.

    3. It allows you to provide default values for properties. For example, you could provide a default value for isAdmin or isMod if they are not passed in the object.

  1. Use 'Modules' instead of 'Classes'

    ๐Ÿ‘‡๐ŸปโŒ

     class SomeClass {
       methodOne() {}
       methodTwo() {}
     }
    
     // Usage
     const someClassInstance = new SomeClass();
     someClass.methodOne();
    

    ๐Ÿ‘‡๐Ÿปโœ…

     export const functionOne = () => {};
     export const functionTwo = () => {};
    
     // Usage
     import * as someFunctions from './someFunctions';
    
     someFunctions.functionOne();
    

    Both of these approaches have their advantages and disadvantages, and the choice between them ultimately depends on the specific needs of your project. Here are some factors to consider:

    1. Class-based approach

Advantages:

  • Classes provide a clear structure for organizing related methods and data.

  • Methods can be grouped together and easily referenced using the class instance.

  • Class-based code can be more readable and easier to understand, especially for developers with experience in object-oriented programming.

Disadvantages:

  • Classes can be more verbose and require more boilerplate code than simple functions.

  • Class instances can consume more memory than simple functions.

  1. Function-based approach

Advantages:

  • Functions are generally simpler and more concise than classes.

  • Function-based code can be easier to write and maintain.

  • Functions can be more flexible and can be easily composed with other functions.

Disadvantages:

  • Functions can be more difficult to organize and group together than classes.

  • Function names may clash if multiple modules have similarly named functions.

  1. Don't Extent the Built-ins

    ๐Ÿ‘‡๐ŸปโŒ

    // Custom average function
    Array.prototype.average = function(){
      return this.reduce((acc, elm) => acc + elem ) / this.length;
    }
    
    const list = [1, 2, 3];
    const avg = list.average();
    

    ๐Ÿ‘‡๐Ÿปโœ…

    class ArrayUtils {
    // Custom average function
    static average(list) {
      return list.reduce((acc, elm) => acc + elem ) / list.length;
      }
    }
    
    const list = [1, 2, 3];
    const avg = ArrayUtils.average(list);
    
    1. The first approach modifies the prototype of the Array object by adding an average() method to it. This can have unintended consequences because any code that iterates over an array using a for...in loop will also iterate over the new average() method. This approach can also lead to naming collisions if multiple libraries or functions modify the same prototype.

    2. The second approach uses a static method defined in a separate class called ArrayUtils. This method is called on the class itself rather than on an instance of the class. This approach is more modular and less likely to cause naming collisions or unintended side effects. It's also easier to test because the average() method can be called independently of any other methods or properties.

  1. Use Array.some

    ๐Ÿ‘‡๐ŸปโŒ

    const hasActiveUsers = list.find((user) => user.isActive);
    
    console.log(Boolean(hasActiveUser)); // true
    

    ๐Ÿ‘‡๐Ÿปโœ…

    const hasActiveUsers = list.some((user) => user.isActive);
    
    console.log(hasActiveUser); // true
    

    In scenarios like this, instead of using Array.find(), or manually searching a list for an occurrence, use the array method Array.some() instead.
    It's exactly built for that purpose .๐Ÿ˜‰

  2. 3 Ways to 'fill' an Array[]

    ๐Ÿ‘‡๐Ÿป using the constructor + the fill method

    const arr = new Array(10).fill('๐Ÿˆ๐Ÿˆ');
    

    ๐Ÿ‘‡๐Ÿป using the constructor + map method

    const arr = new Array(10);
    const filledArr = [...arr].map(() => '๐Ÿˆ๐Ÿˆ')
    

    ๐Ÿ‘‡๐Ÿป I bet you didn't know you could do this ๐Ÿ˜„

    const arr = Array.from({length: 10}, () => '๐Ÿˆ๐Ÿˆ');
    
  3. 3 options you can pass to addEventListener

    you probably use addEventListeners all of the time while working with JavaScipt but did you know that you can pass additional options to an addEventListener?

    const element = document.querySelector(".myElem")
    
    element.addEventListener("click", doSomething, {
      capture: false,
      once: true,
      passive: false
    })
    

    Capture :
    This is a boolean value that indicates whether to use the 'capturing' phase (true) or the 'bubbling' phase (false) for the event. If set to true, the event listener will trigger during the capturing phase instead of the bubbling phase.

    Once :
    This is a boolean value that indicates whether the event listener should be removed after the first time it's triggered. If set to true, the event listener will be removed automatically after it has been triggered once.

    Passive :
    This is a boolean value that indicates whether the event listener will call preventDefault() on the event. If set to true, it indicates that the event listener will not call preventDefault(), which can improve scrolling performance on touch and mobile devices.

  4. Create your own custom HTML Elements

    Did you know you can create custom HTML Elements using JavaScript and then use them in your HTML file like any other element?

    You can create some pretty powerful experiences using this technique.

    class MyElement extends HTMLElement {
      connectedCallback() {
        this.innerHTML = "This is a custom element";
      }
    }
    
    customElements.define("my-element", MyElement)
    

    use it like any other HTML Elements ๐Ÿ‘๐Ÿป

    <body>
      <my-element />
    </body>
    
  5. Use Object.entries to access both 'keys' and 'values'

    ๐Ÿ‘‡๐ŸปโŒ

    Object.keys(someObj).forEach((keys) => {
      const value = someObj[key]
      // Log out 'key' and 'value'
      console.log(key, value)
    })
    

    ๐Ÿ‘‡๐Ÿปโœ…

    Object.entries(someObj).forEach(([key, value]) => {
     // Log out 'key' and 'value'
     console.log(key, value)
    })
    
    1. The Object.entries() method returns an array of key-value pairs, which you can immediately destructure in the function's parameters, making the code more concise.

    2. The Object.keys() method returns an array of keys, so you need to use the [] syntax to get the corresponding values from the object, which can be less readable.

    3. Using Object.entries() makes the code more efficient since you don't need to look up the values for each key separately. The array returned by Object.entries() already contains both the key and its corresponding value.


Let's Connect

Hopefully, this has helped you for learning something new :) As always, you are welcome to leave comments with suggestions, questions, corrections, and any other feedback you find useful.

Thank you for reading!