Skip to main content

Command Palette

Search for a command to run...

Understanding Variables and Data Types in JavaScript

Published
9 min read

Introduction

Imagine you have a small toolbox where you store different tools. Each tool is placed in a separate compartment with a label. When you need a specific tool, you simply look at the label and take it out. Variables in JavaScript work exactly the same way. They are containers that store information with a name (label) so you can use that information later in your code.

In this blog, we will learn what variables are, how to create them, what different types of data they can hold, and the differences between the three ways to declare variables in JavaScript.


1. What Are Variables and Why Are They Needed?

A variable is a named container that holds a value. Think of it like a labeled box where you store something important.

Why Do We Need Variables?

Imagine you are writing a program that uses a user's name multiple times. Instead of typing the name over and over again, you can store it in a variable and use it whenever needed.

Copilot said: # Understanding Variables and Data Types in

Understanding Variables and Data Types in JavaScript

Introduction

Imagine you have a small toolbox where you store different tools. Each tool is placed in a separate compartment with a label. When you need a specific tool, you simply look at the label and take it out. Variables in JavaScript work exactly the same way. They are containers that store information with a name (label) so you can use that information later in your code.

In this blog, we will learn what variables are, how to create them, what different types of data they can hold, and the differences between the three ways to declare variables in JavaScript.


1. What Are Variables and Why Are They Needed?

A variable is a named container that holds a value. Think of it like a labeled box where you store something important.

Why Do We Need Variables?

Imagine you are writing a program that uses a user's name multiple times. Instead of typing the name over and over again, you can store it in a variable and use it whenever needed.

Real-Life Example

Let's say you are building a college management system for a college. You need to store student information like name, age, grade, and marks. Without variables, your code would look messy and repetitive.

// Without variables
console.log("Student name is Ashish");
console.log("Ashish is 20 years old");
console.log("Ashish scored 92 in Data Structures");

With variables, your code becomes clean and reusable:

// With variables (good practice)
let studentName = "Ashish";
let studentAge = 20;
let dataStructuresScore = 92;

console.log("Student name is " + studentName);
console.log(studentName + " is " + studentAge + " years old");
console.log(studentName + " scored " + dataStructuresScore + " in Data Structures");

As you can see, if you need to change the student information later, you only need to change it in one place!


2. How to Declare Variables Using var, let, and const

In JavaScript, there are three ways to declare variables: var, let, and const. Each has its own purpose and behavior.

Declaring Variables with var

The var keyword was the original way to declare variables in JavaScript. It has been around since the beginning.

var cityName = "Jaipur";
console.log(cityName); // Output: Jaipur

Declaring Variables with let

The let keyword was introduced in modern JavaScript (ES6). It is the preferred way to declare variables in most situations.

let cityName = "Delhi";
console.log(cityName); // Output: Delhi

Declaring Variables with const

The const keyword is used to declare variables that should not change after they are assigned a value. const stands for "constant".

const countryName = "India";
console.log(countryName); // Output: India

Quick Comparison

Feature var let const
Can be declared again Yes No No
Can be reassigned Yes Yes No
Scope Function Block Block
Used in modern code Rarely Yes Yes

3. Primitive Data Types in JavaScript

Data types tell JavaScript what kind of information is stored in a variable. Think of it like labeling your box with "Books", "Toys", or "Electronics".

JavaScript has several primitive data types:

String

