DEV Community

zmiles17
zmiles17

Posted on

1 3

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay