What’s the difference between a variable var and a variable const?
From the Mozilla Developer Docs
varstatement declares a variable, optionally initializing it to a value.
const (Click for more…)
Constants are block-scoped, much like variables defined using the
letstatement. The value of a constant can’t be changed through reassignment, and it can’t be redeclared.
OK, so what I understand is that the difference between them is having the possibility to reassign a value or not. But what’s the point of having a variable without an assigned value?
I think you might have misunderstood.
You can still “initialise” your
const variables, the same way you can a
var. You just can’t change them once they’re declared, they’re constant as the name implies.
var my_variable_1 = 21; console.log(my_variable_1); >> 21 const my_constant_1 = 35; console.log(my_constant_1); >> 35 my_variable_1 = 99; console.log(my_variable_1); >> 99 my_constant_1 = 53; >> TypeError: Assignment to constant variable.
Oh, I see. Thank you that helps a lot. What about the difference between let and var variables, then?
As I understand it, any variable you declare with
var is either function-scoped, or global if you’ve declared it outside of a function. Any variable you declare with
let is block-scoped, or global if you’ve declared it outside of any other code block.
Again, the Mozilla Dev documentation on let is really rather good and would probably help you understand how it differs from
I’ll check it out, but anyway thanks a lot for the help, appreciate it!