When to use const with objects in JavaScript?
Asked Answered
A

6

63

I recently read about ES6 const keyword and I can understand its importance when having something like this:

(function(){
    const PI = 3.14;
    PI = 3.15; //  Uncaught TypeError: Assignment to constant variable
})();

So, nobody can change my PI variable.

The misunderstanding I have is that I don't understand in which situation the use of const with objects can make sense (other than preventing people to do myObj = newValue;).

(function(){
    const obj = {a:1 ,b: 2, c:3};
    //obj = {x:7 , y:8, z: 9}
    //This is good
    //TypeError: Assignment to constant variable.

    obj.a=7; obj.b=8 ; obj.c=9;
    console.log(obj); //outputs: {a: 7, b: 8, c: 9}
})();

So when declaring an object: when should I say: Now I must declare my object with const?

Already answered 17/6, 2017 at 11:43 Comment(0)
W
122

it is a common misconception around the web, CONST doesn't creates immutable variables instead it creates immutable binding.

eg.

 const temp1 = 1;
 temp1  = 2 //error thrown here.

But

 temp1.temp = 3 // no error here. Valid JS code as per ES6

so const creates a binding to that particular object. const assures that variable temp1 won't have any other object's Binding.

Now coming to Object. we can get immutable feature with Object by using Object.freeze

const temp3 = Object.freeze( {a:3,b:4})
temp3.a = 2 // it wont update the value of a, it still have 3
temp3.c = 6 // still valid but wont change the object
Widgeon answered 17/6, 2017 at 12:14 Comment(5)
thank you for the clear answer. Can you just please explain how "const assures that variable temp1 won't have any other object's Binding."?Already
any reference stating that?Snuffbox
@Snuffbox , execute above example in your browser's consoleWidgeon
@Snuffbox I'm a bit late for this, but just for the sake of completeness: Here is the reference for const and here is the reference for Object.freeze().Draw
not valid in strict mode though, Uncaught TypeError: Cannot create property 'temp' on number '1'Lignocellulose
P
24

According to ES6-Features.org, constants are used to make "variables which cannot be re-assigned new content".

The const keyword makes a variable itself immutable, not its assigned content. When the content is an object, this means the object itself can still be altered.

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.

You are still allowed to add new attributes to your object.

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"}; //Uncaught TypeError: Assignment to constant variable.
console.log(myObj.newNameAttr);

myVar = "newValue"; //Uncaught TypeError: Assignment to constant variable.
console.log(myVar);

You can also see on this fiddle: https://jsfiddle.net/am2cbb00/1/

Passacaglia answered 17/6, 2017 at 12:3 Comment(5)
So... what would something like this do, at the top of a function? const obj = new myObject(this, data); I'm not sure if it's like a static in PHP or more like a ..ehm.. singleton pattern perhaps, but with.. erhm... "resuable" constructor? Or perhaps just a programmer showing off his shiny new keyword for no reason....Alecto
@ChristofferBubach it's a constructor in javascript. "new" keyword is used to create an instance of an object. Basically, it creates a new object and assigns a const variable to it. So, that const variable cannot be bind with an another object. Only the content of object can be changed and updated. Please also check here for "new" keyword usage in JS: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Passacaglia
I know what I constructor is - my question is rather: what happens the second time the function is called? Is the object re-initialized with the new data-variable, or is it more like a static between calls? I find it unclear why one would use it inside a function like this.Alecto
@ChristofferBubach when the function is called second time, it initialises completely a new instance of "myObject" but it's not possible to assign that new instance to the same "obj" variable because it's defined constant variable. In your example, constructor owner also passes current object scope with "this". It might be possible that developer wants to reach some variable from that scope in the constructor.Passacaglia
So question is, would it be appropriate (best practise wise) to use an object if you are going to change/reassign its properties or not?Mirk
I
10

let and const are meant for type safety. There is no situation where you must use them, but they can be handy and reduce hard to spot bugs.

One 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);
Inoculation answered 17/6, 2017 at 12:5 Comment(0)
A
4

If you work with an object and want to make sure that identity of the object is never changed say:

const a = {};

a.b = 1;

// ... somewhere in the other part of the code or from an async call
// suddenly

someAjaxCall().then(() => { a = null; }) // for preventing this

Also using const is a good hint for javascript compiler to make optimisations about your code, thus making execution much faster then with let or var because the identity never changes,

BUT

beware of using const/let in loops for performance reasons, because it might slowdown the performance due to creation of a variable per loop, but in most cases the difference is negligible.

Atomicity answered 17/6, 2017 at 12:2 Comment(0)
O
1

const actually creates immutable binding instead of making the variables immutable.

Since primitive data-types (Boolean, null, undefined, String, and Number) are passed by value, they themselves become immutable and hence can't be re-assigned to some other value.

In the case of complex data-types (Array, Function, and Object), they are passed by reference. When we change or modify their properties/elements, we not changing their binding, hence const doesn't throw any error.

Oz answered 15/3, 2019 at 15:55 Comment(0)
H
0

const makes the name AND content immutable UNLESS the content is an object, then only the content can be changed.


const n = 1; 
n = 2; // Uncaught type error
let n = 2 // Already assigned


Halogen answered 16/7, 2021 at 17:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.