Skip to main content

Command Palette

Search for a command to run...

Variables in JavaScript: A Beginner's Guide

Updated
โ€ข8 min read
Variables in JavaScript: A Beginner's Guide
V
Vishal Gupta Android dev in progress. Building toward SaaS โ€” one shipped product at a time. I care about reliability over hype. Still learning, but I build things that work.

๐Ÿ’ก What Are Variables & Why They Are Needed

Understanding Variables

JavaScript variable are container which store data .

Visual Box Analogy

We imagine variable as a box as a jar , and data as a sugar in that box we store sugar .

Example: Without Variables

console.log("My name is John");
console.log(25);
console.log(true);

Example: With Variables

let name = "John";
let age = 25;
let isStudent = true;

console.log(name);
console.log(age);
console.log(isStudent);

๐Ÿ”ค Primitive Data Types

Primitive datatype that is store single value like number , string, boolean (true/false) etc .

JavaScript has 5 main primitive data types:

1๏ธโƒฃ String (Text) ๐Ÿ“

Text values enclosed in quotes.

let name = "John";
let city = 'Mumbai';
let message = `Hello`;

console.log(name);        // Output: John
console.log(typeof name); // Output: string

Examples:

  • Name: "Alice"

  • City: "New York"

  • Message: "Hello there"

2๏ธโƒฃ Number (Integers & Decimals) ๐Ÿ”ข

Both whole numbers and decimal numbers.

let age = 25;
let height = 5.8;
let temperature = -10;

console.log(age); // Output: 25
console.log(typeof age); // Output: number

Examples:

  • Age: 25

  • Height: 5.8

  • Temperature: -10

3๏ธโƒฃ Boolean (True or False) โœ“

Only two values: true or false.

let isStudent = true;
let isTeacher = false;
let hasLicense = true;

console.log(isStudent);        // Output: true
console.log(typeof isStudent); // Output: boolean

Examples:

  • Is student? true

  • Has license? false

  • Account verified? true

4๏ธโƒฃ Undefined โ“

Variable declared but no value assigned.

E.g - You have a form and that form a field name is phone number . you have not fill that value for that time that field is undefined means value not put on that field .

let x;

console.log(x); // Output: undefined
console.log(typeof x); // Output: undefined

5๏ธโƒฃ Null ๐Ÿšซ

It represent value not available in variable .

E.g - same thing you have form ๐Ÿ“ and you have to fill phone number field . But you suddenly remember , i don't own any phone and phone number .

So i just put value N/A means not available . Intentionally that N/A signal this field is empty because user not own any phone-number .

let data = null;

console.log(data); // Output: null
console.log(typeof data); // Output: object

Data Types Summary

Type Example Output
String "John" text
Number 25 25
Boolean true true
Null null null
Undefined let x; undefined

๐Ÿ“Œ How to Declare Variables: var, let, and const

Method 1: Using var

The old way (avoid in modern code).

var name = "John";
var age = 25;
var isStudent = true;

console.log(name);
console.log(age);
console.log(isStudent);

Method 2: Using let

The modern way for variables that can change.

let name = "John";
let age = 25;
let isStudent = true;

console.log(name);
console.log(age);
console.log(isStudent);

Method 3: Using const

For values that should NOT change.

const name = "John";
const age = 25;
const isStudent = true;

console.log(name);
console.log(age);
console.log(isStudent);

Syntax Breakdown

โš–๏ธ Basic Difference: var vs let vs const

Comparison Table ๐Ÿ“Š

Feature var let const
Can change value? โœ… Yes โœ… Yes โŒ No
Can re-declare? โœ… Yes โŒ No โŒ No
Scope Function Block Block
Modern? โŒ No โœ… Yes โœ… Yes
Best for? Never Changing values Fixed values

Changing Values

With var:

var x = 10;
x = 20;  // โœ… Can change
x = 30;  // โœ… Can change
console.log(x); // Output: 30

With let:

let y = 10;
y = 20;  // โœ… Can change
y = 30;  // โœ… Can change
console.log(y); // Output: 30

With const:

const z = 10;
z = 20;  // โŒ ERROR! Cannot change

Re-declaring Variables

With var:

var a = 10;
var a = 20;  // โœ… Can re-declare
console.log(a); // Output: 20

With let:

let b = 10;
let b = 20;  // โŒ ERROR! Cannot re-declare

With const:

