New to JavaScript and a beginner. I came across JavaScript variables and realized there are three different ways to go about them (var, let and const). Do they each have a specific purpose or you can just use one throughout?
Made some searches on google and apparently var is for old browsers but I want to find out from actual developers, which one is best to use in this day and age? Or it doesn’t really matter?
2
Answers
In my opinion nowadays it is better to use let and const.
According to the ES6 standard, these options are more convenient with their scope. Both give us the so-called block scope. This means that the scope of their use can be limited to a block of code, such as a for loop or an if expression. This gives the developer more flexibility in choosing the scopes of variables.
In addition, if we consider these options, then you will not be able to change the variable declared with const, unlike var and let.
Generally speaking, let and const are often used now, depending on the need.
let & const keywords were introduced in ES6 (2015).var existed since Javascript’s inception
const:
Identifiers declared with const cannot be re-assigned
let & var
scoping:-
The main difference b/w the two is scoping rules. Variables declared by var are scoped to the immediate function body while let variables are scoped to the immediate enclosing block.
print();
Hoisting:-
Variables declared with both let & var are hoisted. Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
Variables declared with var are initialized with undefined before the code is run. So, they are accessible in their enclosing scope even before they are declared:
print();
let variables are not initialized until their definition is evaluated. Accessing them before the initialization results in ReferenceError.
print2();
So, use let when you know that the value of an identifier will change. Use const when the identifier value is constant, wont change. Avoid using var because it causes confusion & bugs.