Hi, I am a new javascript programmer. I am in the learning stage, I wanted to ask a question if anyone doesn’t mind. If the “var” and “let” can both be reassigned, then what’s the difference between them? And why do people say we should use “let” instead of “var”?
Hi Hassan,
const
and let
both have been introduced in 2015 with ES6. Before that, there has only been var
for variable declarations. That means that using let
and const
is a more modern way of declaring variables. And while using var
doesn’t indicate whether you intend to overwrite the variable later on, using let
tells the reader of your code that you probably do want to reuse the variable. So it is also a more semantic way of declaring variables.
There are other differences between var
and let
as the so called hoisting. Hoisting means that your variable will be initialized as ‘undefined’ at the top of your code even before you initialized it. That way, you won’t get a type error if you use the variable before you initialized it. But then your code will be harder to debug.
And as a last thing there is a difference between var and let regarding the scope. var is available in the global scope while let is only available in your current scope. Another potential cause of errors that are difficult to debug.
See this MDN article for more infos on scoping differences between var and let.
Thanks, now I understand.
This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.