Monday, December 5, 2016

const in js

  1. new const feature

    in the past there was no real constants in js, everything could be overwritten (even sometimes keywords)
    in ECMAScript6 this has been alleviated

    const in JS means the object can be assigned once
    if you try this

    const i = 45
    i= 0
    console.log(I)



    this will fail
    SyntaxError: Identifier 'i' has already been declared

    with objects member can be assigned afterwards


    const obj2 = {}
    obj2.a ="gg"



    but subsequent
    obj2 = {}
    will fail

    even with const, the only way to have a readonly member of an object is

    var testobj = {};
    Object.defineProperty( testobj , "pseudoconst",
    {
    value: 3,

    writable: false,

    enumerable: true,

    configurable: true
    });


    testobj.pseudoconst
    3
    testobj.pseudoconst = 5//this wont raise an error but wont change the value either
    5
    testobj.pseudoconst
    3

No comments:

Post a Comment