Skdev Online Academy logo
JavaScript

Chapter 1: Variables & Declarations

Understand variables in JavaScript, including var, let, const, block scope, function scope, and hoisting.

What are Variables?

  • Variables are containers that hold data.
  • They help us store, reuse, and update information in JavaScript — from simple values like numbers to complex data like arrays and objects.
  • Think of a variable as a box with a name on it. You can put something inside it (a value), and later check or change what's inside.
  • In JavaScript, you create these boxes using keywords: var, let, or const.

var, let, and const

var

  • Old and Risky
  • Scoped to functions, not blocks
  • Can be redeclared and reassigned
  • Hoisted to the top with undefined value
var score = 10;
var score = 20; // OK

let

  • Modern & Safe
  • Scoped to blocks ({})
  • Can be reassigned but not redeclared
  • Hoisted, but stays in the Temporal Dead Zone (TDZ)
let age = 25;
age = 30; // ✅
let age = 40; // ❌ Error (same block)

const

  • Constant values
  • Scoped to blocks
  • Cannot be reassigned or redeclared
  • Value must be assigned at declaration
  • TDZ applies here too
const PI = 3.14;
PI = 3.14159; // ❌ Error

But: If const holds an object/array, you can still change its contents:

const student = { name: "Shoaib" };
student.name = "Harsh"; // ✅ OK
student = {}; // ❌ Error

Scope in Real Life

  • Block Scope → Code inside {} like in loops, if, etc.
  • Function Scope → Code inside a function
  • let and const follow block scope.
  • var ignores block scope — which leads to bugs.
{
  var x = 5;
  let y = 10;
  const z = 15;
}
console.log(x); // ✅ 5
console.log(y); // ❌ ReferenceError
console.log(z); // ❌ ReferenceError

Hoisting

  • JavaScript prepares memory before running code.
  • It moves all declarations to the top — this is called hoisting.

But:

  • var is hoisted and set to undefined.
  • let and const are hoisted but not initialized — so accessing them early gives ReferenceError.
console.log(a); // undefined
var a = 10;
console.log(b); // ❌ ReferenceError
let b = 20;

Common Confusions

  • const doesn't make things fully constant. It protects the variable, not the value.
  • var is outdated — it's better to use let and const.
  • let and const behave similarly, but const gives more safety — use it when you're not planning to reassign.

Mindset Rule

  • Use const by default. Use let only when you plan to change the value.
  • Avoid var — it belongs to the past.

Practice Zone

  1. Declare your name and city using const, and your age using let.
  2. Try this and observe the result:
let x = 5;
let x = 10;
  1. Guess the output:
console.log(count);
var count = 42;
  1. Create a const object and add a new key to it — does it work?
  2. Try accessing a let variable before declaring it — what error do you see?
  3. Change a const array by pushing a value. Will it throw an error?