var
should be avoided for initalising variables, since those variables are hoisted (Hoisting) to the nearest function scope, or else globally. This brings with it a few problems:
somethingElse
to the value of an undefined variable won’t cause an issue because JavaScript implicitly pulls any var
declarations to the top of the containing function and sets them to undefined
function myFunc() {
let somethingElse = myVar;
if (1 == 1) {
var myVar = 'a string'
}
}
var
variables are not block-scoped. For example in the following snippet, myVar
is accessible to the console log function despite being in a separate blockfunction myFunc() {
{
var myVar = 'hello world'
}
console.log(myVar) // 'hello world'
}
let
allows the value of the variable to be changed. The variable is block-scoped, so won’t be accessible outside of its containing { }
block
const
will not allow the value of the variable to be changed. A variable defined with const
is also block-scoped
JavaScript Hoisting ****refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code