Do you need to use `let` to assign a value to a variable that could change?

I’ve learned to use let to assign values to variables that might change. But I’ve also noticed that it seems like once you’ve initially assigned the value, you don’t need to use let again. For example:

let a = 5;
let b = 5;
a = a + b;

So I started messing around in Codepen, and I also noticed that simply stating: a = 5 (without any let also works):

a = 5;
b = 5;
a = a + b;

Do you need to use let?

When you don’t use let, var, or const the variable gets put in the global scope. It’s generally considered a bad idea and most linters will yell at you for it.

3 Likes

Just to clarify (maybe you already know this), if you tried let a = a + b it wouldn’t be possible because you declare a with let and the assign a value with =, if you tried again with let you’d get a redeclaration error.

1 Like

Yes I did notice that, thank you!!!

You can use var as well. It’s just the older way of defining a variable. Nowadays, coders use let more than var. If you do it without defining tthe variables with let, I’m pretty sure JS will give you an error.

1 Like

If you don’t need to reassign your variable anywhere else, you can use const keyword instead let
If you use let keyword to declare a variable, you can’t redeclare the same variable but you can reassign.
For example:

let a =5;
let a=6; //throws error
1 Like