# Understanding Variables and Data Types in JavaScript

Hey! Welcome to the very first post of our **JS Exploration** series.

You know how it is, whenever you look up JavaScript variables online, you usually find the same boring examples like `let x = 10` or `let apple = "fruit"`. But come on, we aren't here to build a fruit basket. We are here to build actual, complex applications.

So, put on your developer armor. Today, we are managing pirate ships, RPG hero stats, and magical inventories to really understand **Variables and Data Types** in JavaScript. Grab your chai, and let's get into it. ☕

### 1\. Storage Containers: `var`, `let`, and `const`

Think of variables like those treasure chests we keep hoarding in RPG games. You label the chest and stash something inside so you can easily find it later. In JavaScript, we have three ways to label our chests: `var`, `let`, and `const`.

#### The Modern Standard: `let` and `const`

Honestly, 99% of the time, you will only use these two.

`let` is used for values that you know will *change* (mutate) over time. Honestly, `let` is like your ex, can change at any time without warning! 😂

```javascript
let crewCount = 12;
console.log("crew count: ", crewCount); // 12

// We recruited more sailors!
crewCount = 14; 
console.log("crew count: ", crewCount); // 14
```

`const` is used for values that should *never* be reassigned. It literally stands for "constant". Think of `const` like your brothers and your daily cutting chai, they never leave you and they absolutely cannot be changed! ☕🤝

```javascript
const captainName = "Jack Sparrow";
console.log("Captain Name: ", captainName);

// This will crash the ship (throw an error)! Don't even try it.
// captainName = "Dipesh"; 
```

#### The Ghost of the Past: `var`

Before 2015, JavaScript only had `var`. It does the same job, but bro, it has a massive flaw: **It doesn't respect block scope.** Imagine hiding your treasure inside a secure room (like an `if` statement block). With `let` or `const`, the treasure stays locked in that room. With `var`, it magically leaks out through the walls.

```javascript
if (true) {
  var leakyTreasure = "Gold coins";
}

// var ignores the {} walls! How did this get out?!
console.log(leakyTreasure); // Output: "Gold coins"
```

*My advice? Always use* `let` *and* `const`*. Leave* `var` *at the bottom of the ocean. (Speaking of the ocean, have you explored our "*[*From Wire to Web*](https://blog.mayurbadgujar.me/series/wire-web)*" series yet? 😉🌊)*

### 2\. Primitive Data Types

A "Data Type" just tells the JavaScript engine what *kind* of data is inside your chest. Is it text? A number? A simple Yes/No?

Here are the absolute basics (Primitives) you'll use every day:

*   **String** (Text wrapped in quotes):
    
    ```javascript
    const weaponName = "Flame Sword";
    console.log("Weapon: ", weaponName, "| type: ", typeof weaponName);
    ```
    
*   **Number** (Integers or decimals):
    
    ```javascript
    const attackPower = 75;
    const attackUpgrade = 1.5;
    ```
    
