How to use javascript constant in javascript file from another javascript file

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.

However, polluting the global scope like this come with it's risks, as those variables are easily changed.


  1. Create a file which contains all the constants and variables

Constants.js

const EMAIL = "[email protected]"
const PHONE = "9911223344"
var NAME = "Default name"
  1. Access the Constants.js file in your HTML file

xyz.html

<script src="Constants.js"></script>
  1. Now you can access the Constants in any of file inside a project

Multiple ways.

Concatenate

Use a task runner like grunt to define a task that concatenates your files into a single one. This will not only allow convenient definition of constants but also improve performance.

There are other tools to do this, too. See Prepros for windows and codekit for Macs.

Modularize

If you are on client side, use a tool like require.js or browserify to define commonJS / AMD modules and require them as you need.

If you are on server side using node, this works out of the box for commonJS.

Load scripts in correct order, expose them through global objects.

You could load your constant defining script first and do something like this:

var constants = {
    MY_CONST: 'Foo'
}

Your main, whi script could access this variable. If you omit the var keyword, the variable becomes globally available. Note however that this should be avoided.

You could even add a property to the global object (window on the client side).


Personally I like to use commonJS modules when working on projects that allow me to do so. Rob Ashton has an opinion on this that I would like to share.

When I can't use those modules in a convenient way, which would be the case when working with (custom) web-components because of their isolated scopes, I like to add a single script which creates an Object like App. I use this object to expose modules, services & constants which can then be required by any component in a neat way:

App.myService.doSomething()

Tags:

Javascript