Javascript: Assigning objects to const variables vs let variables

Viewed 686

This might be a silly question, but I wanted to see if there were any best practices in terms of what to assign to a CONST or LET variable. I understand CONST variables cannot be reassigned once declared, but I noticed that by assigning an object to a CONST variable, you can update the contents of the object.

const person = {
  name: "John"
}
console.log(person.name) => //"John"

person.name = "Kim"
console.log(person.name) => //"Kim"

Would this be considered bad practice? If not, why not use LET variable?

1 Answers

Your example isn't bad practice, and is perfectly acceptable because person still refers to the same object, even though you've changed a property. You could add, remove or change properties and person still refers to your object.

ES6 const makes the binding immutable, not the value.

In ES6 you should use const if you don't need to rebind, otherwise use let. In your example you are not rebinding person so it is valid and correct.

If for example you had a second object person2 and tried to rebind like person = person2 then that would throw a type error.

If you wish to make your object value immutable, you can do that with Object.freeze() like so:

const person = Object.freeze({
    name: "John"
});
person.name = "Kim";
// quietly fails or throws a type error
Related