JavaScript Variables Demystified: Exploring var, let, and const

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

  1. Function Scope: Variables declared with var are scoped to the function in which they are declared. If declared outside a function, they are globally scoped.
  2. Hoisting: var declarations are hoisted to the top of their scope. This means that the variable is accessible before its declaration line, but it is initialized with undefined until the declaration is executed.
  3. Re-declaration: var allows re-declaration of the same variable within the same scope without throwing an error.

Examples

  1. 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();