Difference Between Var, Let and Const in ES6
I will try to explain following JavaScripts Keywords:
- var
- let
- const
var:
With “var” there are only two types of scope for a variable.There is global scope which is where we would place a variable if we define the variable with “var” outside of any function. And then there is function scope for variable defined inside of a function. But there is no block scope and this is a source of confusion and occasional bugs.
Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it’s declared. This behavior is called “hoisting”, as it appears that the variable declaration is moved to the top of the function or global code.
Reference for var keyword:
let:
let allows us to define variables.Previously we declare our variables using “var” keyword. But it has some limitations when it comes to scope as it does not offer block scope.But now using “let” keyword we can declare truly block-scoped variables.