const keyword in JavaScript

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can’t be changed through reassignment, and it can’t be redeclared.

You can change the properties of a constant object.

You can change an element in an array. You can add an element to an array. But, you cannot reassign a constant array.

Sample Code:

    const a = 1;
    //console.log( a = 3 );//TypeError: Assignment to constant variable
    
    const obj = { 'a' : '1', 'b' : '2' };
    obj.c = '3';
    console.log( obj );//{a: "1", b: "2", c: "3"}. No Error. You can change the properties of a constant object.
    //obj = { 'c' : '3' };//TypeError: Assignment to constant variable. You cannot assign a new object.
    delete obj.c; console.log( obj );//{a: "1", b: "2"}. No Error. You can delete the property also.
    
    const arr = [ 1, 2, 3, 4, 5 ];
    arr.push( 6 );
    console.log( arr );//[1, 2, 3, 4, 5, 6]. No Error. You can add elements to the array.
    arr[ 0 ] = 0;
    console.log( arr );//[0, 2, 3, 4, 5, 6]. No Error. You can change values inside the array.
    //arr = [ 3, 4 ];//TypeError: Assignment to constant variable. You cannot assign a new array.

Leave a Reply