Variables (var, let, const)

What Are Variables in JavaScript?

Variables are containers used to store data in your program. You can think of them as labeled boxes where you can keep values like numbers, text, or other types of data.

Why Do We Need Variables?

  • They store values you want to use later
  • They make your code reusable and dynamic
  • They help you organize and manage data
  • They allow you to perform operations and logic

A Real-Life Analogy

Imagine labeling a box as 'age' and putting the number 25 inside it. That’s what variables do — they store a value with a name so you can access or change it later.

let age = 25;
let name = "JD";

Types of Variable Declarations in JavaScript

There are three ways to declare variables: var, let, and const. Each has its own rules and use cases.

  • `var` – Old way (function scoped)
  • `let` – Modern way (block scoped)
  • `const` – For constants (block scoped)

`var` – The Old Way

`var` is the traditional way to declare variables in JavaScript, but it has some issues due to function scoping.

Declaring vs Initializing with var

// Declaring without initializing
var city;

// Initializing
city = "Delhi";

var city; // declaration
city = "Delhi"; // initialization
var city = "Mumbai"; // redeclaration allowed
city = "Pune"; // reassignment allowed

  • Function scoped
  • Can be redeclared
  • Can be reassigned
  • Prone to bugs — avoid in modern code

**Summary**: Use `var` only for legacy code or when you specifically need function scoping. Prefer `let` or `const` in modern JavaScript.

`let` – The Modern Way

`let` is block scoped and prevents many issues found with `var`. Use it when the variable value might change later.

Declaring, Initializing, and Redeclaring with let

let age; // declaration
age = 30; // initialization
// let age = 40; // redeclaration not allowed in same scope
age = 31; // reassignment allowed

  • Block scoped
  • Can be reassigned
  • Cannot be redeclared in same scope
  • Use when value will change

**Summary**: Use `let` when the value will change during the program. It avoids the pitfalls of `var`.

`const` – For Constants

`const` is block scoped and used when the value should never change. It must be initialized at declaration.

Errors When Redeclaring or Reassigning const

const pi = 3.14; // declaration + initialization
// const pi; // Error: Must be initialized
// pi = 3.14159; // Error: Cannot reassign
// const pi = 3.15; // redeclaration not allowed

  • Block scoped
  • Cannot be reassigned
  • Cannot be redeclared
  • Must be initialized at declaration
  • Use when value should stay constant

**Summary**: Use `const` by default unless you know the value will change — in that case, use `let`.

var vs let vs const

Featurevarletconst
ReassignableYesYesNo
RedeclarableYesNoNo
ScopeFunctionBlockBlock
Hoisting BehaviorYes (initialized as undefined)Yes (TDZ - ReferenceError until initialized)Yes (TDZ - ReferenceError until initialized)
Use CaseAvoid in modern JSWhen value changesWhen value stays constant

Which One Should You Use?

Use `const` for most cases, and `let` only when the value will change. Avoid `var` unless maintaining old code.

Variable Naming Rules

  • Names must start with a letter, `_`, or `$`
  • Cannot start with a number
  • No spaces or hyphens allowed
  • Use camelCase (e.g., `userName`, `totalPrice`)
  • Avoid reserved words like `let`, `if`, `return`

JavaScript is Dynamically and Loosely Typed

JavaScript doesn’t require you to declare a variable type — the type is decided at runtime (dynamic typing). It’s also loosely typed, meaning it automatically converts between types when needed (type coercion).

FeatureDynamically TypedLoosely Typed
DefinitionVariable type is decided at runtime and can change during execution.JavaScript automatically converts data types when needed.
Main BehaviorYou can store any type of value in the same variable at different times.Type coercion happens implicitly or explicitly.
Examplelet x = 10; x = 'Hello'; // works fine5 + '5' → '55', '10' - 2 → 8
ProsFlexible and easy to write code without worrying about types.Convenient when mixing values of different types.
ConsCan cause bugs if you forget the current type of a variable.May produce unexpected results if coercion logic isn’t clear.

// Dynamically typed example
let value = 100;    // number
value = "hundred";  // string

// Loosely typed example
console.log(5 + "5");   // "55"
console.log("10" - 2);  // 8

Quick Recall

  • Dynamic typing → “Change clothes anytime” (variable changes type freely at runtime)
  • Loose typing → “Mix and match outfits” (JS automatically mixes types via coercion)

Best Practices

  • Use const by default for values that won't change.
  • Use let for values that may change later.
  • Avoid var in modern JavaScript unless you specifically need function-scoped variables.
  • Always use clear, camelCase names for variables.

Summary

Variables store and manage data in JavaScript. You can declare them with var, let, or const. Modern best practice is to use const unless you know the value will change, then use let. Avoid var in most cases. JavaScript’s dynamic and loose typing makes variables flexible but can also lead to unexpected results if not handled carefully.

JavaScript Variables Explained (var, let, const)

@JDCodebase • Learn JavaScript the right way 🚀