What's the difference between the var, let and constant declarations?

I’m having difficulty wrapping my head around the use car, let and const declarations? When is the appropriate use for each declarations?

On the project,

Kelvin Weather

There’s two instances where you use const or let to declare the value. So what is the benefit of using or the other?

Here’s a good article explaining the difference.


Essentailly, const is used to declare constants; variables which cannot be changed, for example:

const a = "something";
a = "somethingelse";
//this would throw an error, as a const variable can't be changed

The differences between var and let are more subtle. var is function scoped, which means that you can access variables declared outside of a function (with var), inside a function, where you can’t do that with let. Don’t worry if that doesn’t make much sense now; when you do functions, it’ll become clearer…

1 Like

Good rule of thumb, use const for everything, unless you are certain that by design they are going to be changing. Take for example a for loop…

for (let x of [1, 2, 3, 4, 5]) {
  const y = x ** 2
  const z = y ** 2
  console.log(`x**2: ${y}, x**4: ${z}`)
}

A new learner will suggest that we cannot make y and z constant declarations because then they cannot change. That would be true if we needed them to change in a single iteration of the loop. x is declared with let because it needs to be able to change. The other two are brand new declarations with each new iteration. None of them can leak out of the code block that contains them (the loop body). That’s the main concern.

2 Likes

What do we mean by change? As in the variable is going to be assign a different value? I think this is where I get the most confused.

Correct, a new value taken from the array is assigned to the variable, x. The variables y and z do not exist outside of the loop body so are created anew with each iteration. x persists until the array has been completely iterated.