# Understanding JavaScript Variables and Data Types Through Game Design

Whenever you start learning a programming language, be it Python, Java, C++, or JavaScript, one concept is common to all of them: **variables** and **data types**. Variables and Data Types are the building blocks of a programming language. Variables solve a simple yet important problem: the memory. When a user types their name into a login form, your code needs to hold onto that name long enough to display it, validate it, or send it to a server. When a game tracks your score, it stores that number somewhere so it can update it every time you earn points. Without variables, every piece of data would vanish the moment it appeared. Your program would have no memory, no state, and no way to make decisions based on what happened before.  
But storing data is only half the story. A program also needs to understand what kind of data it is working with. This is where data types come in. Imagine storing the value 50. Is it a number representing age? A score in a game? Or is it the string "50" typed by a user in a form? The program needs to know this difference because it determines what operations can be performed on that value. Numbers can be added, divided, or compared mathematically, while strings are treated as text that can be concatenated, sliced, or formatted. Data types give meaning and structure to the values stored in variables.

Let's explore the two with the concept of games.

## Variables: The Save File

Imagine playing an RPG with no save files. Whenever you launch the game, your character is gone, the item in your bag disappears, your world resets. The world has no idea who you are in every single run.

That would be unbearable, exactly what code would be like without variables.

A **variable** is JavaScript's save file. It's a named space in memory where your program stores a piece of information and can look it up later by that name.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">A variable is a named save slot in memory that can store values, so it can be used later.</div>
</div>

Hence, every RPG has a save file, where the game save your progress, the character name, the inventory, current HP, upgrades, map, level, character progression. Later when you load your save file, you start from where you left off.

**Variable Mapping of Save File**

| fileName | Store | JS Syntax | Data Type |
| --- | --- | --- | --- |
| playerName | Caraxes | let playerName = 'Caraxes' | String |
| health | 70 | let health = 70 | Number |
| BOSS\_LEVEL | 14 | const BOSS\_LEVEL = 14 | Number |
| swordAcquired | false | let swordAcquired = false | Boolean |

In JavaScript code

```javascript
// Creating save file for a game character
let playerName = "Caraxes";        // slot: name
let health = 100;                 // slot: current HP
let bossLevel = 0;               // slot: starts at 0
let swordAcquired = false;
const BOSS_LEVEL  = 99;         // locked: Number of Boss remains same

// Reading from save slots
console.log(playerName);        // "Caraxes"
console.log(health);           // 100

// The game progresses update the slots
health = 70;                 // player took damage
bossLevel  = 3;              // progression on map
swordAcquired = true;         // sword found

console.log(health);          // 70
console.log(bossLevel);       // 3
console.log(swordAcquired)     // true
```

## Declaring Variables: var, let and const

In games, not all save slots work the same way. Some hold your main campaign state, updated regularly. Some are locked achievement records you can only read, never modify.

JavaScript offers **three keywords** through which variables can be declared:

1.  `var:` The original way to declare variables which is now deprecated. It can be redeclared and has no scope. It introduces a lot of bugs to the code by not following the modern rules and concepts introduced to JavaScript.
    

```javascript
var playerName = "Caraxes";
console.log(playerName);            //Caraxes

//Redeclared
var playerName = "Neoz";
console.log(playerName);            //Neoz
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The problem with <code>var</code> is that it can be <strong>redeclared</strong> without any warning, which makes it easy to accidentally overwrite a value and create bugs which are difficult to spot.</div>
</div>

1.  `let:` This keyword is used when the variables are expected to see change overtime.
    

```javascript
let health = 60;
let healthPotion = 20;
console.log(health);        // 60

// update value
health = health + healthPotion;
console.log(health);       // 80

let health = 100;         // SyntaxError:'health' has already been declared
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">You can update it freely but you cannot <em>redeclare</em> the same variable in the same scope</div>
</div>