A string is text or a sequence of characters. Strings are always written inside single quotes (''), double quotes (""), or backticks (`).

let firstName = "Ashish";
let city = 'Jaipur';
let message = `Welcome to ${firstName}'s city`;

console.log(firstName);  // Output: Ashish
console.log(city);       // Output: Jaipur
console.log(message);    // Output: Welcome to Ashish's city

Number

A number represents numeric values. This includes whole numbers (integers) and decimal numbers (floats).

let age = 18;
let height = 5.8;
let mobilePrice = 15000;

console.log(age);         // Output: 18
console.log(height);      // Output: 5.8
console.log(mobilePrice); // Output: 15000

Boolean

A boolean is the simplest data type. It can only be one of two values: true or false. Booleans are useful for making decisions in your code.

let isStudent = true;
let hasLicense = false;

console.log(isStudent); // Output: true
console.log(hasLicense); // Output: false

Null

null is a special value that represents "nothing" or "no value". You use it when you intentionally want a variable to be empty.

let favoriteColor = null;
console.log(favoriteColor); // Output: null

Undefined

undefined is a value that JavaScript automatically assigns to a variable that has been declared but not assigned any value.

let someValue;
console.log(someValue); // Output: undefined

4. Basic Differences Between var, let, and const

Now let's understand the key differences between these three declaration methods:

Reassignment and Redeclaration

var and let can be reassigned (the value can be changed), but only var can be redeclared (declared again with the same name).

// With var
var favoriteFood = "Samosa";
var favoriteFood = "Dosa"; // This is allowed (redeclaration)
favoriteFood = "Daal Bati";     // This is allowed (reassignment)
console.log(favoriteFood); // Output: Daal Bati

// With let
let favoriteDrink = "Coffee";
favoriteDrink = "Chai"; // This is allowed (reassignment)
// let favoriteDrink = "Tea"; // Not allowed
console.log(favoriteDrink); // Output: Chai

// With const
const country = "India";
// country = "Nepal"; // Not allowed
// const country = "Pakistan"; // Not allowed
console.log(country); // Output: India

What is Hoisting and Temporal Dead Zone?

Hoisting is JavaScript's behavior of moving declarations to the top of their scope before code execution. However, this happens differently for var, let, and const.

var Hoisting

When var is hoisted, it is initialized with the value undefined. This means you can use the variable before it is declared, but it will have the value undefined.

console.log(age); // Output: undefined (not an error)
var age = 25;
console.log(age); // Output: 25

let and const Hoisting with Temporal Dead Zone

let and const are also hoisted, but they are NOT initialized. There is a period from the start of the block until the declaration is reached where the variable cannot be accessed. This period is called the Temporal Dead Zone (TDZ).

If you try to access the variable in the Temporal Dead Zone, you will get a ReferenceError.

console.log(name); // ReferenceError: Cannot access 'name' before initialization
let name = "Piyush";
console.log(name); // Output: Piyush

The same applies to const:

console.log(city); // ReferenceError: Cannot access 'city' before initialization
const city = "Patiala";
console.log(city); // Output: Patiala

Key Takeaway

  • Use let for variables that will change

  • Use const for values that should stay the same

  • Avoid var in modern JavaScript


5. What Is Scope? (Beginner-Friendly Explanation)

Scope is the area of your code where a variable can be accessed and used. Think of it like the visibility range of a variable.

Global Scope

A variable declared outside of any function is in the global scope. It can be accessed from anywhere in your code.

let globalVariable = "I am global";

function myFunction() {
  console.log(globalVariable); // This works
}

myFunction(); // Output: I am global

Block Scope

A variable declared inside a block (like inside an if statement or a loop) is only accessible within that block.

let age = 20;

if (age > 18) {
  let message = "You are an adult in India";
  console.log(message); // This works
}

// console.log(message); // This would cause an error

Function Scope

A variable declared inside a function is only accessible within that function.

function calculateAge() {
  let birthYear = 2005;
  let currentYear = 2026;
  let myAge = currentYear - birthYear;
  return myAge;
}

console.log(calculateAge()); // Output: 21
// console.log(birthYear); // This would cause an error

Comparison Table of var, let, and const

Feature var let const
Declaration Keyword var let const
Can Be Redeclared Yes No No
Can Be Reassigned Yes Yes No
Scope Function Scope Block Scope Block Scope
Hoisting Behavior Hoisted and initialized with undefined Hoisted but not initialized (Temporal Dead Zone) Hoisted but not initialized (Temporal Dead Zone)
When to Use Avoid in modern code Variables that change Values that stay the same
Example Use Case Legacy code Form input values, counters Fixed values like Pi, country names

Summary

  1. Variables are containers that store values with names, making your code clean and reusable

  2. Three ways to declare variables: var, let, and const

  3. Primitive data types: String, Number, Boolean, Null, and Undefined

  4. Modern practice: Use let for changing values and const for fixed values

  5. Scope determines where a variable can be accessed in your code

  6. Hoisting is JavaScript's behavior of moving declarations to the top, but let and const have a Temporal Dead Zone where they cannot be accessed until they are declared