Member-only story
Var, Let and Const — What’s the Difference?
One of the features that came with ES6 is the addition of let and const. They are used for variable declaration. Now, what’s the difference between the original variable declaration var with let and const?
Var
Before ES6, var declarations were used.
Var scope
Scope means where these variables are available for use. var declarations are globally scoped or function/locally scoped.
var is a function scoped when it is declared within a function. It’s only available and can be accessed only within that function.
A variable defined using a var statement is known throughout the function it is defined in, from the start of the function.
var tester = "hey hi";
function newFunction() {
var hello = "hello";
}
console.log(hello); // error: hello is not defined
var variables are initialized with undefined. We can say that variables declared with var keyword are hoisted and initialized. It means that they are accessible in their enclosing scope even before they are declared, however the value is undefined before the declaration statement is reached.
function checkHoisting() {
console.log(foo); // undefined
var foo = "Foo";
console.log(foo)…