Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can global constants be declared in JavaScript?

If so, what is the syntax for such a declaration?

like image 691
Giffyguy Avatar asked Nov 13 '10 20:11

Giffyguy


People also ask

Can const be global in JavaScript?

The const Keyword Functionally const is similar to let and var in that it declares variables. It is also just like let in that it has block level scope that can be global or local to the function in which it is declared.

Can we declare global variable in JavaScript?

Declaring Variable: A variable can be either declared as a global or local variable. Variables can be declared by var, let, and const keywords. Before ES6 there is only a var keyword available to declare a JavaScript variable.

Are global constants acceptable?

Although you should try to avoid the use of global variables, it is generally permissible to use global constants in a program. A global constant is a named constant that is available to every function in a program.


2 Answers

Javascript doesn't really have the notion of a named constant, or an immutable property of an object. (Note that I'm not talking about ES5 here.)

You can declare globals with a simple var declaration in the global scope, like outside any function in a script included by a web page:

<script>   var EXACTLY_ONE = 1; 

Then your code can use that constant of course, though it's not really "constant" because the value can be changed (the property updated, in other words).

edit — this is an ancient answer to an ancient question. In 2019, there's the const declaration that's supported just about everywhere. However note that like let, const scoping is different from var scoping.

like image 155
Pointy Avatar answered Oct 09 '22 23:10

Pointy


As "Pointy" so carefully notes, ECMAscript has no such feature. However, JavaScript does:

const a = 7; document.writeln("a is " + a + "."); 

Of course, if you're writing code to put on the web to run in web browsers, this might not help you much. :-)

like image 26
Ken Avatar answered Oct 09 '22 21:10

Ken