javascript tutorial - [Solved-5 Solutions] Constants in JavaScript - javascript - java script - javascript array



Problem:

Is there a way to use constants in JavaScript?

Solution 1:

const MY_CONSTANT = "some-value";
click below button to copy the code. By JavaScript tutorial team

Solution 2:

var CONFIG = (function() {
     var private = {
         'MY_CONST': '1',
         'ANOTHER_CONST': '2'
     };

     return {
        get: function(name) { return private[name]; }
    };
})();

alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

CONFIG.private.MY_CONST = '2';                 // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST'));  // 1

click below button to copy the code. By JavaScript tutorial team

Solution 3:

"use strict";

var constants = Object.freeze({
    "π": 3.141592653589793 ,
    "e": 2.718281828459045 ,
    "i": Math.sqrt(-1)
});

constants.π;     // -> 3.141592653589793
constants.π = 3; // -> TypeError: Cannot assign to read only property 'π' …
constants.π;     // -> 3.141592653589793

click below button to copy the code. By JavaScript tutorial team

Solution 4:

function MY_CONSTANT() {
   return "some-value";
}


alert(MY_CONSTANT());

click below button to copy the code. By JavaScript tutorial team

Solution 5:

var constant = function(val) {
   return function() {
        return val;
    }
}
click below button to copy the code. By JavaScript tutorial team

This approach gives us functions instead of regular variables, but it guarantees* that no one can alter the value once it's set.

a = constant(10);

a(); // 10

b = constant(20);

b(); // 20

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Constants in JavaScript