103

I want to declare string constants in JavaScript.

Is there is a way to do that?

1

11 Answers 11

137

Many browsers' implementations (and Node) have constants, used with const.

const SOME_VALUE = "Your string";

This const means that you can't reassign it to any other value.

Check the compatibility notes to see if your targeted browsers are supported.

Alternatively, you could also modify the first example, using defineProperty() or its friends and make the writable property false. This will mean the variable's contents can not be changed, like a constant.

4
  • 5
    great idea. u can further save yourself a few keystrokes by not having the ''s around the property names, e.g., = { constant1: 'value1',}
    – Ian Davis
    Mar 1, 2013 at 15:04
  • awesome thank so much for this answer. I was going to use const but unfortunately we still support users with ie9 :( One weird thing though is on the MDN page it says that it can be "data descriptor" or "accessor descriptor" but not both... however the examples show them both being used (ie: enumerable with writable) then on the "defineProperties" it doesn't say that and lets you use any...a bit confusing. Mar 25, 2016 at 17:08
  • 1
    In addition it is good practice naming constants in uppercases with underscore to signal their special usage. e.g. const SOME_VAR = "Your string";
    – Sven 31415
    Apr 7, 2016 at 14:38
  • @Sven31415 Good idea, made an edit.
    – alex
    Apr 8, 2016 at 7:24
6

Are you using JQuery? Do you want to use the constants in multiple javascript files? Then read on. (This is my answer for a related JQuery question)

There is a handy jQuery method called 'getScript'. Make sure you use the same relative path that you would if accessing the file from your html/jsp/etc files (i.e. the path is NOT relative to where you place the getScript method, but instead relative to your domain path). For example, for an app at localhost:8080/myDomain:

$(document).ready(function() {
  $.getScript('/myDomain/myScriptsDir/constants.js');
  ...

then, if you have this in a file called constants.js:

var jsEnum = { //not really an enum, just an object that serves a similar purpose
  FOO : "foofoo",
  BAR : "barbar",
}

You can now print out 'foofoo' with

jsEnum.FOO
1
  • Ya, but you can also do: jsEnum.FOO = "booboo". Not a constant.
    – xr280xr
    Apr 28, 2016 at 18:57
6

There's no constants in JavaScript, but to declare a literal all you have to do is:

var myString = "Hello World";

I'm not sure what you mean by store them in a resource file; that's not a JavaScript concept.

5

Of course, this wasn't an option when the OP submitted the question, but ECMAScript 6 now also allows for constants by way of the "const" keyword:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

You can see ECMAScript 6 adoption here.

4

Standard freeze function of built-in Object can be used to freeze an object containing constants.

var obj = {
    constant_1 : 'value_1'
};
Object.freeze(obj);
obj.constant_1 = 'value_2';   //Silently does nothing
obj.constant_2 = 'value_3';   //Silently does nothing

In strict mode, setting values on immutable object throws TypeError. For more details, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

3

Well, you can do it like so:

(function() {
    var localByaka;
    Object.defineProperty(window, 'Byaka', {
        get: function() {
            return localByaka;
        },
        set: function(val) {
            localByaka = window.Byaka || val;
        }
    });
}());
window.Byaka = "foo"; //set constant
window.Byaka = "bar"; // try resetting it for shits and giggles
window.Byaka; // will allways return foo!

If you do this as above in global scope this will be a true constant, because you cannot overwrite the window object.

I've created a library to create constants and immutable objects in javascript. Its still version 0.2 but it does the trick nicely. http://beckafly.github.io/insulatejs

2

Starting ECMAScript 2015 (a.k.a ES6), you can use const

const constantString = 'Hello';

But not all browsers/servers support this yet. In order to support this, use a polyfill library like Babel.

1
  • const is supported in google chrome Jul 1, 2016 at 7:58
0

So many ways to skin this cat. You can do this in a closure. This code will give you a read-only , namespaced way to have constants. Just declare them in the Public area.

//Namespaced Constants
var MyAppName;
//MyAppName Namespace
(function (MyAppName) {
    //MyAppName.Constants Namespace
    (function (Constants) {
        //Private
        function createConstant(name, val) {
            Object.defineProperty(MyAppName.Constants, name, {
                value: val,
                writable: false
            });
        }

        //Public
        Constants.FOO = createConstant("FOO", 1);
        Constants.FOO2 = createConstant("FOO2", 1);

        MyAppName.Constants = Constants;
    })(MyAppName.Constants || (MyAppName.Constants = {}));
})(MyAppName || (MyAppName = {}));

Usage:

console.log(MyAppName.Constants.FOO);       //prints 1
MyAppName.Constants.FOO = 2;
console.log(MyAppName.Constants.FOO);       //does not change - still prints 1
2
  • One problem with this solution is that you can redefine the parent object. MyAppName.Constants = null; console.log(MyAppName.Constants.FOO); //will throw an error
    – Beckafly
    Oct 4, 2014 at 7:39
  • @Byaxy, that is correct. Your suggested solution is more accurate for providing an actual 'constant'. What I like about the approach I suggested is that it reducing cluttering of the DOM and uses 'constants' in a more organized fashion (uppercased & namespaced). All this to make something work in a language that doesn't support it natively. Ah, the joys of JavaScript. =p
    – Simon
    Oct 6, 2014 at 11:39
-1

You can use freeze method of Object to create a constant. For example:

var configObj ={timeOut :36000};
Object.freeze(configObj);

In this way you can not alter the configObj.

-1

Use global namespace or global object like Constants.

var Constants = {};

And using defineObject write function which will add all properties to that object and assign value to it.

function createConstant (prop, value) {
    Object.defineProperty(Constants , prop, {
      value: value,
      writable: false
   });
};
1
  • This is the way to create constant in ES5, with ES6 we have new keyword const to do it. Oct 10, 2015 at 5:44
-4

Just declare variable outside of scope of any js function. Such variables will be global.

3
  • 1
    Globals clutter up the global namespace, and cause for more problems than necessary.
    – Kevin Ji
    Apr 26, 2011 at 4:58
  • 1
    How else would you treat "declare on the page"? The only interpretation of it that I could "invent" is global variable.
    – Lloyd
    Apr 26, 2011 at 14:35
  • 3
    A global variable is not a constant - it can be modified.
    – Thierry
    Dec 20, 2012 at 16:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.