JavaScript Variables
Storing and managing data in JavaScript
📦 What are JavaScript Variables?
Variables are containers that store data values. In JavaScript, you can create variables using var, let, or const keywords.
// Creating variables
let name = "John";
const age = 25;
var city = "New York";
console.log(name, age, city);
Output:
John 25 New York
Variable Declaration Keywords
let
Block-scoped, can be reassigned
let x = 10;
x = 20; // Can change
const
Block-scoped, cannot be reassigned
const PI = 3.14159;
// PI = 3.14; // Error!
var
Function-scoped, can be reassigned
var name = "John";
name = "Jane"; // Can change
Naming
Rules for variable names
let myVariable = 1;
let _private = 2;
let $special = 3;
🔹 Variable Declaration and Assignment
You can declare variables and assign values in different ways:
// Declaration and assignment together
let firstName = "John";
const lastName = "Doe";
// Declaration first, assignment later
let age;
age = 25;
// Multiple variables at once
let x = 5, y = 10, z = 15;
console.log(firstName, lastName, age, x, y, z);
Output:
John Doe 25 5 10 15
🔹 Variable Naming Rules
JavaScript variable names must follow certain rules:
// Valid variable names
let userName = "John";
let user_name = "Jane";
let $price = 100;
let _count = 5;
let age2 = 25;
// Invalid variable names (will cause errors)
// let 2age = 25; // Cannot start with number
// let user-name = "X"; // Cannot contain hyphens
// let let = "value"; // Cannot use reserved words
console.log(userName, user_name, $price, _count, age2);
Output:
John Jane 100 5 25
🔹 Variable Scope
Variables have different scopes depending on where they are declared:
// Global scope
let globalVar = "I'm global";
function myFunction() {
// Function scope
let functionVar = "I'm in function";
if (true) {
// Block scope
let blockVar = "I'm in block";
console.log(globalVar); // Accessible
console.log(functionVar); // Accessible
console.log(blockVar); // Accessible
}
// console.log(blockVar); // Error! Not accessible here
}
myFunction();
Output:
I'm global
I'm in function
I'm in block