What are the differences between `var` and `let`? Are they necessary?

When creating a variable, do you need to use let or var at all if the variable ISN’T going to be a constant? The code still seems to record the variable just fine, and allow changes, whether I use var/let or not. ?

Same with spaces between the +, -, / etc. The code seems to work just fine without the extra spaces so do I really need them, or it’s just accepted practice, or the “standard” that people put spaces between those characters for neatness (or whatever)?

2 Likes

do you need to? No. Should you? Yes.

the keyword (var or let) indicates the scope of the variable, without var, let or const the variable has a global scope. Which is far from ideal

for readability, the spaces are recommended

14 Likes

This post has links to a few articles that explain variable declaration pretty well.

4 Likes

Hello,

But what is the difference between var and let then, if both of them can be reassigned to a diff value later???

Hi,

Also:

12 Likes

I understand that we do not use VAR anymore ?

We can still use var if you have a good reason, but generally not. let and const are preferable.

3 Likes

Hi I have a question,

In this exercise the loop need to be stated as ‘let’

for( i=0;i<bobsFollowers.length;i++){
  for( j=0;j<tinasFollowers.length;j++){
    if(bobsFollowers[i]===tinasFollowers[j]){
      mutualFollowers.push(bobsFollowers[i])
    }
  }
};

the correct one should be like this

for(let i=0;i<bobsFollowers.length;i++){
  for(let j=0;j<tinasFollowers.length;j++){
    if(bobsFollowers[i]===tinasFollowers[j]){
      mutualFollowers.push(bobsFollowers[i])
    }
  }
};

The result does the same thing, so if we do not specify whether it’s VAR, CONST, or LET, is it still okay? Thanks

let ensures the variable are block-scoped, so variables don’t pollute the global namespace or leak outside the intented scope.

There is a difference between: working code and good code. And maybe even more important, understanding the difference/consequences when doing something (like leaving out let keyword)

3 Likes

Just to confirm - because the course doesn’t specifically say this, but if I wanted a variable with global scope that can be overwritten, I don’t need to put a variable declaration keyword at the front?

there is a difference between what is possible and what is good practice. And there certainly small difference (like how the variable interacts with the window object)

1 Like