DEV Community

Lukas Gaucas
Lukas Gaucas

Posted on

Don't use explicit const in global scope of JavaScript

Global scope should be exploited as little as possible, although if exploited too much (relatively) it's referred to "global pollution" . But if it happened you had no choice, do but just not this way :

const f = {
    namespace: "NS_F"
}
f // {namespace: 'NS_F'}
// let's garbage collect it :
f = null; // Assignment to constant variable
// SOLUTION is to swap CONST with LET, although...
Enter fullscreen mode Exit fullscreen mode

... Although if you a OKAY to garbage collect it as soon as job is done, choose this run-to-completion (functional) approach :

// function declaration
function f () {
    return {namespace: "NS_F"}
}
f() // {namespace: 'NS_F'}
// run the following separately :
f = null;
// run the following separately :
f() // f is not a function
// Hooray !
Enter fullscreen mode Exit fullscreen mode

Nearly best solution is to use weakSet(s) or weakMap(s) – read this


Thanks & see in the next one !

Top comments (0)