DEV Community

Discussion on: When to use LET or CONST

Collapse
 
matscode profile image
Michael Akanji • Edited

I don't recommend having the mindset to reassign an object variable.

Reasons

If it is an object of the same typeOf instance... I would recommend you rather update the objects properties value than reassign the variable object itself.

It would make your code obfuscated if you use let for an object because you want to change it later. In my opinion, I think it is a bad practice, no offense.

I wouldn't want to be reading through a code and I suddenly see a User object variable become Fruit object variable. The maintainability of such code is questionable...

So how can you prevent such thing from happening? I believe it is by declaraing variable with object value as a const...

This way, you can loop and update all object property but not the variable itself..

I don't know if this is helpful though...

Collapse
 
diek profile image
diek

If the object is the same instance than before, it is not better to update it persé, it depends, the garbage collector will delete unused pointers so no pain in reassign it, depending of the application making an update/copy method can be so much elaborated, even more if you are receiving info fetching api requests.
I do the same as Curtis, always const until i need to reassign the variable.

Collapse
 
curtisfenner profile image
Curtis Fenner

1) If you use TypeScript (and there's really not much reason not to anymore), changing the type is something the compiler will reject -- the problem of not knowing the type of a variable is not a problem of assignment but the lack of static analysis in JavaScript.

2) mutating objects is filled with danger, because you don't know who else has a handle on the object. Invoking immutable/pure functions will necessitate assignment in loops.

Thread Thread
 
matscode profile image
Michael Akanji

I see where you are coming from...

You have 2 points. :-D

It seems to appear like we have a common point.

However, here, the post is just about pure JS.

It's been nice debating with you.. :raise-hand: