Skip to main content

Command Palette

Search for a command to run...

Understanding Variables and Data Types in JavaScript

Updated
9 min read
Understanding Variables and Data Types in JavaScript
G

Self-taught Engineer | Disassembled my first PC at 16, been building ever since | Hardware fundamentals to software and coding| Obsessive learning | Built from scratch to scale

When I started learning JavaScript, nothing made sense for a while...

let, const, var, data types, scope — it was a lot to take in all at once.

I wasn't struggling because I wasn't trying hard enough. I was struggling because no one explained the why. Everyone just threw definitions all around and expect all to stick.

So this blog is my personal attempt to fix that for anyone who wants to learn.

I'll go through everything step by step, with real examples and zero unnecessary jargon. By the end, you won't just know what variables are. You'll understand how JavaScript actually thinks about them. Let's get into it....

What Are JavaScript Variables?

Skip the textbook definition for now.

Think of a variable like a drawer in your desk.

  • you put something inside it

  • you stick a label on the front

  • you come back later, open it, and grab what's inside

  • you swap out the contents whenever you need to

That drawer => that's your variable.

In JavaScript, a variable is a named container that holds a value so your program can use it later.

let username = "IronMan";

Here's how I picture it in my own mind:

  • username → the label on the drawer.

  • "IronMan" → what's sitting inside it.

So Why Do We Actually Need Them ?

Because your program needs to remember things.

Think about what happens when you open any app:

  • It remembers who you are

  • It tracks whether you're signed in

  • It knows what's in your shopping cart

  • It holds your settings and preferences

All of that lives in variables. Without them, JavaScript forgets everything the moment it runs — like a brain with zero short-term memory.

Variables are not just important. They're the backbone of every program ever written.

Declaring Variables — var, let, and const

JavaScript gives us three keywords to create variables:

  • var

  • let

  • const

They look similar but behave very differently. This is where most beginners trip up, so let's go through each one carefully.

1. var — The Old Way

var points = 10;

Works fine. You can also update it:

points = 25; // no problem

But var has a catch — it lets you declare the same variable twice without throwing any error:

var country = "India";
var country = "Japan"; // still no error

In a small file this seems harmless. In a real project with hundreds of lines? This can quietly overwrite important values and create bugs that take hours to find.

That's the core problem with var. Modern JavaScript doesn't ban it — but it's rarely the right choice anymore.

2. let — Flexible and Safe

let level = 1;

Use let when the value is going to change over time.

level = 5; // totally valid

But try to declare it twice in the same place:

let level = 10; // Error

JavaScript stops you immediately. And I think that's a feature, not a limitation. It catches mistakes before they become real problems.

3. const — Locked In

const maxPlayers = 4;

When I write const, I'm making a promise to JavaScript:

This value is set. Don't let anyone -> including future me -> change it...

maxPlayers = 6; // Errorr  

JavaScript holds you to that promise...

My personal rule that I actually stick to:

Start with const. If you realize the value needs to change, switch to let. Never reach for var.

This habit alone will save you from a lot of confusing bugs.

Comparison at a Glance

Feature var let const
Can be reassigned Yes Yes No
Can be redeclared Yes No No
Block scoped No Yes Yes
Modern usage Avoid When needed Default choice

You can follow my rules like :

  • Reach for const first

  • Use let only when the value changes

  • Leave var alone for now

What Are Data Types?

Now let's talk about what actually goes inside those variables.

Every value in JavaScript has a type. When I say "data type," I'm just asking:

What kind of thing is stored here?

If a variable is a drawer, the data type tells you whether it's holding a piece of paper, a coin, or a key.

There are two broad categories in JavaScript:

  • Primitive — basic, single values

  • Non-Primitive — complex structures like arrays and objects

We're only covering primitive types here since they're what you'll use constantly as a beginner.

The five main ones:

  1. String

  2. Number

  3. Boolean

  4. Null

  5. Undefined


1. String — Text

Any time you're storing text, you're using a string.

let playerName = "Arjun";
let city = "Bengaluru";
let welcomeText = "Good to have you here!";

Always wrap strings in quotes — single, double, or backticks. Without quotes, JavaScript assumes it's a variable name, not actual text.

