DEV Community

Andrew Lee
Andrew Lee

Posted on

const over let unless I'm forced to

In the beginning, this discussion wasn't even necessary. We only had one choice in JavaScript to store value (var). Nowadays I always reach for const unless I'm forced to.

This argument isn't as strong for JavaScript, since there are no known performance gains at the moment of using a constant (const) over a variable (let). This is not the case in other languages (i.e. Swift) and maybe JavaScript will have performance gains for constants in the future.

When am I forced to use let? If I find myself changing a previously declared constant, JavaScript will throw an error.

const x = "hi";
x = "bye";

// VM226:1 Uncaught TypeError: Assignment to constant variable
Enter fullscreen mode Exit fullscreen mode

This way I don't bother with thinking about which declaration I should use, I'll be alerted when I have to by following a rule.

Arrays and Objects

What about arrays and objects? When we mutate an existing object or array, JavaScript will not give us a warning. This is because they are passed by reference.

In this case I still use const even if changes are being made.

const arr = [];
arr.push(1);
Enter fullscreen mode Exit fullscreen mode

When I create a new array with the new changes (common practice in React to trigger state change), JavaScript will throw me a warning.

let arr = [];
arr = [...arr, 1];
Enter fullscreen mode Exit fullscreen mode

In this case I will switch my const to a let.

Conclusion

const over let unless I'm forced to

I just let my tools let me know if a variable is necessary. It also makes sense to use a variable (let) when the value stored inside of it varies throughout the lifecycle of the program.

Top comments (2)

Collapse
 
andyrewlee profile image
Andrew Lee • Edited

Thanks for pointing that out. I just made an edit to the post to address this.

I still would recommend using const for objects and arrays since mutating an existing array or object. This way I can stick with this rule. When I create a new object after mutating it (common in React), JavaScript will force me to use a variable.

const c = { b: 1 };
c = {...c, b: 42};
Enter fullscreen mode Exit fullscreen mode

What's most important is for the team members to be on the same page and use linters if possible to codify the understanding.

Collapse
 
aitor profile image
dragonDScript

var is underrated.