Variables in JavaScript are like containers that store information for later use. They allow you to save data, reuse it, and manipulate it dynamically in your programs.
Think of a variable as a labeled box: you can put data inside it, change it, and access it whenever you need.
1️⃣ Declaring Variables
There are three main ways to declare variables in JavaScript:
1. let (Modern, block-scoped)
let name = "Alice"; // Stores the string "Alice" let age = 25; // Stores the number 25
{ } only)2. const (Constant, cannot be changed)
const pi = 3.1416; // Cannot reassign value later
const value will cause an error3. var (Older, function-scoped)
var city = "Paris";
var in modern code2️⃣ Variable Naming Rules
Valid Examples:
let userName; let $price; let _age; let totalCount;
Invalid Examples:
let 1stName; // Cannot start with number let user-name; // Cannot use hyphen
3️⃣ Data Types Stored in Variables
JavaScript variables can store different types of data:
let name = "Alice"; // String
let age = 25; // Number
let isStudent = true; // Boolean
let colors = ["red","blue","green"]; // Array
let person = {name:"Alice", age:25}; // Object
let empty = null; // Null
let notDefined; // Undefined
4️⃣ Changing Variable Values
Variables declared with let or var can be reassigned:
let age = 20; age = 25; // New value console.log(age); // 25
const cannot be reassigned:
const pi = 3.14; pi = 3.1416; // ❌ Error: Cannot reassign constant
5️⃣ Using Variables in Operations
Variables can be used in mathematical operations or string concatenation:
let x = 10; let y = 5; console.log(x + y); // 15 console.log(x - y); // 5 let firstName = "Alice"; let lastName = "Smith"; console.log(firstName + " " + lastName); // Alice Smith
Explanation:
userName, age, and pi are declaredage is incremented inside the function to show that variables can change<!DOCTYPE html>
<html>
<head>
<title>JavaScript Variables Example</title>
<style>
body { font-family: Arial; padding: 20px; }
button { padding: 10px 20px; margin: 5px; cursor: pointer; }
p { font-size: 18px; color: darkgreen; }
</style>
</head>
<body>
<h1>JavaScript Variables Demo</h1>
<p id="demo">Your message will appear here.</p>
<button onclick="showMessage()">Click Me</button>
<script>
// Variable declaration
let userName = "Alice";
let age = 25;
const pi = 3.1416;
// Function using variables
function showMessage() {
document.getElementById("demo").innerHTML =
"Hello, " + userName + "! You are " + age + " years old. Pi is " + pi;
// Changing variable value
age += 1; // Increment age by 1
console.log("Updated age:", age);
}
</script>
</body>
</html>