Strings show up everywhere: usernames, addresses, error messages, button labels — anything text-based.

2. Number — Numeric Values

let itemsInCart = 3;
let productPrice = 149.99;

Unlike some other languages, JavaScript doesn't split numbers into "integers" and "decimals". Everything is just number.

3 and 149.99 are both the same type. Simple.

Numbers handle everything from counting items to calculating totals to tracking scores.

3. Boolean — Yes or No

Booleans look basic. But they control the logic of nearly every program.

let isPremiumUser = true;
let isCartEmpty = false;

There are only two options: true or false.

They answer questions like:

  • Has the user verified their email?

  • Is the payment successful?

  • Should this button be disabled?

Every if statement, every condition — it all comes down to a boolean at its core.

4. null — Empty on Purpose

null means you deliberately left something blank.

let activeSession = null;

This isn't an accident or a missing value. It's you saying:

I know this is empty right now. I'll fill it in when I need to.

5. undefined — Not Set Yet

Declare a variable without giving it a value:

let discount;

JavaScript steps in and assigns undefined automatically.

The variable exists. There's just nothing in it yet.

How null and undefined actually differ:

undefined

JavaScript assigned this — you never gave it a value

null

You assigned this — intentionally marking it as empty

This a very Small difference, but worth knowing early.

What is Scope?

When I first encountered "scope," it felt like another technical term invented to confuse beginners.

But the actual idea is straightforward.

Scope answers one thing:

Where in your code can this variable be used?

That's it. very simple.

Picture It as Floors in a Building

Think of your program as a building. Each { } block is a separate floor.

Whatever you declare on one floor stays on that floor. You can't jump to a different floor and expect to find it there.

{
  let statusMessage = "Order confirmed";
  console.log(statusMessage); // works fine
}
console.log(statusMessage); // ReferenceError

statusMessage only exists inside that block. Step outside it and JavaScript has no idea what you're referring to.

This isn't the value being undefined — the variable simply doesn't exist outside that floor. That's an important distinction.

Block Scope — How let and const Behave

let and const are block-scoped. They live and die inside the { } they were created in.

if (true) {
  let attempts = 3;
}
console.log(attempts); // ReferenceError

attempts only exists inside that if block. The moment execution steps outside, it's gone.

This is actually a good thing — it keeps variables contained, prevents name clashes, and stops one part of your code from accidentally interfering with another.

Global Scope — Available Everywhere

Declare a variable outside any block or function and it belongs to the global scope:

let appName = "ShopEasy"; // global

function displayHeader() {
  console.log(appName); // accessible here too
}

Global variables can be read from anywhere in your program.

But the downside? Overuse them and your code becomes a mess where any part of the program can modify any value unexpectedly.

Think of global scope like a shared big whiteboard in an office or factory which is useful in small doses, chaotic if everyone dumps everything there.

Keep global's to a minimum.

Scope => Visual Breakdown

Global Scope
│
├── let appName = "ShopEasy"        ✅ accessible everywhere
│
└── function displayHeader() {
      │
      └── console.log(appName)         ✅ can reach up to global
          let headerText = "Welcome"   ❌ only exists inside here
    }

Assignment - Try It

// Step 1: Declare your variables
const fullName = "Riya Mehta";
let age = 19;
let isStudent = true;

// Step 2: Log them
console.log(fullName);    // Riya Mehta
console.log(age);         // 19
console.log(isStudent);   // true

// Step 3: Update what you can
age = 20;
console.log(age);         // 20

fullName = "Someone Else"; // Error — const doesn't allow reassignment

Run this in your browser console or VS Code. Then deliberately break things — change const to let, try re -declaring a variable, see what errors pop up.

That's not failing. That's exactly how this stuff gets wired into your head.

Wrapping Up

Variables and data types aren't beginner concepts you just push through and forget.

They're the foundation everything else is built on top of.

Once it properly clicks that:

  • A variable is just a labeled container holding a value

  • const is your default, let is for things that change, var is best left alone

  • Data types describe what kind of value you're actually storing

  • Scope controls where in your code a variable can even be seen

...the rest of JavaScript starts making a lot more sense.

You stop guessing what the output will be. You start knowing.