What's the difference between const and Object.freeze() in JavaScript? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What's the difference between const and Object.freeze() in JavaScript?

14th Mar 2021, 7:50 PM
AGirlHasNoName
AGirlHasNoName - avatar
3 Answers
+ 1
AGirlHasNoName const is used to defined constant variable means which value can't be change. Object.freeze() is used to freeze the object means you can't change anything of that object.
14th Mar 2021, 9:44 PM
A͢J
A͢J - avatar
+ 1
There are a few differences. If you declare a const variable, you can't change the initial value (unlike let and var). If you use an object as the value, you can still change the object's properties and values even though you can't reassign. Example: // create a const and assign an object as the value const car = { colour: "red" } // trying to reassign fails car = { colour: "blue" } // but changing the object's properties and values is fine car.colour = "blue" car.year = 2021 console.log(car) // outputs changed object { colour: "blue", year: 2021 } If you had used Object.freeze(car) before trying to change the car object, you would not have been allowed to make changes like above. So trying to change the colour to blue and adding a year property would've failed. If the car object had a property which had an object or function as the value, you could still change those even after using Object.freeze().
15th Mar 2021, 4:24 AM
CamelBeatsSnake
CamelBeatsSnake - avatar
0
none. const are just frozen variables by design ^^
14th Mar 2021, 7:52 PM
visph
visph - avatar