Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 330
  • Last Modified:

Javascript - How to define constants/values used by multiple function

I understand Javascript do have the notion of constant.  However I would like to use a set of constant value across multiple functions.  How will I do that?
For example I have the following set of variables that I would like to treat as constant and used in different functions.
     var FORM_TYPE_CREATE = 1;
     var FORM_TYPE_UPDATE = 2;
     var FORM_TYPE_READ_ONLY = 3;
     var FORM_TYPE_DISABLED = 4;
     var FORM_TYPE_BULK_EDIT = 6;
  • 2
3 Solutions
you have already done it - put your vars in uppercase. that's how you define a constant in javascript.
obviously it's not really a constant, the naming convention simply tells other developers that they should treat these as constants and not change the vlaues OR DIE.
unless you are in firefox only... then you have "const"

Greetings tommym121,

I agree with basicinstinct, it's just a naming convention. Now, you could do closures instead and wrap your constants in a function:

function CONSTANTS()
        constants = {};
        //List your constants
        constants.FORM_TYPE_CREATE = 1;
        return function () {
             return constants;    


Open in new window

This way you can encapsulate your "constants" in a local function that does not clutter the global namespace, and it's available for read only purposes.

//Retrieve an specific constant during run-time
var form_type_create = CONSTANTS().FORM_TYPE_CREATE;

Open in new window

You can even go fancy and use augmented loosely pattern in order to update the values at some point

CONSTANTS = (CONSTANTS(constants_object, new_value_for_form_type_create)
   var old_constant = constants_object.FORM_TYPE_CREATE;
   constants_object.FORM_TYPE_CREATE = new_value_for_form_type_create || old_constant;
   //In case, for instance, no value was provided.
})(CONSTANTS(), 2)

Open in new window

Don't you just love Javascript?
tommym121Author Commented:

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now