Can global constants be declared in JavaScript?

67,413

Solution 1

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.

Solution 2

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. :-)

Solution 3

Everything is global unless declared with the var keyword.

There are no constants either. You can simply declare them without the var keyword.

If you want to ensure global scope you can throw it into the window object:

window.GLOBAL_CONSTANT = "value";

You can do this from within any scope. Constants can then be declared inside functions or closures, though I wouldn't recommend that.

Solution 4

If you only care about supporting newer browsers (or are using a transpiler such as Babel to support older browsers) you can do the following:

  1. Create a settings.js file with whatever constants you want and export them:
export const FRUIT = "kiwi";
export const VEGETABLE = "carrot";
  1. In files that you want to use them you could then import them as follows:
import * as Settings from './settings.js'
  1. Then to use the constants do something like this:
console.log("The unchangeable fruit is " + Settings.FRUIT);

This is a much cleaner approach than trying to implement a global constant, especially when you have multiple JavaScript files that you want to use the constants in.

Solution 5

You could do it with getters and setters like so:

Object.defineProperty(window, 'TAU', { 
    get: function(){return Math.PI*2;}
});

If you want a general function to do this:

function define(name, value){
    Object.defineProperty(window, name, { 
       get: function(){return value;},
       set: function(){throw(name+' is a constant and cannot be redeclared.');},
    });
}

// Example use
define('TAU', Math.PI*2);
Share:
67,413
Giffyguy
Author by

Giffyguy

I enjoy writing hardcore OO data-structures in native C++.

Updated on July 09, 2022

Comments

  • Giffyguy
    Giffyguy almost 2 years

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

  • Tim Down
    Tim Down over 13 years
    Why on earth has this been downvoted? It's true, not well-known and useful if you're working in a Mozilla-only environment. +1 from me.
  • Christian C. Salvadó
    Christian C. Salvadó over 13 years
    @Tim, was down-voted by someone that doesn't knows the difference between ECMAScript and JavaScript(tm)..., +1 also from me... BTW One thing to keep in mind, is that the TC39 committee has approved a set recommendations for implementors, that include restrictions on non-standard declarations -as const- on strict mode code. Firefox 4 at the moment has no restrictions about non-standard declarations under strict mode, but WebKit's JavaScriptCore has them -really good thing IMO-, you can't use const or have FunctionDeclarations inside Blocks... just to keep in mind..
  • Tim Down
    Tim Down over 13 years
    @CMS: Interesting, I hadn't looked into that. Thanks.
  • netpoetica
    netpoetica over 10 years
    Update - const keyword available in most modern browsers and standard in ES6 Harmony: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • mid
    mid over 7 years
    Old answer, but I'm pretty sure you can override functions.
  • Robert Parcus
    Robert Parcus almost 7 years
    Do read the docs! const is limited to the scope, so something like: if(DEBUG){const HOST = "locahost";} else { const HOST = "coolhost";} won't expose HOST globally.
  • kojow7
    kojow7 over 6 years
    Perhaps the answer is being down voted because it does not answer the question of globality.
  • ethmz
    ethmz about 5 years
    if you remove the var keyword, you get an undefined error in strict mode.
  • ecc521
    ecc521 almost 5 years
    You may want to edit to talk about strict mode, other environments (such as nodejs, which uses global instead of window), new Function("return this")(), and globalThis
  • ecc521
    ecc521 almost 5 years
    +1 for using getters and setters (which should allow code not in the global scope to define constant globals). You may want to edit to talk about strict mode, other environments (such as nodejs, which uses global instead of window), new Function("return this")(), and globalThis.
  • Pointy
    Pointy over 4 years
    @RudolfCicko well it'd be writable: false, enumerable: false probably; there's no "readOnly"
  • Rudy
    Rudy over 4 years
    @Pointy Aww yeah you are right.. Object.defineProperty(window, 'CONST_ATTR', { value: 'UNCHANGEABLE_VALUE' }); would work because writable: false is by default.