# Understanding Variables and Data Types in JavaScript

*By Saurabh Prajapati | Full-stack Engineer @ IBM India Software Lab*

* * *

## Why I Wanted to Learn This (Again)

Okay, I know what you're thinking — "Variables? Really? Isn't that the most basic thing in JavaScript?"

Yes. And that's exactly why it matters.

I've been building full-stack apps with React, Node.js, and even LangChain pipelines. But every time I onboard someone new to JavaScript, I realize how often the *fundamentals* trip people up. So I decided to write this one down properly — the way I *wish* someone had explained it to me when I started.

If you're just starting out, stick with me. This one will click.

* * *

## What Even Is a Variable?

Think of a variable like a **labeled box**.

You have a box. You write a name on it. You put something inside it. Later, you can open that box and see what's in it — or swap it out for something new.

```plaintext
📦 Box labeled "userName"
   Inside: "Saurabh"
```

In JavaScript, that looks like this:

```js
let userName = "Saurabh";
```

That's it. You just created a box called `userName` and stored the value `"Saurabh"` in it.

Why do we need this? Because programs work with *data* — names, numbers, true/false answers. Variables let us **store and reuse** that data instead of writing it out every single time.

* * *

## How to Declare a Variable

JavaScript gives you **three ways** to create a variable:

```js
var oldWay = "I'm from the past";
let modernWay = "I can change";
const fixedWay = "I never change";
```

Let's understand each one.

* * *

## `var` — The Old Way

`var` was the original way to declare variables in JavaScript. It works, but it has some quirky behavior that caused a lot of bugs.

```js
var city = "Ahmedabad";
city = "Mumbai"; // ✅ This works fine
```

Honestly? Just avoid `var` in modern code. Use `let` or `const` instead. I'll explain why in a bit.

* * *

## `let` — The Modern, Flexible Variable

Use `let` when you know the value will **change over time**.

```js
let score = 0;
score = 10;   // ✅ Updated!
score = 25;   // ✅ Updated again!
```

Real-world example: a counter, a user's score, or a form input value.

* * *

## `const` — The Locked Box

Use `const` when the value should **never change**.

```js
const appName = "DevExplorer";
appName = "Something Else"; // ❌ Error! You can't do this.
```

The moment you try to reassign a `const`, JavaScript throws an error.

> **I wish I knew this earlier:** Use `const` by default. Only switch to `let` if you *know* the value needs to change. This habit prevents a lot of accidental bugs.

* * *

## `var` vs `let` vs `const` — Quick Comparison

| Feature | `var` | `let` | `const` |
| --- | --- | --- | --- |
| Can be reassigned? | ✅ Yes | ✅ Yes | ❌ No |
| Block scoped? | ❌ No | ✅ Yes | ✅ Yes |
| Modern best practice? | ❌ Avoid | ✅ Yes | ✅ Yes |
| Risk of bugs? | ⚠️ Higher | 🟢 Low | 🟢 Lowest |

* * *

## Primitive Data Types

Every value you store in a variable has a **type**. JavaScript has 5 primitive types you need to know right now.

### 1\. String — Text

```js
let name = "Saurabh";
let greeting = 'Hello, World!';
let template = `Hi, my name is ${name}`; // Template literal!
```

Anything wrapped in quotes is a string.

### 2\. Number — Any Number

```js
let age = 25;
let price = 99.99;
let temperature = -5;
```

JavaScript doesn't separate integers and decimals. It's all just `number`.

### 3\. Boolean — True or False

```js
let isLoggedIn = true;
let isStudent = false;
```

Think of it like a light switch. On or off. Yes or no. This is incredibly useful in conditions and logic.

### 4\. Null — Intentionally Empty

```js
let selectedUser = null;
```

`null` means "this box exists, but I've intentionally left it empty." You're saying: *"I know there's nothing here right now."*

### 5\. Undefined — Accidentally Empty

```js
let result;
console.log(result); // undefined
```

`undefined` means you created the box but never put anything in it. JavaScript fills it with `undefined` automatically.

> **Wait, what?** Yes, `null` and `undefined` both mean "empty" — but they mean it differently. `null` is *intentional*. `undefined` is *accidental*. I confused these for weeks before it finally clicked.

* * *

## What Is Scope? (Keep It Simple)

Scope answers one question: **"Where can I use this variable?"**

Think of it like rooms in a house.

*   Variables declared **inside a room (block)** can only be used in that room.
    
*   Variables declared **in the hallway (outside)** can be used everywhere.
    

```js
// Outside — accessible everywhere
let globalMessage = "I'm available everywhere";

{
  // Inside a block
  let roomMessage = "I only exist in here";
  console.log(globalMessage); // ✅ Works
  console.log(roomMessage);   // ✅ Works
}

console.log(globalMessage); // ✅ Works
console.log(roomMessage);   // ❌ Error! roomMessage doesn't exist out here
```

### Scope Visualization

```plaintext
┌─────────────────────────────────┐
│  GLOBAL SCOPE                   │
│  let globalMessage = "..."      │
│                                 │
│  ┌───────────────────────────┐  │
│  │  BLOCK SCOPE { }          │  │
│  │  let roomMessage = "..."  │  │
│  │                           │  │
│  │  ✅ Can use globalMessage │  │
│  │  ✅ Can use roomMessage   │  │
│  └───────────────────────────┘  │
│                                 │
│  ✅ Can use globalMessage       │
│  ❌ Cannot use roomMessage      │
└─────────────────────────────────┘
```

This is why `let` and `const` are safer than `var` — they **respect block scope**. `var` doesn't, which is what causes the buggy behavior I mentioned earlier.

* * *

## Key Discoveries

Here's what surprised me (or what trips up beginners the most):

*   `const` **doesn't mean the value is frozen forever for objects/arrays** — just the variable reference. But for primitives like strings and numbers, it's completely locked. (We'll explore this in a future post!)
    
*   `undefined` **vs** `null` — I used to use them interchangeably. Don't. Use `null` when *you* want to express emptiness. `undefined` is what JavaScript gives you when you forget something.
    
*   **Scope is everywhere** — every `if`, `for`, `while`, or `{}` block creates its own scope. Once I understood this, so many bugs made sense.
    

* * *

## Wrapping Up

Variables are the foundation of everything in JavaScript. Every app I've built — from enterprise tools at IBM to personal projects like *Chat With Your PDF* — uses these fundamentals at their core.

Here's the quick recap:

*   **Variables** are named containers for storing data
    
*   Use `const` by default, `let` when values change, avoid `var`
    
*   **Primitive types**: `string`, `number`, `boolean`, `null`, `undefined`
    
*   **Scope** controls where a variable can be accessed
    

The moment this clicked for me was when I stopped thinking of variables as "code things" and started seeing them as **labeled boxes holding information**. Everything else follows from there.

Have you just started learning JavaScript? Or maybe you're revisiting the basics like I did? Drop a comment or reach out — I'd love to hear where you are in your journey.

* * *

## About the Author

**Saurabh Prajapati** is a Full-stack Software Engineer at IBM India Software Lab, working on enterprise cloud-native solutions with Maximo. He specializes in GenAI, React, and modern web technologies — and loves breaking down complex topics into simple, learnable pieces.

*   🐙 GitHub: [prajapatisaurabh](https://github.com/prajapatisaurabh)
    
*   💼 LinkedIn: [saurabh-prajapati](https://linkedin.com/in/saurabh-prajapati)
    
*   📧 [saurabhprajapati120@gmail.com](mailto:saurabhprajapati120@gmail.com)
    
*   🌐 Available for work
    

* * *
