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.
Basic JavaScript - Global Scope and Functions
What is the proper to write a global const in javascript es6? - Stack Overflow
oopsGlobal should be a global variable and have a value of 5
Confusion in global variable (var) and block variable (let , const) at node js
Videos
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.
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?
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.
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:
game.state.firePaused- This locks your game state to a single character, but will better contain the state of a character shooting.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.
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
Basically,
- use
letif the variable's value will change during the code - use
constif it won't and you / your team want to useconstin 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:
It tells others reading your code that you don't intend the value to change.
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?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
constsaves 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."
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:
- It avoids side effects caused by involuntary reassignments;
- During a code review, it removes an uncertainty, because the developer who sees a
constvariable can count on the certainty that it will not be reassigned; - Maybe we could say it is more consistant with functional programming and immutable states.
- 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:
- Re-assignment is not a dangerous thing, it is just... usual;
- If a variable could be reassigned, then it should be declared with
let, because it is more expressive to reserveconstfor real constants; constis misleading because it doesn’t stop references being modified;- It is two more characters to write and to bundle;
- Using
constby default is inconsistant with function parameters; - There is no performance gain to use
const.