Object Declaration

Hello all! Your answers have been incredibly helpful so far so i thought I might try to post a question on something that doesn’t seem to have been discussed before.

When we declare objects - should we always use the ‘const’ keyword? In all the ‘object’ lessons I’ve seen so far, they have used ‘const’.

e.g. https://www.codecademy.com/courses/introduction-to-javascript/lessons/objects/exercises/objects

Does this make sure that objects keep the same name throughout the whole code while still allowing us to add, change and delete properties and methods? What are the benefits/drawbacks of using ‘let’ for object declaration?

Hello @anthonyma2611412276 , welcome to the forums! While I’m not the most qualified person to answer, I think the reason is similar to the reason why one uses const when declaring functions using arrow syntax: it stops you (or other developers) from changing the object to something completely different:

let obj = {y: "hello"}
obj = 3344;
//this is legal (as in, no errors would be thrown), but almost certainly
//very bad for the code, whereas:
const obj = {y: "hello"}
obj = 3344;
//this will throw an error, and therefore stop you from doing it

As objects are mutable, even if they’re declared with const, you can still change/add/subtract properties. This is a good answer from StackOverflow, if you want more reading.
I hope this helps!

1 Like