1.  `const:` This keyword is used when the variables are not supposed to change.
    

```javascript
const maxHealth = 100;

maxHealth = 200;         //TypeError: Assignment to constant variable
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Default to <code>const</code>. Only switch to <code>let</code> if you know the value will change. Never use <code>var</code> in your code.</div>
</div>

`var` vs `let` vs `const`

| Feature | `var` | `let` | `const` |
| --- | --- | --- | --- |
| Redeclared | Yes | No | No |
| Reassigned | Yes | Yes | No |
| Scope | Function | Block | Block |
| Hoisted | Yes, as `undefined` | Yes but not initialized | Yes, but not initialized |
| Use | Avoid | Yes | Yes, preferred |

## Primitive Data Types: What Goes In The Slot?

A save file aka variable stores value, and every value has a **type**. Some slots hold text (a character name), some hold numbers (HP), some hold a simple yes/no flag (does the character have a sword?). In JavaScript, the type of the value determines what it is, how it would behave and what operations can be performed.

There are *five* primitive data types:

### String

Any text placed between quotes, which can be single, double or backticks are treated as string type.

```javascript
let firstName = "Caraxes";
let greeting = 'Hello';
let message = `Welcome to Neverland, ${firstName}!`; // Template literal

console.log(firstName); // Caraxes
console.log(greeting);  // Hello
console.log(message);   // Welcome to Neverland, Caraxes!
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Backtick strings or template literals lets you embed variables using <code>${}</code>. Prefer them over string concatenation.</div>
</div>

### Number

Integers and decimals are `number` in JavaScript.

```javascript
let health = 100;                 
let healthPotion = 1;              
let level = 0; 

console.log(health-10);    // 90
console.log(level + 1);    // 1
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Watch out for floating-point quirks: <code>console.log(0.1 + 0.2);</code> results in <code>0.30000000000000004</code> as JS uses <strong>IEEE 754</strong> standard. use <code>toFixed()</code> to solve this problem or make use of library in case of sensitive data.</div>
</div>

### Boolean

They have two states: either yes/true or no/false. They are used in logic and consitions.

```javascript
let isAlive = true;
let hasArmour = false;

console.log(isAlive);  // true
console.log(hasArmour);  // false

if (!hasArmour) {
  console.log("You are vulnerable in Boss fight"); // You are vulnerable in Boss fight
}
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Boolean variables often start with <code>is</code>, <code>has</code>, or <code>can</code> — like <code>isLoggedIn</code>, <code>hasPermission</code>, <code>canUpdate</code>. This makes the intent immediately clear.</div>
</div>

### Null

It is used to make an intentional empty slot.

```javascript
let weaponEquipped = null;
console.log(weaponEquipped); // null
```

### Undefined

When a variable or slot exist but a value is not stored in that slot. JavaScript does it automatically when you declare a variable without assigning a value.

```javascript
let conquest;
console.log(conquest); // undefined
```

Highlights:

```javascript
let playerName  = "Caraxes";   // String. Text in quotes
let health      = 100;        // Number. No quotes
let hasShield   = true;      // Boolean. true or false
let equippedGun = null;      // Null. Empty on purpose
let questReward;             // Undefined. Slot exists, nothing saved yet

// typeof reveals the type stored in each slot
console.log(typeof playerName);   // "string"
console.log(typeof health);        // "number"
console.log(typeof hasShield);     // "boolean"
console.log(typeof equippedGun);   // "object"  JS bug
console.log(typeof questReward);   // "undefined"
```

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><code>typeof null</code> returns <code>"object"</code> — this is a <a target="_self" rel="noopener noreferrer nofollow" class="text-primary underline underline-offset-2 hover:text-primary/80 cursor-pointer" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null" style="pointer-events: none;">bug in JavaScript</a> that was never fixed for backward compatibility reasons.</div>
</div>

```javascript
let weapon = null;
console.log(typeof weapon);      // "object" which is confusing
console.log(weapon === null);   // true. use this instead
```

