DEV Community


Posted on

const vs. let

If you're new to JavaScript and coding like me, then you may be wondering why people use const or let. I come from a science/mathematics background and constant means to me that the constant will not vary or change. In JavaScript, const means that the variable assigned cannot be reassigned and it only exists in the block of code where it has been declared or lexical scope.

Attempt of logging a const outside of its lexical scope

In the example above, I logged sum outside of the function in which it was created and it returned an error because sum is only defined inside the function.

Logging a const within its scope

Just to validate my explanation, I provided a log within the variable's lexical scope. Let works in a similar fashion except let can be reassigned, which makes it useful for loops and mathematical purposes.

So I made a basic addition function much like the previous examples, except this function takes an array of numbers. This is where let becomes mandatory. If I were to make the variable sum into a constant, then the code will return an error because we are attempting to reassign its value. The same rule applies for the loop where I let i = 0. If I set const i = 0, then it will never equal anything other than zero. When the code attempts to increment the constant variable, the console returns an error saying "assignment to constant variable".

So that's the difference between const and let. This is my second blog post ever so let me know what you liked or didn't like and I will try to improve on that in my next post.

Top comments (0)