Skip to main content

Command Palette

Search for a command to run...

Understanding Variables and Data Types in JavaScript

Updated
10 min read
Understanding Variables and Data Types in JavaScript

A beginner friendly guide to storing information in your code,with real ife analogies, simple examples, and hands on practice.


What Is a Variable?

Imagine you have a box. You write a label on it, say, "Name", and you put the value "Rahul" inside it.

Later, whenever you need to know someone's name, you just look at that box. And if the name changes? You open the box, take out the old value, and put in the new one.

That box is a variable.

In programming, a variable is a named storage space that holds a piece of information. Instead of writing the same value over and over again in your code, you store it once in a variable and use the variable's name wherever you need it.

Why Do We Need Variables?

  • To store information (like a user's name or age)

  • To reuse values without repeating them

  • To update values when something changes

  • To make code readable and easy to understand

Without variables, imagine trying to write a program, you'd have to type the same number or text dozens of times, and if it changed, you'd have to update every single place manually. Variables solve that problem.


How to Declare a Variable in JavaScript

JavaScript gives you three ways to create (declare) a variable:

var name = "Rahul";
let age = 20;
const country = "India";
  • var — the old way (still works, but mostly avoided now)

  • let — the modern way for values that can change

  • const — for values that should never change

We'll look at the differences properly in a moment. First, let's understand what kinds of values you can actually store.


Data Types in JavaScript

Every value you store in a variable has a type, it tells JavaScript what kind of information it is.

JavaScript has 5 basic (primitive) data types:

  1. String

  2. Number

  3. Boolean

  4. Null

  5. Undefined

Let's go through each one.


1. String

A string is simply text. It can be a name, a sentence, a word, anything written between quotes.

let firstName = "Rahul";
let greeting = "Hello, World!";
let city = 'Mumbai';       // single quotes work too

You can use either "double quotes" or 'single quotes' for strings. Both are fine.

Real-life example: Think of a string like the text written on a name tag at an event, it's just a piece of text that represents something.


2. Number

A number is exactly what it sounds like, any numeric value. It can be a whole number or a decimal.

let age = 20;
let price = 99.99;
let temperature = -5;

In JavaScript, there's only one Number type for both whole numbers and decimals (unlike some other languages that split them up).

Real life example: Your age, your score in a game, the price of an item, all of these are numbers.


3. Boolean

A boolean can only be one of two values: true or false. That's it.

let isStudent = true;
let hasPassport = false;
let isLoggedIn = true;

Think of a boolean like a light switch — it's either ON (true) or OFF (false).

Real-life example: "Is the student enrolled?" — Yes (true) or No (false). Booleans are very useful when you pair them with control flow (like if statements).


4. Null

null means intentionally empty. You use it when you want to say: "This variable exists, but it has no value right now, on purpose."

let middleName = null;    // person has no middle name
let selectedItem = null;  // nothing is selected yet

💡 null is something you set yourself, you're deliberately saying "this is empty."


5. Undefined

undefined means a variable has been declared but not given a value yet.

let score;
console.log(score);  // undefined

JavaScript automatically assigns undefined when you create a variable but don't give it a value.

The difference: null = "empty on purpose." undefined = "no value was ever given."


Quick Summary of Data Types

Data Type Example What It Represents
String "Rahul" Text
Number 20, 99.5 Any number
Boolean true, false Yes/No, On/Off
Null null Intentionally empty
Undefined undefined No value given yet

How to Check a Variable's Type

You can use typeof to see what type a value is:

let name = "Rahul";
let age = 20;
let isStudent = true;

console.log(typeof name);       // "string"
console.log(typeof age);        // "number"
console.log(typeof isStudent);  // "boolean"

This is handy when you're not sure what type of value is stored in a variable.


var vs let vs const

Now let's understand the real difference between the three ways to declare variables.

let — Use This Most of the Time

let creates a variable whose value can be changed later.

let score = 10;
console.log(score);  // 10

score = 50;          // changing the value
console.log(score);  // 50

This works fine. let allows you to update the value.


const — For Values That Should Not Change

const creates a variable whose value cannot be changed after it is set.

const country = "India";
console.log(country);  // India

country = "USA";  // ❌ ERROR! Cannot reassign a const variable.

If you try to change a const variable, JavaScript will throw an error. Use const when you know the value will stay the same — like a tax rate, a website URL, or a fixed configuration value.

A good habit: start with const. If you later realize the value needs to change, switch it to let.


var — The Old Way (Avoid It for Now)

var works, but it has some confusing behaviours that can lead to bugs. Modern JavaScript code uses let and const instead. You'll see var in older code, so it's good to recognise it, but don't use it in your own new projects.

var city = "Delhi";
city = "Pune";        // this works
console.log(city);    // Pune

Quick Comparison

var let const
Can change value? Yes Yes No
Modern & recommended? Old Yes Yes
When to use? Old code only Values that change Values that stay the same

What Is Scope?

Scope answers one question: "Where in your code can this variable be used?"

Think of it like a room in a house. If you put something inside a room, only people inside that room can use it. People outside the room can't see it or touch it.

Global Scope

If you declare a variable outside any block or function, it's available everywhere in your code. This is called global scope.

let userName = "Rahul";   // declared outside — global scope

if (true) {
  console.log(userName);  // works — can access it here
}

console.log(userName);    // works — can access it here too

Block Scope (with let and const)

If you declare a variable inside curly braces {} using let or const, it only exists inside those braces.

if (true) {
  let message = "Hello!";
  console.log(message);   // works — inside the block
}

console.log(message);     // ERROR — message doesn't exist out here

Think of the {} as a closed room. message was created inside that room. Once you step outside, it's gone.

var does NOT follow block scope, it leaks out of blocks. This is one of the reasons var causes bugs and is avoided in modern code.


Why Does Scope Matter?

Scope helps you keep your variables organised and safe. You don't want every variable in your whole program mixing together. Scope lets different parts of your code have their own variables without interfering with each other.


Assignment

Try writing this program yourself, it's the best way to learn!


Assignment: Your Profile

Declare variables for your name, age, and student status. Print them all. Then try changing some values and see what happens.

// Step 1: Declare your variables
const name = "Rahul";      // name won't change, so we use const
let age = 20;              // age can change, so we use let
let isStudent = true;      // this can change too

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

Output:

Name: Rahul
Age: 20
Is Student: true

Now Try Changing Values

// Updating let variables, this works fine
age = 21;
console.log("Updated Age:", age);     // 21

isStudent = false;
console.log("Is Student:", isStudent); // false

Now Try Changing a const Variable

// Trying to update a const variable — this will cause an error
name = "Priya";
// TypeError: Assignment to constant variable.

Run this in your browser console or in a JavaScript playground and read the error message. Understanding error messages is a key skill for every developer!


Bonus: Check the Types

console.log(typeof name);       // string
console.log(typeof age);        // number
console.log(typeof isStudent);  // boolean

Quick Recap

Concept What It Means
Variable A named box that stores a value
let Declares a variable that can be updated
const Declares a variable that cannot be updated
var Old way — avoid in new code
String Text — "Hello"
Number Numeric value — 25, 3.14
Boolean True or false only
Null Intentionally empty
Undefined No value has been assigned yet
Scope Where in your code a variable can be used

Key Takeaways

  • A variable is like a labelled box, it stores a piece of information with a name.

  • Use let when the value will change, and const when it won't.

  • Every value has a data type, string, number, boolean, null, or undefined.

  • Scope controls where a variable can be accessed, think of it as the variable's "home zone".

  • Use typeof to check what type a value is.

You now understand one of the most foundational ideas in all of programming. Variables and data types are used in every single program ever written. Master these, and you have a rock solid foundation to build on. Keep going!