DEV Community

Discussion on: Modify global variables in 2020 🤔

Collapse
 
pentacular profile image
pentacular • Edited

You are modifying it when you call getID.

The difference is that you're using a mechanism which enforces a policy of access to that piece of global state.

Which should tell us that this problem isn't about global variables -- it's about policy enforcement.

If you have es6 modules available, I'd recommend using those to provide this kind of policy mechanism.

// userCounter.js

let id = 0;

export const getNextUserId = () => id++;
Enter fullscreen mode Exit fullscreen mode

// foo.js

import { getNextUserId } from './userCounter.js';
Enter fullscreen mode Exit fullscreen mode

// bar.js

import { getNextUserId } from './userCounter.js';
Enter fullscreen mode Exit fullscreen mode

Which also solves the problem of ensuring that the same counter is used properly in each context that requires that counter.

Collapse
 
daniacu profile image
DaniAcu

Yeah you right, I just use a funny title. Yeah any encapsulation that protects the access to the variable is valid. Thanks for sharing 😊