I want to declare string constants in JavaScript.
Is there is a way to do that?
Introduction to the JavaScript const keyword ES6 provides a new way of declaring a constant by using the const keyword. The const keyword creates a read-only reference to a value. By convention, the constant identifiers are in uppercase. Like the let keyword, the const keyword declares blocked-scope variables.
The new 'const' statement for writing constant variables is a nifty feature, which adds features to an already interesting update. The variable is created as read-only, and once it is stated it can't be overridden.
An initializer for a constant is required. You must specify its value in the same declaration. (This makes sense, given that it can't be changed later.) The const declaration creates a read-only reference to a value.
Once a constant is initialized, we cannot change its value. Simply, a constant is a type of variable whose value cannot be changed.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With