DEV Community

56kode
56kode

Posted on

1 1 1 1

Avoiding global functions in JavaScript

Many beginner developers modify global prototypes in JavaScript without realizing the risks. Let's look at a common example: creating a function that finds the difference between two arrays.

A developer might try to extend the native prototype like this:

// Never do this
Array.prototype.diff = function(comparisonArray) {
  const hash = new Set(comparisonArray);
  return this.filter(elem => !hash.has(elem));
};

// Usage
const array1 = [1, 2, 3, 4];
const array2 = [2, 4];
console.log(array1.diff(array2)); // [1, 3]
Enter fullscreen mode Exit fullscreen mode

This approach might look convenient at first, but it creates several serious problems. Name collisions are the main risk: if two libraries add a diff method to the Array prototype, one will override the other. This can make your code behave differently depending on the order scripts load, creating bugs that are hard to find.

Modifying prototypes also affects performance. Each addition to the prototype makes JavaScript work harder when operating on arrays. This slows down your entire application, even parts that don't use the new method.

Fixing bugs becomes harder because errors can appear far from the source of the problem. Standard debugging tools can't easily show where a prototype was modified, making code maintenance difficult.

A much better solution is to create a pure function:

const arrayDiff = (array1, array2) => {
  const hash = new Set(array2);
  return array1.filter(elem => !hash.has(elem));
};

// Usage
const array1 = [1, 2, 3, 4];
const array2 = [2, 4];
const result = arrayDiff(array1, array2); // [1, 3]
Enter fullscreen mode Exit fullscreen mode

This functional approach has many benefits. The function stays isolated and predictable, doesn't change native types, and is easier to test. The code becomes clearer because you can see exactly where the arrayDiff function comes from.

Your code also becomes more portable. Without global changes, there's less risk of conflicts with future JavaScript versions or other libraries. Updating to new versions of frameworks becomes easier.

By using pure functions like this, you create code that's easier to maintain, more reliable, and simpler for all team members to understand.

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay