← Back to Chapters

JavaScript Variables

? JavaScript Variables

⚡ Quick Overview

A JavaScript variable is a container used to store data values such as numbers, strings, booleans, objects, and more. You declare variables using var, let, or const.

? Key Concepts

  • Variable: A named storage location for data in your program.
  • var: Function-scoped, older way of declaring variables.
  • let: Block-scoped variable that can be reassigned.
  • const: Block-scoped constant that cannot be reassigned.
  • Naming rules: Names must start with a letter, underscore, or dollar sign.

? Syntax & Theory

✍️ Declaring Variables

? View Declaration Example
var x = 5;
let y = 10;
const z = 15;

?️ Valid Variable Names

? View Naming Example
let firstName = "John";
let _age = 30;
let $salary = 5000;

? Reassigning Values

? View Reassignment Example
let score = 50;
score = 75; // Valid

const pi = 3.14;
pi = 3.14159; // ❌ Error - Assignment to constant variable

? Multiple Declarations

? View Multiple Declarations Example
let a = 1, b = 2, c = 3;

? Live Output & Explanation

? View Example with Console Output
let score = 10;
console.log("Initial score:", score);

score = 20;
console.log("Updated score:", score);

const pi = 3.14;
console.log("Value of pi:", pi);

? Expected Console Output

Initial score: 10
Updated score: 20
Value of pi: 3.14

? Try the Variable Demo

Click the button to increase the counter.

Current counter value: 0

? Tips & Best Practices

  • Use let for values that change.
  • Use const for fixed values.
  • Avoid var in modern code.

? Try It Yourself

  • Declare a variable and change its value, then log both the old and new values to the console.
  • Create a constant (like const city = "Pune";) and attempt to reassign it. Check the console for the error.