const c = 10;
const c = 20;  // โŒ ERROR! Cannot re-declare

Real-World Example

// โœ… Use const for fixed values
const maxScore = 100;
const PI = 3.14159;
const userName = "John";

// โœ… Use let for changing values
let currentScore = 0;
currentScore = 50;  // Change as needed
currentScore = 80;

// โŒ Avoid var (outdated)
// var old = "don't use";

๐Ÿ” What Is Scope

Understanding Scope

Scope determines where a variable can be used in your code.

Simple analogy:

Think of scope like a room
  โ†“
A variable inside a room (block) 
  โ†“
Can only be used inside that room
  โ†“
It's invisible outside the room

Global Scope (Everywhere) ๐ŸŒ

Variables declared outside any block are accessible everywhere.

let name = "John";  // Global scope

if (true) {
    console.log(name);  // โœ… Can access here
}

for (let i = 0; i < 3; i++) {
    console.log(name);  // โœ… Can access here too
}

Block Scope (Inside Blocks Only) ๐Ÿ“ฆ

Variables declared inside blocks {} are only available inside.

if (true) {
    let city = "Mumbai";  // Block scope
    console.log(city);    // โœ… Works here
}

console.log(city);  // โŒ ERROR! Not available outside

Block Scope with for Loop

for (let i = 0; i < 3; i++) {
    let message = "Hello";  // Block scope
    console.log(i, message);  // โœ… Works inside loop
}

console.log(i);        // โŒ ERROR! i is not defined
console.log(message);  // โŒ ERROR! message is not defined

Scope Visualization Diagram ๐Ÿ“Š

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   GLOBAL SCOPE                       โ”‚
โ”‚   let globalVar = "available";       โ”‚
โ”‚                                      โ”‚
โ”‚   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚   โ”‚ BLOCK SCOPE (if/for/etc)       โ”‚ โ”‚
โ”‚   โ”‚ let blockVar = "local";        โ”‚ โ”‚
โ”‚   โ”‚                                โ”‚ โ”‚
โ”‚   โ”‚ โœ“ Can use globalVar here       โ”‚ โ”‚
โ”‚   โ”‚ โœ“ Can use blockVar here        โ”‚ โ”‚
โ”‚   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚                                      โ”‚
โ”‚   โŒ Cannot use blockVar here        โ”‚
โ”‚   โœ“ Can use globalVar here           โ”‚
โ”‚                                      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Real Example

let globalName = "John";  // Global

if (true) {
    let blockName = "Alice";  // Block
    
    console.log(globalName);  // โœ… John
    console.log(blockName);   // โœ… Alice
}

console.log(globalName);  // โœ… John
console.log(blockName);   // โŒ ERROR!

๐ŸŽฏ Practical Assignment

Task: Declare and Use Variables

Complete this step-by-step exercise.

Step 1: Declare Variables

Create variables for your personal information:

const name = "John";
const age = 25;
const isStudent = true;

Step 2: Print Them in Console

Display the variables:

console.log("Name: " + name);
console.log("Age: " + age);
console.log("Is Student: " + isStudent);

Expected Output:

Name: John
Age: 25
Is Student: true

Step 3: Try Changing Values with let

Change values and observe behavior:

let score = 0;
console.log("Initial score: " + score);  // Output: 0

score = 50;
console.log("After test: " + score);     // Output: 50

score = 80;
console.log("After improvement: " + score); // Output: 80

Step 4: Try Changing Values with const (Observe Error)

Try to change a const variable:

const maxScore = 100;
console.log("Max score: " + maxScore);  // Output: 100

maxScore = 150;  // โŒ This will cause an ERROR

Error Message:

TypeError: Assignment to constant variable.

What you learn:

  • โœ… let values CAN change

  • โŒ const values CANNOT change

Complete Assignment Code

// Step 1: Declare variables
const name = "John";
const age = 25;
const isStudent = true;

// Step 2: Print them
console.log("Name: " + name);
console.log("Age: " + age);
console.log("Is Student: " + isStudent);

// Step 3: Change values with let
let score = 0;
console.log("\nInitial score: " + score);

score = 50;
console.log("After test: " + score);

score = 80;
console.log("After improvement: " + score);

// Step 4: Try changing const (uncomment to see error)
const maxScore = 100;
console.log("\nMax score: " + maxScore);
// maxScore = 150;  // โŒ Uncomment to see error