Professional Documents
Culture Documents
Difference Between Var
Difference Between Var
The difference between let and var is in the scope of the variables they create: Variables
declared by let are only available inside the block where they're defined. Variables
declared by var are available throughout the function in which they're declared.
There are three keywords in JavaScript that can be used to declare variables: let, var, and
const. Each keyword has different rules and implications for how the variables they create can
be used.
Block-scoped means that the variable is only available within the block it was declared
in, which is usually denoted by curly braces {}.
Function-scoped means that the variable is only available within the function it was
declared in. Global variables are available throughout your entire code.
Constants are also called “immutable variables”, but that’s a bit of a misnomer since
they are actually variables – just ones that can’t be reassigned.
The var keyword is the oldest way of declaring variables in JavaScript and is supported by all
browsers. The let and const keywords are newer additions to the language and are not
supported by older browsers.
If you need to support older browsers, you can use var instead of let or const. If you don’t need
to support older browsers, you can use let or const. If you want your variable to be immutable,
use const.
As you can see, var and let variables can be reassigned, but const variables cannot.
Another difference between var and let/const is that var variables are function-scoped, while
let and const variables are block-scoped.
This means that var variables are only available within the function they were declared in.
So, to sum up, the main differences between var, let and const are:
The scoping principles of const are the same as that of the let keyword. Like let, the variables
declared with the const keyword will also have scope restricted to the block in which they are
declared.