Skip to content

JavaScript const object | Example code

  • by

According to ES6, constants are used to make “variables which can’t be re-assigned new content”. The JavaScript const object can still be altered because the const keyword makes a variable itself immutable, not its assigned content.

Therefore, it’s possible to change the content of the object that is declared with const variable, but you cannot assign a new object to a const variable.

JavaScript const object

Simple example code allowed to add new attributes to a const object.

<!DOCTYPE html>
<html>
<body>
  <script>    
    const myVar = "someValue";
    const myObj = {"name": "nameValue", "age": 14}

    console.log(myVar); //someValue
    console.log(myObj.name); //nameValue

    myObj.name = "newNameValue"; 
    console.log(myObj.name); //newNameValue

    myObj.someNewAttr = "newAttrValue";
    console.log(myObj.someNewAttr); //newAttrValue

    myObj = {"newNameAttr": "newNameValue"}; //TypeError
    console.log(myObj.newNameAttr);

    myVar = "newValue"; //TypeError
    console.log(myVar);
  </script>  

</body>
</html>

Output:

JavaScript const object

One more example of a situation where const would be useful for an object that you don’t want to turn into another type.

const x = {"hello":"world"};

// This is OK
x.hello = "stackoverflow";

// This is not OK
x = JSON.stringify(x);

You can use Object.freeze to prevent an object (or array) from being changed:

const x = [1, 2, 3];
Object.freeze(x);

x.push(4); // This will throw an exception

Why object const can be changed after the definition in JavaScript?

Answer: A variable declared with const means one thing: the standalone variable name cannot be reassigned with = later.

In contrast, o.a = 5; is not reassigning the variable name – it’s mutating the content of the object, but it’s not changing what the o variable points to in memory.

To prevent the reassignment of a variable name, use const. To prevent mutation of an object is something entirely different – for that, you’d need something like Object.freeze or manipulate objects using immutable-js.

How to create Javascript constants as properties of objects using the const keyword?

Answer: You can’t do it with constants. The only possible way to do something that behaves like you want, but is not use constants, is to define a non-writable property:

var obj = {};
Object.defineProperty( obj, "MY_FAKE_CONSTANT", {
  value: "MY_FAKE_CONSTANT_VALUE",
  writable: false,
  enumerable: true,
  configurable: true
});

Source: stackoverflow.com/

Comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading