The ‘var’ keyword is used to declare variables in JavaScript. It has been around since the early versions of the language and was the primary method for declaring variables before the introduction of ‘let’ and ‘const’.
var x = 1;
if (x === 1) {
var x = 2;
console.log(x);
// Expected output: 2
}
console.log(x);
// Expected output: 2
Scope of ‘var’ Variables:
- Global Scope: Variable declared with ‘var’ outside any function have global scope. They are accessible throughout the entire JavaScript environment.
- Function Scopre: Variables declared with ‘var’ within a function are limited to that function’s scope. They are accessible only within the function or nested functions.
Example
function foo() {
var x = 1;
function bar() {
var y = 2;
console.log(x); // 1 (function `bar` closes over `x`)
console.log(y); // 2 (`y` is in scope)
}
bar();
console.log(x); // 1 (`x` is in scope)
console.log(y); // ReferenceError, `y` is scoped to `bar`
}
foo();
The ‘var’ keyword has certain characteristics that can lead to unexpected behavior if not used carefully. Some common issues include variable hoisting, redeclaration without errors, and the lack of block scope. These issues have been addressed by the introduction of ‘let’ and ‘const’ in modern JavaScript.