var
, let
, and const
are keywords used in JavaScript for declaring variables. While all of them are used for variable declaration, they differ in terms of scope, hoisting, and mutability.
var
var
is the oldest keyword for declaring variables in JavaScript. It has function-level scope, which means that a variable declared with var
is accessible within the function in which it is declared, as well as any nested functions. Variables declared with var
are also hoisted to the top of their scope, meaning that they are moved to the top of the code block in which they are declared. However, they are not initialized to a value until the line of code where the variable is actually declared is reached. This can sometimes lead to unexpected behavior, as a var
variable can be accessed before it is initialized.
function example() {
var x = 1;
if (true) {
var x = 2; // same variable as the one declared in the function scope
console.log(x); // Output: 2
}
console.log(x); // Output: 2
}
example();
In the above example, var
is used to declare the variable x
with a value of 1
. Within the if
block, var
is used again to redeclare x
with a value of 2
. This is possible because var
variables have the function-level scope and can be accessed and modified within nested blocks.