Var, let and const keywords
In JavaScript var used to be the only way to declare variables. But with ES6 we now have the let and const keywords. These new ways of declaring variables solves some of the issues involved with using var.
var
The var keyword is scoped to the current execution context meaning that it is scoped to the function it is in, or if it is outside of a function then it is has global scope. This means that var is not block scoped like const or let.
For example, if you use an if statement and use var with it the variable will be scoped globally because var is scoped to the current execution context which means that it is either scoped to its enclosing function or the global scope. Var can be redeclared more than once in the same scope which is a problem that let and const will solve. This is a problem because you can accidently change the value of a variable that you didn’t intend to.
This will return “hi everyone”
let
Let and const variables have block scope which means that they cannot be accessed outside the block { } that they were declared in.
This function will return “well hello there”
Now compare this to var:
This will return “bye”
const
The const keyword was designed with the goal of having a variable that can't change. This prevents someone from accidently changing the value of a variable. Const if useful for things like pi const pi = 3.1415926 which always stays the same.