Defining Constant in Javascript

Prior to javascript ES6, there was no way to define constants, so one have to write their own custom way to write constants.

So, here are two ways to define constant that are mutable i.e, which can'nt be reassigned.

1. Using Const (ES6) : -

const MAX_NUM = 10;

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.

2. Using defineProperty

And we can use throughout our application.

(function() {
    var locarVar;
    Object.defineProperty(window, 'MAX_NUM', {
        get: function() {
            return locarVar;
        },
        set: function(val) {
            locarVar = window.MAX_NUM || val;
        }
    });

}());

MAX_NUM = 10;
MAX_NUM = 12; // Cannot redefine property: MAX_NUM

console.log(MAX_NUM); // 10

Comments

Popular posts from this blog

What is MQTT protocol & its use

What the hack is Call, bind & apply

What is Provider in Angular Js?