How to declare string constants in JavaScript?

JavascriptConstants

Javascript Problem Overview


I want to declare string constants in JavaScript.

Is there is a way to do that?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

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

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

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
   });
};

Solution 10 - Javascript

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.

Solution 11 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGirish ChaudhariView Question on Stackoverflow
Solution 1 - JavascriptalexView Answer on Stackoverflow
Solution 2 - JavascriptEsteban ArayaView Answer on Stackoverflow
Solution 3 - JavascriptMattCView Answer on Stackoverflow
Solution 4 - JavascriptMohitView Answer on Stackoverflow
Solution 5 - JavascriptSimonView Answer on Stackoverflow
Solution 6 - JavascriptBeckaflyView Answer on Stackoverflow
Solution 7 - JavascriptRyan RhoView Answer on Stackoverflow
Solution 8 - JavascriptSimonView Answer on Stackoverflow
Solution 9 - JavascriptSandip NirmalView Answer on Stackoverflow
Solution 10 - JavascriptRubi sainiView Answer on Stackoverflow
Solution 11 - JavascriptLloydView Answer on Stackoverflow