Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a file of constants in Javascript?

Is there a way to create a file of constants in JavaScript, which I can reference and then use? What I am looking for is something like this:
Constants.js:

var Phones =
{
Nokia: 1,
Samsung: 2
}

Then, in another JavaScript file JS2.js access those values: JS2.js:
alert(Phones.Nokia);

And then, in an aspx file that uses them, reference both of them, like:
<asp:ScriptReference Path="../js/JS2.js" />
<asp:ScriptReference Path="../js/Constants.js" />

Is such an architecture possible? What datatypes can we use? I only exemplified enums because this is what i use right now, but they must be declared in the same file as they are used.

like image 771
TheRifle Avatar asked Jun 30 '10 19:06

TheRifle


People also ask

How do I create a constant file in react JS?

All you have to do is take each section of your constants that are currently within index. js and put them within own their brand new file in /src/constants and link them to our constants/index. js file for easy referencing.

How do you use constants in JavaScript?

If you declare your constants in file1 as global variables: var someConstant = 42; Then you can just use that variable in your other JS files. Just make sure file1 is loaded before you try to use them.

What does const [] mean in JavaScript?

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.


2 Answers

It is very much possible (exactly as you use them). It won't be an enum though, just an object with several numeric fields.

You should use the script reference to constants as the topmost one (logically).

The common types are:

  • undefined (variable)
  • null (variable)
  • String
  • Boolean
  • Number
  • String
  • Object
like image 166
Jaroslav Jandek Avatar answered Sep 19 '22 15:09

Jaroslav Jandek


you're doing it right.

make sure the constants are declared first.

JavaScript parses alls scripts and script file links in top down order.

like image 37
Sonic Soul Avatar answered Sep 17 '22 15:09

Sonic Soul