๐Ÿง  JavaScript Variables

Variables in JavaScript are used to store data values. You can declare variables using var, let, and const. Understanding how they work is key to writing bug-free and efficient code.

๐Ÿ“Œ Why Use Variables?

  • To store and reuse data.
  • To make code dynamic and flexible.
  • To make programs more readable and maintainable.

๐Ÿ“ฆ Variable Declaration

There are three ways to declare variables in JavaScript:

var name = "JD";     // function-scoped
let age = 25;        // block-scoped
const PI = 3.14;     // block-scoped, read-only

๐Ÿ” var

  • Function-scoped.
  • Can be redeclared and updated.
  • Hoisted to the top of its scope and initialized as undefined.

๐Ÿ“ฆ let

  • Block-scoped.
  • Cannot be redeclared in the same scope.
  • Hoisted but not initialized (TDZ - Temporal Dead Zone).

๐Ÿ”’ const

  • Block-scoped.
  • Cannot be redeclared or reassigned.
  • Must be initialized during declaration.

๐Ÿง  Scope of Variables

  • Global Scope: Declared outside any block or function.
  • Function Scope: Accessible only within a function (applies to var).
  • Block Scope: Declared inside a block ({}) and only accessible within (applies to let and const).

๐Ÿ“ค Hoisting

JavaScript moves declarations to the top of the scope. However, only var is initialized with undefined. let and const are hoisted but not initialized (TDZ).

console.log(a); // undefined
var a = 10;

console.log(b); // ReferenceError
let b = 20;

โœ… Best Practices

  • Use const by default.
  • Use let only if the value will change.
  • Avoid var to prevent unexpected bugs due to scope leakage.

๐Ÿงช Interview Questions

  1. What is the difference between var, let, and const?
  2. What is variable hoisting in JavaScript?
  3. What is the Temporal Dead Zone (TDZ)?
  4. Why should we prefer const and let over var?
  5. What are global, function, and block scopes?

๐Ÿงฐ Practice Exercise

Write a JavaScript program to demonstrate scoping and hoisting:

function testScope() {
  console.log(x); // undefined
  var x = 5;

  if (true) {
    let y = 10;
    console.log(y); // 10
  }

  console.log(typeof y); // ReferenceError
}
testScope();