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.
π‘ A variable is a named save slot in memory that can store values, so it can be used later.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
// 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:
-
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.
var playerName = "Caraxes";
console.log(playerName); //Caraxes
//Redeclared
var playerName = "Neoz";
console.log(playerName); //Neoz
π‘
The problem with var is that it can be redeclared without any warning, which makes it easy to accidentally overwrite a value and create bugs which are difficult to spot.
-
let:This keyword is used when the variables are expected to see change overtime.
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
π‘
You can update it freely but you cannot redeclare the same variable in the same scope
-
const:This keyword is used when the variables are not supposed to change.
const maxHealth = 100;
maxHealth = 200; //TypeError: Assignment to constant variable
π‘
Default to const. Only switch to let if you know the value will change. Never use var in your code.
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.
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!
π‘
Backtick strings or template literals lets you embed variables using ${}. Prefer them over string concatenation.
Number
Integers and decimals are number in JavaScript.
let health = 100;
let healthPotion = 1;
let level = 0;
console.log(health-10); // 90
console.log(level + 1); // 1
π‘
Watch out for floating-point quirks: console.log(0.1 + 0.2); results in 0.30000000000000004 as JS uses IEEE 754 standard. use toFixed() to solve this problem or make use of library in case of sensitive data.
Boolean
They have two states: either yes/true or no/false. They are used in logic and consitions.
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
}
π‘
Boolean variables often start with is, has, or can β like isLoggedIn, hasPermission, canUpdate. This makes the intent immediately clear.
Null
It is used to make an intentional empty slot.
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.
let conquest;
console.log(conquest); // undefined
Highlights:
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"
π‘
typeof null returns "object" β this is a bug in JavaScript that was never fixed for backward compatibility reasons.
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.
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
π‘
var was designed before block scope existed. It ignores if, for, and while blocks. This means a var declared inside an if statement is accessible outside it. It is a real source of bugs. let and const were created specifically to fix this.
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.
// 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
constprevents 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.
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
constby default. Switch toletonly if the value needs to change. Avoidvar.The 5 primitive types are:
string,number,boolean,null, andundefined.Scope controls where a variable is accessible.
letandconstare block-scoped;varis not.Use
typeofto inspect what type a variable holds.

Top comments (0)