Var and let obsolete?

why would i want to use anything other than const when creating variables? it seems like let and var can pollute the global and local namespaces, but const seems like a consistently safe bet to avoid bugs. is there any reason to use let and var anymore in JS?

Hey @py1374291636

I had a little problem today while doing a Project in the Loops Section. We have to keep in our minds that with const, variables cannot be reassigned (change the data type from string to a number for example), nor can you just leave them empty.

What I did today was, the instructions told me to create an empty variable. So what I did? const myVariable; and when I ran my function, trying to reassigning the empty const, I have gotten some errors. It took me a while to figure it out. As soon as I have changed from const to let, everything ran perfectly. Because the const variable was empty, without any data/type.

I am sure others could explain this more thoroughly. But it is definitely not a “safe bet” to just use const.



const is a good bet when we know that a value will never change. Not all values are constant in a running session.

Consider a for loop:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for (let x of arr) {
  const y = x ** 2 + x

In the above, x is a variable that changes value on every loop. It is declared outside of the block so we must use let in order to allow it to change. y, on the other hand never changes once it is declared. Because the block is exited on each iteration it can be redeclared each time.

You’ll find other examples like this, so be sure not to draw any conclusions that you haven’t tested thoroughly.


thanks, i can see now where const doesn’t always work.

thanks, i just started the section on how JS does loops, i’m hoping to run into more examples like these where both let and const are relevant. i’m coming from learning python first, so the extra ways to create variables are throwing me for a “loop” at the moment…