JavaScript Variables

JavaScript Variables: A Complete Beginner's Guide
Everything you need to know about storing and using data in JavaScript
Why Every Programmer Needs Variables?
Imagine you're playing a video game and you need to keep track of your score, health points, and current level. You could try to memorize these numbers, but what if your score increases after defeating an enemy? What if you take damage and your health changes? What if multiple parts of the game interface need to display your current stats?
In programming, we face the same challenge- we need to store values or information and use it throughout our code. That's exactly what variables do for us.
What is a Variable?
The Simple Definition
A variable is like a labeled container that stores data in your program. Just like you might put specific type of food item in a jar labeled "Cookies". Same way you can put data in a variable with meaningful name.
Real-World Analogy
Think of variables as:
Labeled boxes in a storage room
Medicine bottles with prescription labels (each bottle clearly marked)
Sticky notes with important information
Contacts in your phone (name + phone number)
Why Do We Need Variables?
Variables solve three major problems:
Memory: Store information for later use
Reusability: Use the same value in multiple places
Flexibility: Change values without rewriting code
// Without variables (bad):
console.log("Hello, John!");
console.log("John, you have 5 new messages");
console.log("Welcome back, Sahil!");
// With variables (good):
let userName = "John";
let messageCount = 5;
console.log("Hello, " + userName + "!");
console.log(userName + ", you have " + messageCount + " new messages");
console.log("Welcome back, " + userName + "!");
// Change the values
let userName = "Sonam";
let messageCount = 2;
console.log("Hello, " + userName + "!");
console.log(userName + ", you have " + messageCount + " new messages");
console.log("Welcome back, " + userName + "!");
Creating Your First Variable
Basic Syntax
Example 1:
let variableName = value;
//declar
let userName; // Declared but no value yet (undefined)
const maxScore; // This would cause an error - const needs a value
//assign
let age; // Declare first
age = 25; // Assign value later
// OR declare and assign in one line:
let name = "Sarah"; // Declare and assign together
//Multiple lines
// Method 1: One line each
let firstName = "John";
let lastName = "Smith";
let age = 30;
// Method 2: Multiple declarations in one line
let x = 10, y = 20, z = 30;
// Method 3: Declare multiple, assign later
let width, height, depth;
width = 100;
height = 200;
depth = 50;
// Method 4: Mixed (some with values, some without)
let score = 0, lives, playerName = "Alex";
Example 2:
// Storing different types of data
let age = 25; // Number
let name = "Alex"; // String (text)
let isStudent = true; // Boolean (true/false)
let favoriteColor = "blue"; // Another string
// Using the variables
console.log("My name is " + name);
console.log("I am " + age + " years old");
console.log("Am I a student? " + isStudent);
let vs const
JavaScript gives us two main ways to create variable: let and const. Here's when to use each:
Use let
When Values Can change
let score = 0; // Score starts at 0
score = 10; // Score changes to 10
score = score + 5; // Score changes to 15
let currentWeather = "sunny";
currentWeather = "rainy"; // Weather can change
Use const
When Values Stay the Same
const pi = 3.14159; // Pi never changes
const myBirthday = "Jan 26"; // Birthday doesn't change
const appName = "My App"; // App name stays the same
// This would cause an error:
// pi = 3.14; Can't change a const!
Quick Guide
Can this value change later? Use let
Will this value always stay the same? Use const
Not sure? Start with const, change to let if needed
What About var
?
You might see var in older code, but modern JavaScript uses let and const. Think of var as the old way, it still works, but let and const are better and safe.
Variable Naming Rules & Conventions
Rules (Must Follow)
// ✅ Valid names
let userName = "John";
let age2 = 25;
let _private = "secret";
let $price = 19.99;
// ❌ Invalid names
let 2age = 25; // Can't start with number
let user-name = "John"; // No hyphens
let let = "hello"; // Can't use reserved words
Naming Conventions
// ✅ Good naming practices
let firstName = "John"; // camelCase
let totalPrice = 99.99; // Descriptive
let isLoggedIn = true; // Clear boolean
let userAccountBalance = 500; // Self-explanatory
// ❌ Poor naming practices
let x = "John"; // Not descriptive
let data = 99.99; // Too vague
let flag = true; // Unclear purpose
let thing = 500; // Meaningless
camelCase Convention
JavaScript uses camelCase for variable names:
Start with lowercase letter
Capitalize the first letter of each new word
No spaces or special characters
let firstName = "Sarah";
let lastLoginDate = "2024-01-15";
let numberOfUnreadMessages = 5;
let isEmailVerified = true;
Descriptive Names Save Time
// You'll forget what these mean
let a = 21;
let b = a * 365;
let c = b * 24;
// Crystal clear purpose
let ageInYears = 21;
let ageInDays = ageInYears * 365;
let ageInHours = ageInDays * 24;
JavaScript Variable Scope
What is Scope?
Think of scope like rooms in a house. Each room has its own space, and you can only access things that are in the room you currently are in (plus some shared space).
Technical Definition Scope is a fundamental concept in programming that defines the visibility and accessibility of variables, functions within different parts of the program during execution.
The term visibility and accessibility means when a variable able to access from anywhere in the program we can say its visible and accessible.
function example() {
let localVar = "I exist here";
// localVar is VISIBLE only inside this function
}
console.log(localVar); // NOT VISIBLE here - ReferenceError
let globalVar = "I'm accessible everywhere";
function test() {
console.log(globalVar); // ACCESSIBLE here
}
console.log(globalVar); // ACCESSIBLE here too
In JavaScript there are 4 concepts for scope Global Scope, Function Scope, Block Scope.
- Global Scope : Technical Definition: Global scope refers to the outermost execution context where variables are declared outside of any function, block, or module and are accessible throughout the entire program execution.
var globalName = "John"; // This is in global scope
let globalAge = 25; // This is also global
function sayHello() {
console.log(globalName); // Can access global variables
console.log(globalAge); // Can access global variables
}
sayHello(); // Output: John, 25
console.log(globalName); // Can access from anywhere
- Function Scope : It refers to the scope inside the function. Variables created inside a function can ONLY be used inside that same function. Note : Each function invocation creates a new execution context with its own variable environment. Means : Every time you CALL a function, it creates a brand new, separate workspace with its own variables
function officeCubicle(employeeName){
let computer = "Hp Laptop"; //Personal computer
let documents = `${employeeName}'s files`; // Personal files
console.log(`${employeeName} is working with ${computer}`);
}
officeCubicle("Alice"); // Alice gets her own cubicle with her own stuff
officeCubicle("Bob"); // Bob gets a completely separate cubicle
function simpleExample() {
let message = "Hello!"; // Gets created fresh every time
console.log(message);
}
simpleExample(); // Creates room #1, message = "Hello!"
simpleExample(); // Creates room #2, message = "Hello!" (brand new!)
function myFunction() {
var functionName = "Alice"; // Only exists inside this function
let functionAge = 30; // Only exists inside this function
console.log(functionName); // works inside the function
}
myFunction(); // Output: Alice
console.log(functionName); // Error! Can't access outside the function
- Block Scope: Variables created inside curly braces {} can only be used inside those same curly braces.
if (true) {
let insideBox = "I'm trapped in this box!"; // Variable lives in the {} box
console.log(insideBox); // Works - we're inside the same box
}
console.log(insideBox); // Error! Can't reach inside the box from outside
JavaScript creates a brand new 'storage container' for each set of curly braces {}
// Storage Unit #1 (Global)
let globalItem = "Everyone can see this";
if (true) {
// JavaScript creates Storage Unit #2 for this block
let blockItem1 = "Only this block can see me";
if (true) {
// JavaScript creates Storage Unit #3 for this nested block
let blockItem2 = "Only this inner block can see me";
console.log(globalItem); // Can access global storage
console.log(blockItem1); // Can access parent block storage
console.log(blockItem2); // Can access current block storage
}
// Storage Unit #3 gets thrown away here
console.log(blockItem2); // Error! Storage Unit #3 is gone
}
// Storage Unit #2 gets thrown away here
Scope Chain: The scope chain is JavaScript's variable lookup mechanism. It's a linked list of execution contexts where each context points to its parent context.
How it Works:
Start at current execution context
*Search for variable in current scope
If not found, move to parent scope
Repeat until variable found or global scope reached
Throw Reference Error if not found
Current Scope → Parent Scope → Grandparent Scope → Global Scope → null
let global = "global"; // Global scope
function outer() {
let outerVar = "outer"; // Outer function scope
function inner() {
let innerVar = "inner"; // Inner function scope
// Scope chain: inner → outer → global
console.log(innerVar); // Found in: inner scope
console.log(outerVar); // Found in: outer scope
console.log(global); // Found in: global scope
}
}
let vs const vs var
- Declaration & Initialization
var x; // Can declare without value
let y; // Can declare without value
const z; // Must initialize immediately
const z = 10; // Must have value
- Declaration Rules
var name = "John";
var name = "Jane"; // var allows redeclaration
let age = 25;
let age = 30; // let prevents redeclaration
const city = "NYC";
const city = "LA"; // const prevents redeclaration
- Reassignment Rules
var score = 100;
score = 200; // var can reassign
let level = 1;
level = 2; // let can reassign
const health = 100;
health = 150; // const cannot reassign
- Scope Differences
// var: Function scoped
function test() {
if (true) {
var x = 1; // Available throughout function
}
console.log(x); // Works
}
// let/const: Block scoped
function test() {
if (true) {
let y = 1; // Only available in this block
}
console.log(y); // Error
}
Subscribe to my newsletter
Read articles from Bijayananda Lenka directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