## Scope: Who can access which slot?

Some game data is global. Your player name shows in every menu, every screen. Other data only exists during a specific fight, a boss's HP bar lives only for that encounter. When you leave the arena, it's gone.

That's **scope**. It determines where in your code a variable is accessible. `let` and `const` are block-scoped, they live only inside the `{ }` where they were created. `var` ignores blocks and leaks out, which is exactly the problem.

### Global Scope

A variable declared outside any function or block is **global**. It can be accessed anywhere in your code.

### Block Scope

Variables declared with `let` or `const` inside curly braces `{ }` only exist *within* those braces.

```javascript
const GAME_TITLE = "Dark Soul";    // Global scope but cant be changed
let playerName = "Caraxes";        // Global scope but can be changed

if (true) {                        // entering the boss arena
  let bossHealth = 7100;         // block-scoped: stays here
  const bossName   = "Nameless King"; // block-scoped: stays here
  var narrator     = "You can't trap me"; // leaks out!
} 

console.log(playerName);  // "Caraxes" 
console.log(narrator);    // "You can't trap me" | var leaked out
console.log(bossHealth);  // ReferenceError: bossHealth is not defined
console.log(bossName);    // ReferenceError: bossName is not defined
```

![](https://cdn.hashnode.com/uploads/covers/678b775e773554ab7117f20a/17fa4489-e179-4608-b741-a5ba357491c3.png align="center")

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><code>var</code> was designed before block scope existed. It ignores <code>if</code>, <code>for</code>, and <code>while</code> blocks. This means a <code>var</code> declared inside an <code>if</code> statement is accessible outside it. It is a real source of bugs. <code>let</code> and <code>const</code> were created specifically to fix this.</div>
</div>

## JavaScript Glitches

Every game ships with a few unintended bugs. JavaScript is no different, it had certain behaviour in its early days. As the language evolved, new features were introduced to help in fixing those issues, but the older issues cannot be patched because as too much of the web depends on them.

*   **"5" + 3 equals "53", not 8**  
    The `+` operator does two different things: math addition and string joining. If either side is a string, JS concatenates instead of adding. This surprises almost every beginner, especially when user input (from forms, URLs, etc.) arrives as a string that looks like a number.
    

```javascript
// Bonus points come in from a form, they're a STRING
let bonus = "100";    // looks like a number, has quotes = string
let score  = 50;

console.log(score + bonus);           // "50100" | string concat
console.log(score + Number(bonus));   // 150 | explicit conversion
console.log(score + +bonus);         // 150 | unary + shorthand
```

*   **const doesn't lock object contents**  
    `const` prevents *reassigning the slot*, but if the slot holds an object, the object's properties can still change. Think of it as locking the locker door, not what's stored inside it.
    

```javascript
const player = { name: "Neoz", health: 100 };

player.health = 80;     // changing a property is allowed
console.log(player);    // { name: "Neoz", health: 80 }

player = {};             // TypeError | can't swap the whole object
```

### Save File

*   A **variable** stores a named value in memory.
    
*   Use `const` by default. Switch to `let` only if the value needs to change. Avoid `var`.
    
*   The 5 primitive types are: `string`, `number`, `boolean`, `null`, and `undefined`.
    
*   **Scope** controls where a variable is accessible. `let` and `const` are block-scoped; `var` is not.
    
*   Use `typeof` to inspect what type a variable holds.
    

### Continue Your Quest

*   [MDN : Variables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#declarations)
    
*   [javascript.info](http://javascript.info)[: Variables](https://javascript.info/variables)
    
*   [MDN: JavaScript Data Types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)
    
*   [javascript.info](http://javascript.info)[: Data Types](https://javascript.info/types)
    
*   [MDN: typeof operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
    
*   [MDN: var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)
    
*   [MDN: let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)
    
*   [MDN: const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)
