0

I'm using Code Academy to learn basic javascript. I had a problem when dealing in assigning objects with const.

The tutorial says: It’s important to know that although we can’t reassign an object declared with const, we can still mutate it, meaning we can add new properties and change the properties that are there.

const spaceship = {type: 'shuttle'}; spaceship = {type: 'alien'}; // TypeError: Assignment to constant variable. spaceship.type = 'alien'; // Changes the value of the type property spaceship.speed = 'Mach 5'; // Creates a new key of 'speed' with a value of 'Mach 5' 

Why I can't change the value of the type property with the code in line 2??

My guess on this: Since we couldn't reassign any value declared by const, we still can change the value of type property using bracket notation or dot notation. Is it right??

Thanks

2
  • You are correct. You cannot reassign the value of an object declared with const. You can use dot notation or bracket notation… spaceship['type'] = 'alien'; to change properties on the object. Commented Jan 17, 2022 at 12:12
  • In JS {} creates in new object. So in line 2 you are creating new object and assigning it to constant spaceship, which is not allowed. Commented Jan 17, 2022 at 12:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.