JavaScript Constants

This lesson explain you, How to declare JavaScript constants. JavaScript const statement to declare a constant variable with a value. As per ECMA specification constant variable scope to the nearest enclosing block.

Constant variable can not re declare, and you can not reassign constant a value to a constant variable.

Syntax

const constant_name = value;

Parameter

  • const: JavaScript reserved keyword.
  • constant_name: Name of the constant variable.
  • value: Required, Initializing constant value.

Shorthand style, you can declare a one or more constant in single statement separated by comma.

const con1 = val1, con2 = val2, ..., conN = valN;

Example

<script>
    const a = 10;
    console.log("Constant a: ", a);        // a value 10

    const b;            // weird, const can define without initial value,
    console.log("Constant b: ", b);    // automatic assign 'undefined'
    
    //const a = 20;     // throw TypeError 'a' already been declared

    //var a = 20;       // throw TypeError 'a' already been declared
                        // 'a' is already used as a constant can not declare as a variable

    a = 20;           // Define 'a' variable without var keyword, can't throw error
    console.log("a without var:", a);
    const c = 20;       // Define and initializing 'c' constant variable
    const d = b;        // Define 'd' constant variable, initialize constant 'c'
    console.log("Constant c: ", c);
    console.log("Constant d: ", d);
    
    const obj = {"a": "A", "b": "B"};    // Define and initializing constant object
    console.log("Constant Object:", obj);
    console.log("Constant obj.a:", obj.a);

    //var obj = 10;              // throw TypeError 'obj' already been declared
    obj.a = "AA";                // 'a' key, try to reassign
    console.log("Reassign after Object:", obj);    // Object {a: "AA", b: "B"}
</script>

Run it...   »

Browser Compatibility

  • Google Chrome 20+
  • Mozilla Firefox 13+
  • Internet Explorer 11+
  • Opera 12+
  • Safari 5.1+

Note: Here details of browser compatibility with version number may be this is bug and not supported. But recommended to always use latest Web browser.

All browser partially supported, also fails in value reassignment.