
Mastering var in JavaScript: Function Scope, Hoisting, and More
var in JavaScript
The var keyword is used to declare variables in JavaScript. It has been around since the beginning of the language, and understanding its behavior is crucial for working with legacy code and for grasping how variable declarations have evolved.
Characteristics of var
- Function Scope: Variables declared with
varare scoped to the function in which they are declared. If declared outside a function, they are globally scoped. - Hoisting:
vardeclarations are hoisted to the top of their scope. This means that the variable is accessible before its declaration line, but it is initialized withundefineduntil the declaration is executed. - Re-declaration:
varallows re-declaration of the same variable within the same scope without throwing an error.
Examples
- Function Scope
function example() {
if (true) {
var x = 10; // x is declared within the function scope
}
console.log(x); // Output: 10, because x is accessible here
}
example();
2.Hoisting
function hoistingExample() {
console.log(y); // Output: undefined, because y is hoisted
var y = 5;
console.log(y); // Output: 5, after initialization
}
hoistingExample();
3.Re-declaration
function redeclarationExample() {
var a = 1;
var a = 2; // No error, a is re-declared
console.log(a); // Output: 2
}
redeclarationExample();
4.Global Scope
var globalVar = "I am global";
function globalScopeExample() {
console.log(globalVar); // Output: I am global
}
globalScopeExample();
