15+ Most Popular JavaScript Code Snippets

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 ๐
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
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).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 ๐ })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); // 5The second approach is better as it uses the nullish coalescing operator (
??) to check if the value is strictlynullorundefinedinstead of falsy.
In the first approach, if the valueprice_1is0, which is falsy, the default value10will be assigned, even though0is 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 strictlynullorundefined, which is what we usually intend when setting a default value. This makes the code more reliable and easier to understand.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' }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) // NorwayFormat 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" // }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:
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.
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.
It allows you to provide default values for properties. For example, you could provide a default value for
isAdminorisModif they are not passed in the object.
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:
- 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.
- 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.
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);The first approach modifies the prototype of the
Arrayobject by adding anaverage()method to it. This can have unintended consequences because any code that iterates over an array using afor...inloop will also iterate over the newaverage()method. This approach can also lead to naming collisions if multiple libraries or functions modify the same prototype.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 theaverage()method can be called independently of any other methods or properties.
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); // trueIn scenarios like this, instead of using
Array.find(), or manually searching a list for an occurrence, use the array methodArray.some()instead.
It's exactly built for that purpose .๐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 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 callpreventDefault()on the event. If set to true, it indicates that the event listener will not callpreventDefault(), which can improve scrolling performance on touch and mobile devices.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>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) })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.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.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 byObject.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!



