JavaScript var keyword
The var is the oldest keyword to declare a variable in JavaScript. It has the Global scoped or function scoped which means variables defined outside the function can be accessed globally, and variables defined inside a particular function can be accessed within the function.
Example 1: The below code example explains the use of the var keyword to declare the variables in JavaScript.
var a = 10
function f() {
var b = 20
console.log(a, b)
}
f();
console.log(a);
Output
10 20 10
Example 2: The below example explains the behavior of var variables when declared inside a function and accessed outside of it.
function f() {
// It can be accessible any
// where within this function
var a = 10;
console.log(a)
}
f();
// A cannot be accessible
// outside of function
console.log(a);
Output:
10
ReferenceError: a is not defined
Example 3: The below code re-declare a variable with same name in the same scope using the var keyword, which gives no error in the case of var keyword.
var a = 10
// User can re-declare
// variable using var
var a = 8
// User can update var variable
a = 7
console.log(a);
Output
7
Example 4: The below code explains the hoisting concept with the var keyword variables.
console.log(a);
var a = 10;
Output
undefined
Difference between var, let and const keywords in JavaScript
The keywords var, let, and const in JavaScript define the variable scope and behavior. The var keyword has function scope and is hoisted. The let and const keywords have block scope, with const requiring an initial value and preventing reassignment.