*   **BigInt** (For massive numbers that normal Numbers just can't handle):
    
    ```javascript
    console.log(typeof 42n); // Notice the 'n' at the end!
    ```
    
*   **Boolean** (`true` or `false`):
    
    ```javascript
    const isLoggedIn = true;
    ```
    
*   **Undefined** (A chest you created, but forgot to put anything inside):
    
    ```javascript
    let bonusEffect;
    console.log(typeof bonusEffect); // Output: undefined
    ```
    
*   **Null** (An *intentional* empty chest. You explicitly told JS, "there is nothing here"):
    
    ```javascript
    let curseStatus = null;
    let weatherApiResponse = null;
    ```
    
*   **Symbol** (Creates a unique, hidden identifier—even if the names look identical):
    
    ```javascript
    const uniqueRuneId = Symbol("rune_of_fire");
    const uniqueRuneId2 = Symbol("rune_of_fire");
    // These two are NOT the same!
    ```
    

### 3\. Non-Primitive Data Types

Primitive types hold just *one* piece of value. But what if you need to store an entire character's profile, or a whole list of items? That's where we use **Non-Primitives** (also known as Reference Types).

#### Objects (Key-Value pairs)

Objects let us group related data together using labels (keys). Super useful.

```javascript
const heroStats = {
  name: "Deepak",
  level: 12,
  class: "Ranger",
};
console.log("Hero: ", heroStats, " | type: ", typeof heroStats);
```

#### Arrays (Ordered Lists)

Arrays are perfect for your lists. Under the hood, they are technically just objects, but they use numbered indexes (starting at `0`) instead of named keys.

```javascript
const inventory = ["Flame Sword", "Health Potion", "Shield"];
console.log("Inventory: ", inventory, " | type: ", typeof inventory);
```

#### Functions (Reusable Code)

Yep, in JavaScript, functions are technically a data type (an object) too!

```javascript
function castSpell() {
  return "Fireball";
}
console.log("Spell Type ", typeof castSpell); // Output: "function"
```

### 4\. Value vs. Reference (Listen closely to this one!)

Bro, if there is one thing you take away from this blog, let it be this. This is where 90% of beginners mess up. Pay close attention to how JavaScript copies data.

**Copying Primitives (Pass by Value)** When you copy a primitive (like a Number), JS makes a completely independent, safe clone.

```javascript
let originalHP = 100;
let cloneHP = originalHP;

cloneHP = 80; // Only the clone took damage!

console.log("Original HP: ", originalHP); // 100 (Safe and sound)
console.log("Cloned HP: ", cloneHP);      // 80
```

**Copying Non-Primitives (Pass by Reference)** When you copy an Object or Array, JS **does not copy the data**. It literally just copies the *address* pointing to the original chest.

```javascript
const originalSword = { name: "Flame Sword", damage: 75 };
const cloneSword = originalSword; 

cloneSword.damage = 100; // We upgrade the clone...

// WAIT, WHAT?!
console.log("Original Sword: ", originalSword.damage); // Output: 100
```

Because both variables point to the *exact same object in memory*, changing one secretly changes the other!

![](https://cdn.hashnode.com/uploads/covers/677e148dc0398e29546d0922/1be2fff1-3bf1-4f50-9752-384e0968fe98.png align="center")

#### How to actually clone an Object without breaking things:

1.  **Shallow Copy (The Spread Operator** `...`**):** Perfect for simple objects.
    
    ```javascript
    const armorOriginal = { name: "Iron Plate", defence: 80 };
    const armorCopy = { ...armorOriginal }; 
    ```
    
2.  **Deep Copy (**`structuredClone`**):** Use this if your object has other objects hidden *inside* of it (nested).
    
    ```javascript
    const potionOriginal = { name: "Health", effects: { heal: 40, mana: 30 } };
    const potionCopy = structuredClone(potionOriginal);
    ```
    

### 5\. JavaScript's Weird Historical Quirks

We can use the `typeof` operator to check what's inside a variable. But JS has a few historical bugs that are just too ingrained in the web to fix now. You just have to memorize them and laugh:

```javascript
console.log(typeof "chaicode"); // "string"
console.log(typeof 42);         // "number"
console.log(typeof undefined);  // "undefined"

// 🚨 THE WEIRD ONES 🚨
console.log(typeof null);       // "object" -> (Wait, what? Yep, famous JS bug!)
console.log(typeof []);         // "object" -> (Arrays are technically objects)
```

*Pro-tip: Since* `typeof []` *just tells you it's an "object", the actual right way to check if something is an array is using* `Array.isArray(inventory)`*!*

### What's Next?

Alright, that's enough for today. You now know how to build your storage chests (Variables), what kind of loot to stash inside them (Data Types), and how to avoid that deadly "Pass by Reference" trap.

But right now, our code doesn't really *do* much. In the next post of our **JS Exploration** series, we are going to look at **JavaScript Operators**—how to add, subtract, and compare all this data to make actual things happen.

Catch you in the next one!
