const over let unless I'm forced to

Andrew Lee - Dec 5 '21 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player