JavaScript Variables

Variables are containers for storing data values in JavaScript. They allow you to store numbers, strings, objects, or even functions for later use or manipulation. In modern JavaScript, there are three ways to declare variables: var, let, and const.


Declaring Variables

var

  • Older way to declare variables.
  • Function-scoped.
  • Can be redeclared and updated.
var name = "Alice";
var name = "Bob"; // Redeclaration is allowed

let

  • Introduced in ES6 (2015).
  • Block-scoped.
  • Can be updated, but not redeclared in the same scope.
let age = 25;
age = 30; // ✅ Allowed
// let age = 35; ❌ Not allowed in same scope

const

  • Block-scoped.
  • Cannot be updated or redeclared.
  • Must be initialized at the time of declaration.
const country = "India";
// country = "USA"; ❌ Error: Assignment to constant variable

Naming Rules and Conventions

  • Variable names must begin with a letter, $, or _.
  • They are case-sensitive.
  • Use camelCase for naming: firstName, totalAmount.
let $price = 100;
let _temp = 37;
let userName = "John";

Variable Scope

  • Global Scope: Variables declared outside any function or block.
  • Function Scope (var): Accessible anywhere inside the function.
  • Block Scope (let, const): Limited to { } block.
function example() {
  var x = 10;
  if (true) {
    let y = 20;
    const z = 30;
    console.log(x); // ✅ 10
    console.log(y); // ✅ 20
  }
  // console.log(y); ❌ ReferenceError
}

Hoisting

  • Variables declared with var are hoisted to the top of their scope, but initialized as undefined.
  • let and const are hoisted too, but not initialized, which leads to a temporal dead zone (TDZ).
console.log(a); // undefined (due to hoisting)
var a = 5;

console.log(b); // ❌ ReferenceError
let b = 10;

Examples

var city = "Delhi";
let temperature = 32;
const PI = 3.14;

temperature = 30;     // ✅
city = "Mumbai";      // ✅
// PI = 3.1416;       ❌ Error

Summary Table

KeywordScopeRedeclarableReassignableHoisted
varFunction✅ Yes✅ Yes✅ Yes (as undefined)
letBlock❌ No✅ Yes✅ Yes (TDZ)
constBlock❌ No❌ No✅ Yes (TDZ)

Best Practices

  • Prefer let and const in modern JavaScript.
  • Use const by default unless you plan to reassign.
  • Avoid var unless working with legacy code.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.