Languages
[Edit]
EN

JavaScript - global variable protection / encapsulation

0 points
Created by:
Olivier-Myers
514

In this article, we would like to show you how to protect global variables from being accidentally set to a new value in JavaScript.

For example, by writing window.globalVariableName, we are able to modify the global variable by accident if we do not put it behind some mechanism.

1. Correct solution

In this example, we present how to hide such global variables and protect them from being set to a new value.

// ONLINE-RUNNER:browser;

const object = new function () {
  var counter = 0;
  this.generateId = function () {
    return ++counter;
  };
};

console.log(object.generateId()); // Some action...
console.log(object.generateId()); // Some action...
console.log(object.generateId()); // Some action...
window.counter = 0;
console.log(object.generateId()); // Some action...
console.log(object.generateId()); // Some action...

2. Incrorrect solution

If we do not give a complicated name to a variable, there is a high chance that someone will create or refer to a global variable with the same name, damaging some part of the logic.

The example shows what can happen if we don't hide the counter global variable.

// ONLINE-RUNNER:browser;

var counter = 0;

const generateId = function () {
  return ++counter;
};

console.log(generateId()); // Some action...
console.log(generateId()); // Some action...
console.log(generateId()); // Some action...
window.counter = 0;
console.log(generateId()); // Some action...
console.log(generateId()); // Some action...

Related posts

Alternative titles

  1. JavaScript - correct and incorrect way of generating unique id
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join