You just use const at global scope:

const aGlobalConstant = 42;

That creates a global constant. It is not a property of the global object (because const, let, and class don't create properties on the global object), but it is a global constant accessible to all code running within that global environment.


It's probably worth noting, though, that the trend is to move away from globals, and in fact even to move away from having any code run at global scope (although top-level scripts in browsers will always have access to global scope, for compatibility).

For instance: In NodeJS, none of your code is running at global scope; everything (including the main script you run via the node command) is in a NodeJS module environment, which is not global scope. So in NodeJS, the line above wouldn't create a global, because it's scoped to the call to your module. To create a true global in NodeJS (which usually isn't necessary), you have to create a property on the global object. But how to access the global object? NodeJS calls your code with this set to an empty object (rather than the usual loose mode default where this refers to the global object), and of course there's no window in NodeJS. Answer: NodeJS provides a global available for that: global

// Define a global constant in NodeJS
Object.defineProperty(global, "aGlobalConstant", {
    value: 42
});

That's a constant because by default, properties created via Object.defineProperty are read-only.

ES2015's modules take it a step further than NodeJS: You cannot create a global at all unless the environment makes a global like NodeJS's global available to you (in which case you can do the Object.defineProperty thing). By default, per spec, there is no such global; it's just environments that define them (window on browsers, global in NodeJS, ...). And the top-level code in an ES2015's module is not run with the old default of this referring to the global object (this has the value undefined at the top-level scope of an ES2015 module), so you can't use this for it.

Answer from T.J. Crowder on Stack Overflow
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Do not know how to fix the code - JavaScript
February 6, 2022 - I am struggling with this error: myGlobal should be declared using the let or const keywords. but I do not know how to fix the code . Can you help me?? Your code so far // Declare your variable here var myGlobal = 10; function fun1() { // Assign 5 to oopsGlobal Here oopsGlobal = 5; } // Only change code above this line function fun2() { var output = ""; if (typeof myGlobal != "undefined") { output += "myGlobal: " + myGlobal; } if (typeof oopsGlobal != "undefined") { output += " oopsGl...
Discussions

Basic JavaScript - Global Scope and Functions
Here are the tasks: myGlobal should be defined Failed:myGlobal should have a value of 10 Passed:myGlobal should be declared using the let or const keywords Failed:oopsGlobal should be a global variable and have a value of 5 Your code so far // Declare the myGlobal variable below this line let ... More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
July 24, 2023
What is the proper to write a global const in javascript es6? - Stack Overflow
What is the right way to write a global const in a script in javascript es6 and use it in some other script? More on stackoverflow.com
🌐 stackoverflow.com
oopsGlobal should be a global variable and have a value of 5
Tell us what’s happening: Describe your issue in detail here. When I remove var from oppsGlobal I only pass the 3rd point( myGlobal should be declared using the let or const keywords). When I add var to oppsGlobal I … More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
1
0
February 23, 2022
Confusion in global variable (var) and block variable (let , const) at node js
I understand that var is a global variable in node js and it can be accessed everywhere. However I was confused by below examples In below, global_1 can be accessed without confusion, as it is glo... More on stackoverflow.com
🌐 stackoverflow.com
March 8, 2022
🌐
GitHub
github.com › Peterfrontenddev1 › Global-Scope-and-Functions
GitHub - Peterfrontenddev1/Global-Scope-and-Functions: In JavaScript,
This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with let or const. Using let or const, declare a global variable named myGlobal outside of any function.
Author   Peterfrontenddev1
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Basic JavaScript - Global Scope and Functions - JavaScript - The freeCodeCamp Forum
July 24, 2023 - Here are the tasks: myGlobal should be defined Failed:myGlobal should have a value of 10 Passed:myGlobal should be declared using the let or const keywords Failed:oopsGlobal should be a global variable and have a value of 5 Your code so far ...
Top answer
1 of 3
23

You just use const at global scope:

const aGlobalConstant = 42;

That creates a global constant. It is not a property of the global object (because const, let, and class don't create properties on the global object), but it is a global constant accessible to all code running within that global environment.


It's probably worth noting, though, that the trend is to move away from globals, and in fact even to move away from having any code run at global scope (although top-level scripts in browsers will always have access to global scope, for compatibility).

For instance: In NodeJS, none of your code is running at global scope; everything (including the main script you run via the node command) is in a NodeJS module environment, which is not global scope. So in NodeJS, the line above wouldn't create a global, because it's scoped to the call to your module. To create a true global in NodeJS (which usually isn't necessary), you have to create a property on the global object. But how to access the global object? NodeJS calls your code with this set to an empty object (rather than the usual loose mode default where this refers to the global object), and of course there's no window in NodeJS. Answer: NodeJS provides a global available for that: global

// Define a global constant in NodeJS
Object.defineProperty(global, "aGlobalConstant", {
    value: 42
});

That's a constant because by default, properties created via Object.defineProperty are read-only.

ES2015's modules take it a step further than NodeJS: You cannot create a global at all unless the environment makes a global like NodeJS's global available to you (in which case you can do the Object.defineProperty thing). By default, per spec, there is no such global; it's just environments that define them (window on browsers, global in NodeJS, ...). And the top-level code in an ES2015's module is not run with the old default of this referring to the global object (this has the value undefined at the top-level scope of an ES2015 module), so you can't use this for it.

2 of 3
3

Great answers above especially the note about "const, let, and class don't create properties on the global object".

Just to add, beware of implications of that as relates to IFrames.

In an IFrame you can access the variables defined in the parent-window (if they come from the same domain) by referring to "parent.someVar".

But because 'const' or 'let' or 'class' won't add to the properties of their global object the iFrame can not access variables defined by const or let in the parent-window. But you CAN if you have defined them as variables with 'var', in the parent window.

In that way 'var' gives you a more global reference than 'const' or 'let'. If you need to create a variable that is available in sub-frames you need to use 'var' to declare it it seems. And but then it will not be a "constant".

So one way to answer your question is to say that while you can define "global variables" by using 'var' you can not define (truly) "global constants" because if they are declared with 'const' they won't be visible in iFrames, if they are defined with 'var' they won't be constants.

Unless there's some way to access consts defined in the parent-window. I haven't found one. Is there?

Top answer
1 of 1
2

I understand that var is a global variable in node js and it can be accessed everywhere.

You're wrong.

var inside a function declares a variable scoped to that function.

var outside of a function declares a variable scoped to that module.

(There's an edge case, that T.J. pointed out, where if you run the code in the global context (e.g. node < yourModule.js) instead of loading it as a normal module (node yourModule.js) then it won't be treated as a module and var outside a function will create a global).

But if I put my function2 inside a help.js ; it said global_1 is undefined ; isnt it that when I import helper function, the effect is same as the above code where I paste my function2 in the same file?

No.

The variables that are "in scope" are determined by where a function is defined, not by where it is called.

As for let and const, my understanding is that they can only be accessed within a {} 

No.

They can't be accessed outside of the block in which they are defined.

In your example they are defined outside of any explicit block, do the whole module is treated as the block for these purposes.


var a = 1;

function b () {
    var c = 2;
    let d = 3;
    
    if (a) {
        let e = 4;
        var f = 5;
        // a b c d e and f are available here
    }
    // a b c d and f are available here
    // e isn't because it is block scoped and this is outside the block
}

// a and b are available here.
// Everything else is scoped to either the function b or the block
// connected to the if statement inside it
Find elsewhere
🌐
How-To Geek
howtogeek.com › home › programming › let, var, and const: defining variables in javascript
Let, Var, and Const: Defining Variables in JavaScript
February 23, 2021 - The value of myGlobal is updated in both functions when testB overwrites it. The newer let keyword is the modern alternative to var. You can often adopt let in all the places you used to write var.
🌐
W3Schools
w3schools.com › js › js_let.asp
JavaScript Let
function myfunction() { var x = 1; let y = 2; const z = 3; } //x can NOT be used here //y can NOT be used here //z can NOT be used here · Variables declared with the var always have Global Scope. Variables declared with the var keyword can NOT have block scope:
Top answer
1 of 4
5

If your variable is declared in the global scope, then it doesn't really matter if you use let or var.

These are functionally identical:

let myVar = 123;
function doStuff() {
  console.log(myVar);
}
doStuff();

var myVar = 123;
function doStuff() {
  console.log(myVar);
}
doStuff();

The difference between var and let becomes significant when you're declaring them in blocks:

if(true) {
  var foo = 1;
}
if(true) {
  let bar = 2;
}

console.log("var foo:", foo);
console.log("let bar:", bar);

As you can see, the let declaration is restricted to its wrapping block scope. The var declaration ignores block scope.

2 of 4
3

Looks like you are attempting to maintain a character's (hero) state in multiple locations. This will become more and more difficult to maintain in a global scope as each character's actions / states will add to the global variables.

As per @jeff-huijsmans suggestion, I believe you should maintain the state inside your game object.

This could be defined in a few ways:

  1. game.state.firePaused - This locks your game state to a single character, but will better contain the state of a character shooting.
  2. game.hero.firePaused - This allows each character to maintain their own shooting state. This also has the added benefit of being able to add more characters with firing states.

As an aside, it looks like most of the answers here are attempting to address the scope issue. Defining variables globally and attempting to maintain a state outside of a function becomes very difficult to understand/read/test. There will be a lot of opinions on this topic. Fortunately for your root issue you can avoid this by using your pre-existing state object.

🌐
Reddit
reddit.com › r/learnjavascript › let vs var, global scope vs local scope
r/learnjavascript on Reddit: LET vs VAR, GLOBAL SCOPE VS LOCAL SCOPE
April 15, 2021 -

Hello, my background is java and I am trying to understand variable declaration deeper. Mainly what the differnces between let and var keywords. I found this great website for those who are still looking to understand.

https://scotch.io/tutorials/understanding-scope-in-javascript#toc-block-statements

But I am still having trouble how LET is not a global scope? If you google let vs var, you will get tons of tables like this:

But can't let be considered global too? Since I can declare it globally. Or is it referring to automatic globlazation? Where even if you declare the variable in block statement, it will automatically set it to globabal variable?

Sheesh, I have under estimated the JS. Thanks.

Keywords for people looking for this:

LET vs VAR,

GLOBAL SCOPE VS LOCAL SCOPE

Global scope vs block statement

scope vs block

Top answer
1 of 5
6
But can't let be considered global too? Yes. If declared in the global scope, let and const (and class) will also create global declarations. So the table is incorrect in that sense. Where this gets confusing is, unlike var and function, when let, const, and class are used in the global scope, they do not create global properties, whereas var and function do. var x = 1 let y = 2 console.log(globalThis.x) // 1 console.log(globalThis.y) // undefined This doesn't mean let, etc. are not defined in global, they just don't also exist as properties on the global object. This is possible because global scope has two buckets: an object record (global object and its properties) and a declarative record (declarations not in global object). Definitions in both contribute to those values which are globally available. So in the above example, var x is put into global's object record and let y is placed into the declarative record. What's nice about the declarative record is that it prevents collisions with properties of the global object. This can be especially important on the web as the global object is also the window object with many window-specific properties like name. If you've ever tried to create a name var in the global scope on the web, you may have noticed some problems. var foo = {} console.log(foo) // {} var name = {} console.log(name) // [object Object] What happens here is, var name ends up assigning to the pre-existing window.name property which will stringify values on assignment. The result is that the original object is lost and you're left with its string representation of "[object Object]". foo escapes this fate because it does not already exist on window. Variables defined in the declarative record do not have this problem. let name = {} console.log(name) // {} console.log(window.name) // '' or whatever the window name is In this case, our let name declaration is placed in the declarative record separate from the object record allowing it to coexist with the name property. The declarative record is checked first when referring to global variables by name so checking for just name gives us our declared value. For the object value, you can go directly through the global object accessing it as a property seen here with window.name. Where even if you declare the variable in block statement, it will automatically set it to globabal variable? This will only be the case if you use a non-block scoped declaration with a block statement in the global scope... and that can actually depend on strict mode too. Normal block-scoped declarations in a block do not become global. They're scoped to the block. let x // global { let y // block scoped, not global } Because var isn't block scoped, it will always create a global if in the global scope var x // global { var y // also global } If anywhere in your code - in global, in a block, in a function... - you assign a value to an undeclared variable, that will create a new global property. This isn't a declaration at this point, just an assignment, and if there is no variable of that name in scope, it defaults to assigning a global. function foo () { // function scope { // block scope x = 1 } } foo() console.log(x) // 1 This does not work in strict mode. Strict mode enforces assignments are to valid declarations (or global properties). So instead, an error is thrown. "use strict" function foo () { // function scope { // block scope x = 1 // Error! Does not exist } } foo() Strict mode also has an effect on function declarations making them block-scoped. Not var, only functions. So whereas normally a function in a block in the global scope would be global { function foo () { console.log('foo called') } } foo() // foo called In strict mode, the function would instead be scoped to that block and not be accessible as a global (or in the parent function scope if in a function) "use strict" { function foo () { console.log('foo called') } } foo() // Error! Does not exist So yeah, scope can be a little tricky in JS ;)
2 of 5
2
I don't understand why all these resources introduce scope by talking about 'global scope', 'block scope', 'local scope', 'function scope' etc as opposed to how Javascript actually implements scope: environment records. I just feel like this is one of the few cases where reading the ECMASCript spec is actually clearer than much of the third party material out there. As a bonus you get to learn exactly how closures work!
🌐
GitHub
github.com › EQuimper › CodeChallenge › blob › master › javascript › FreeCodeCamps › Basic JavaScript › Global Scope and Functions.md
CodeChallenge/javascript/FreeCodeCamps/Basic JavaScript/Global Scope and Functions.md at master · EQuimper/CodeChallenge
February 15, 2017 - This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with var. Declare a global variable myGlobal outside of any function.
Author   EQuimper
🌐
freeCodeCamp
freecodecamp.org › news › understanding-let-const-and-var-keywords
How the let, const, and var Keywords Work in JavaScript
January 11, 2022 - Anything and everything outside of a block or a function we'll call Global. So, when we declare variables, they can exist within a block, inside a function, or outside of a block/function – that is, they have global scope.
🌐
Hostman
hostman.com › tutorials › understanding global variables in javascript
Understanding Global Variables in JavaScript | Hostman
December 26, 2025 - It is a best practice to use the keywords var, let, or const when declaring global variables to avoid accidental generation of implicit global variables, which can result to difficult to find problems.
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
🌐
Medium
medium.com › swlh › local-vs-global-scope-and-let-vs-var-in-javascript-6d577d0a2750
Local vs Global Scope and Let Vs Var In JavaScript | by The ERIN | The Startup | Medium
August 28, 2020 - When we declare a variable or constants with the let or const keywords, their scope is limited to the code block or function in which they were defined. We can not access variables that are in a local scope outside of the code block or function ...
🌐
Medium
lethanhan.medium.com › why-use-const-and-let-over-var-and-how-the-hell-does-scope-work-in-js-4d3e94626e28
Why use const and let over var? (And how the hell does scope work in JS?) | by Le Thanh An | Medium
January 30, 2021 - When ES6 comes around, Javascript came up with 2 new ways to declare variables: const and let . And, as you might have guessed it, these 2 keywords support Block Scope.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › const
const - JavaScript | MDN - Mozilla
You should understand const ... bindings", not "immutable values". Many style guides (including MDN's) recommend using const over let whenever a variable is not reassigned in its scope....
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Global Scope and Functions - JavaScript
Variables which are defined outside ... everywhere in your JavaScript code.” " Variables which are declared without the let or const keywords are automatically created in the global scope....
Published   July 17, 2023
Top answer
1 of 6
82

Basically,

  • use let if the variable's value will change during the code
  • use const if it won't and you / your team want to use const in those situations in the project you're working on; it's a matter of style

If you do use const, then it's surprising how often it turns out that the guidelines above mean you use const because you end up not needing to change a variable's value (if you're following the usual rules of keeping your functions of reasonable size and such). (Well, it surprised me, anyway...)

Using const when the variable's¹ value is not meant to change accomplishes a few things:

  1. It tells others reading your code that you don't intend the value to change.

  2. It gives you a nice proactive error if you change the code so it writes to that variable. (A decent IDE can flag this up proactively, but if not, you'll get the error when running the code.) You can then make an informed, intentional decision: Should you change it to let, or did you not mean to change that variable's value in the first place?

  3. It gives a hint to the JavaScript engine's optimizer that you won't be changing that variable's value. While the engine can frequently work that out through code analysis, using const saves it the trouble. (Caveat: I have no idea whether this is actually useful to the JavaScript engine. It seems like it would be, but runtime code optimization is a very complicated and sometimes non-intuitive process.)


¹ Yes, it's funny to use the term "variable" to refer to something that by definition doesn't vary. :-) The specification's term is "binding," but I bet you won't hear people talking about "bindings" in everyday conversation anytime soon... So the aggregate term will probably remain "variable" except when we can specifically refer to something as a "constant."

2 of 6
50

Using const by default is essentially a matter of programming style. However there are pros and cons to each:

Arguments in favor of using const by default

The arguments in favor of using const by default are the following:

  1. It avoids side effects caused by involuntary reassignments;
  2. During a code review, it removes an uncertainty, because the developer who sees a const variable can count on the certainty that it will not be reassigned;
  3. Maybe we could say it is more consistant with functional programming and immutable states.
  4. With TypeScript, there are some cases with better inferences.

Here is an example of advantage when using const with TypeScript:

const hello = "Hello" as string | undefined
if (hello !== undefined) {
    ["A", "B"].forEach(
        name => console.log(`${hello.toUpperCase()}, ${name}`) // OK
    )
}

With let, in strict mode, TypeScript detects an error:

let hello = // …
// …
        name => console.log(`${hello.toUpperCase()}, ${name}`)
//                             ^__ error here: Object is possibly 'undefined'.

Arguments in favor of using let by default

I summarize here the article Use “let” by default, not “const” that gives arguments in favor of using let by default rather than const:

  1. Re-assignment is not a dangerous thing, it is just... usual;
  2. If a variable could be reassigned, then it should be declared with let, because it is more expressive to reserve const for real constants;
  3. const is misleading because it doesn’t stop references being modified;
  4. It is two more characters to write and to bundle;
  5. Using const by default is inconsistant with function parameters;
  6. There is no performance gain to use const.