Variables in JavaScript

🧠 What Are Variables?

In JavaScript, variables are containers for storing data values. You can think of them as labeled jars that hold information like numbers, text, or even functions.

>>“Variables are the building blocks of logic — every program starts with them.” 🧱

📜 Declaring Variables

JavaScript provides three keywords to declare variables:

Variable Declaration Keywords

var name = "Alice";   // Old-style (function-scoped)
let age = 25;         // Modern (block-scoped)
const pi = 3.14;      // Constant (block-scoped)

Note

💡 Prefer let and const in modern JavaScript. Avoid var unless you know why you need it.

⚖️ let vs const

KeywordMutable?Scope
let✅ YesBlock
const❌ No (can't be reassigned)Block
var✅ YesFunction

📦 Examples of Using Variables

Variable Usage

let message = "Hello, World!";
const year = 2025;
var isActive = true;

console.log(message);
console.log(year);
console.log(isActive);

Note

🧪 Try running these in your browser console or in a file using Node.js!

🧱 Variable Naming Rules

  • ✅ Must start with a letter, _, or $
  • ✅ Can contain letters, digits, _, or $
  • ❌ Cannot start with a number
  • ❌ Cannot use reserved keywords like let, function, etc.

Valid and Invalid Variable Names

let _score = 100;
let $value = 200;
let userName = "Dev";

// ❌ let 1name = "invalid";
// ❌ let let = "reserved keyword";

🔁 Changing Variable Values

You can reassign let and var variables, but const cannot be reassigned:

Mutability Example

let counter = 1;
counter = 2; // ✅ okay

const max = 10;
max = 15;   // ❌ Error: Assignment to constant variable

Note

⚠️ const only prevents reassignment — it doesn't make objects or arrays immutable!

🔒 Scope of Variables

Scope defines where a variable is accessible:

  • 🔁 Block Scope: Accessible only inside {} where declared (let / const)
  • 🧾 Function Scope: Available throughout the function where declared (var)

Scope Example

{
  let a = 10;
  const b = 20;
  var c = 30;
}
console.log(c); // ✅ works (var is function-scoped)
// console.log(a); // ❌ Error (block-scoped)
// console.log(b); // ❌ Error (block-scoped)

🧠 Summary

Variables help you store and manipulate data in JavaScript. Choosing the right keyword (let / const) and understanding scope/mutability is essential for writing clean, bug-free code.

  • ✅ Use let for variables that may change
  • ✅ Use const for constants and fixed values
  • ⚠️ Avoid var unless needed for legacy compatibility
  • 🧱 Follow naming rules to avoid errors

📘 Learn More

>>“Well-named, properly-scoped variables are the secret to readable, maintainable code.” 🌟