Variables and Data Types in JavaScript: Your First Step to Writing Real Code

Who is this for? If you are brand new to JavaScript and want to understand what variables are, how to create them, and what kinds of data they can hold — this is the perfect starting point. No prior experience needed.
Table of Contents
Introduction
Every program you will ever write needs to remember things — a user's name, their age, whether they are logged in, how many items are in their cart. Without a way to store and recall information, your code would be useless.
Variables are how your program remembers things.
Once you understand variables and the kinds of data they can hold, you have the foundation for everything else in JavaScript. Let us build that foundation right now.
💡 Open your browser console (
F12→ Console tab) and type along with every example. Reading code is good. Typing it is better.
1. What Are Variables and Why Do We Need Them?
The box analogy
Think of a variable as a labelled box. The box has a name on the outside (the variable name), and you can put a value inside it (the data). Whenever you need that value, you just look up the box by its label.
VARIABLE NAME VARIABLE NAME VARIABLE NAME
│ │ │
▼ ▼ ▼
┌───────────────┐ ┌───────────────┐ ┌───────────────┐
│ │ │ │ │ │
│ name │ │ age │ │ isStudent │
│ │ │ │ │ │
├───────────────┤ ├───────────────┤ ├───────────────┤
│ │ │ │ │ │
│ "Priya" │ │ 21 │ │ true │
│ │ │ │ │ │
└───────────────┘ └───────────────┘ └───────────────┘
▲ ▲ ▲
│ │ │
STORED VALUE STORED VALUE STORED VALUE
(a string) (a number) (a boolean)
Each box stores exactly one value. You can look at what is inside, change what is inside, or use the value to do something.
Why do we need them?
Without variables, you would have to repeat the same values everywhere:
// Without variables — repetitive and fragile
console.log("Hello, Priya!");
console.log("Priya has 5 unread messages.");
console.log("Welcome back, Priya.");
// If the name changes, you update it in three places — and miss one
With a variable, you store the value once and use it everywhere:
// With a variable — change the name in one place, everything updates
const name = "Priya";
console.log("Hello, " + name + "!");
console.log(name + " has 5 unread messages.");
console.log("Welcome back, " + name + ".");
Variables also let your program respond to real input — a form submission, a user clicking a button, data arriving from a server. Without variables, you cannot hold or work with any of it.
2. Declaring Variables: var, let, and const
JavaScript gives you three keywords to create (declare) variables. Each one behaves slightly differently.
let — the modern standard for changeable values
Use let when the value of a variable might change later.
let age = 20;
console.log(age); // 20
age = 21; // updating the value
console.log(age); // 21
const — for values that should never change
Use const when the value is fixed and should not be reassigned.
const country = "India";
console.log(country); // "India"
country = "Nepal"; // ❌ TypeError: Assignment to constant variable.
Once you set a const, it is locked. Trying to change it throws an error — which is actually helpful, because it protects you from accidentally overwriting important values.
var — the old way (still works, but avoid it)
var is the original way to declare variables in JavaScript. It still works, but it has quirky behaviour that causes bugs. Modern JavaScript uses let and const instead.
var city = "Mumbai";
console.log(city); // "Mumbai"
city = "Delhi"; // var allows reassignment
console.log(city); // "Delhi"
You will see var in older code and tutorials, so it is important to recognise it — but write your own code with let and const.
Declaring without a value
You can declare a variable without giving it a value right away. It will hold undefined until you assign something.
let score;
console.log(score); // undefined
score = 95;
console.log(score); // 95
Naming rules for variables
// ✅ Valid variable names
let firstName = "Rahul";
let age2 = 25;
let isLoggedIn = true;
let _count = 0;
let $price = 499;
// ❌ Invalid variable names
let 2fast = true; // cannot start with a number
let my-name = "Ria"; // hyphens not allowed
let let = 5; // cannot use reserved keywords
🔑 Convention: JavaScript developers use camelCase for variable names — the first word lowercase, each following word capitalised:
firstName,totalPrice,isUserLoggedIn.
3. Primitive Data Types
A data type tells JavaScript what kind of value a variable holds. The five most important types for beginners are: string, number, boolean, null, and undefined.
String — text
A string is any sequence of characters wrapped in quotes. Use single quotes '...', double quotes "...", or backticks `...`.
let name = "Priya";
let city = 'Mumbai';
let greeting = `Hello, World!`;
let sentence = "She said, 'I love JavaScript!'";
console.log(name); // Priya
console.log greeting); // Hello, World!
Strings are used for names, messages, email addresses, descriptions — any text.
let email = "priya@example.com";
let message = "Your order has been placed.";
let country = "India";
You can join strings together using +:
let firstName = "Ravi";
let lastName = "Sharma";
let fullName = firstName + " " + lastName;
console.log(fullName); // "Ravi Sharma"
Number — numeric values
Numbers in JavaScript cover both whole numbers (integers) and decimals (floats) — no distinction needed.
let age = 22;
let price = 499.99;
let year = 2025;
let discount = 0.15;
let negative = -10;
console.log(age + 1); // 23
console.log(price * 2); // 999.98
console.log(year - 2000); // 25
Numbers are used for ages, prices, scores, quantities, measurements — anything you calculate with.
Boolean — true or false
A boolean has exactly two possible values: true or false. It represents a yes/no, on/off condition.
let isLoggedIn = true;
let isStudent = false;
let hasDiscount = true;
let isPremium = false;
console.log(isLoggedIn); // true
console.log(isStudent); // false
Booleans are used for conditions — is the user logged in? Has the form been submitted? Is the item in stock?
let isAboveAge = 21 >= 18; // true
let isEven = 7 % 2 === 0; // false
null — intentionally empty
null means a variable exists but has been deliberately set to have no value. It is an intentional blank.
let selectedItem = null; // nothing selected yet
// Later, when the user selects something:
selectedItem = "Laptop";
console.log(selectedItem); // "Laptop"
Think of null as an empty box you placed on the shelf on purpose. You know the box is there — it just does not have anything in it yet.
let profilePicture = null; // user has not uploaded a photo yet
let shippingAddress = null; // address not provided yet
undefined — not yet assigned
undefined means a variable has been declared but no value has been given to it at all. JavaScript sets this automatically.
let score;
console.log(score); // undefined — declared but not assigned
let username = undefined; // you can set it explicitly too, but this is rare
The practical difference from null:
null → you intentionally said "no value here"
undefined → a value was never assigned (usually accidental or temporary)
Checking the type of a value
Use the typeof operator to find out what data type a variable holds:
let name = "Priya";
let age = 22;
let isStudent = true;
let result = null;
let score;
console.log(typeof name); // "string"
console.log(typeof age); // "number"
console.log(typeof isStudent); // "boolean"
console.log(typeof result); // "object" ← a known quirk in JavaScript
console.log(typeof score); // "undefined"
⚠️
typeof nullreturns"object"— this is a long-standing bug in JavaScript that was never fixed to preserve backward compatibility. Just remember:nullis not an object.
Data types at a glance
| Type | Example values | Used for |
|---|---|---|
string |
"Priya", "hello", "42" |
Names, text, messages |
number |
22, 3.14, -100 |
Ages, prices, scores |
boolean |
true, false |
Conditions, flags |
null |
null |
Intentional empty value |
undefined |
undefined |
Unassigned variable |
4. Differences Between var, let, and const
Reassignment
// let — can be reassigned
let score = 80;
score = 95;
console.log(score); // 95 ✓
// const — cannot be reassigned
const maxScore = 100;
maxScore = 110; // ❌ TypeError
// var — can be reassigned (same as let in this regard)
var level = 1;
level = 2;
console.log(level); // 2 ✓
Re-declaration
// var — allows re-declaration (this is a common source of bugs)
var name = "Priya";
var name = "Rahul"; // no error — silently overwrites the first one
console.log(name); // "Rahul"
// let — does NOT allow re-declaration in the same scope
let city = "Mumbai";
let city = "Delhi"; // ❌ SyntaxError: Identifier 'city' has already been declared
// const — does NOT allow re-declaration
const country = "India";
const country = "Nepal"; // ❌ SyntaxError
Re-declaration with var is one of its biggest problems — you can accidentally create a variable with the same name as an existing one, and JavaScript will quietly overwrite it without warning.
Must be initialised
const pi = 3.14; // ✅ must give a value immediately
const gravity; // ❌ SyntaxError: Missing initializer in const declaration
let x; // ✅ let can be declared without a value (gets undefined)
var y; // ✅ var can be declared without a value (gets undefined)
Summary comparison table
| Feature | var |
let |
const |
|---|---|---|---|
| Can be reassigned | ✅ Yes | ✅ Yes | ❌ No |
| Can be re-declared | ✅ Yes | ❌ No | ❌ No |
| Must have initial value | ❌ No | ❌ No | ✅ Yes |
| Scope | Function | Block | Block |
| Modern best practice | ❌ Avoid | ✅ Use | ✅ Use |
🔑 Simple rule for beginners: Use
constby default. Switch toletonly when you know the value will change. Never usevarin new code.
5. What Is Scope?
Scope determines where in your code a variable can be accessed. Think of it as the visibility range of a variable — from where can it be seen and used?
The real-life analogy
Imagine you write something on a whiteboard inside a specific room. People inside that room can read it. People outside the room cannot — even though they know the room exists.
Variables work the same way. A variable declared inside a block {} is only visible inside that block.
Global scope — visible everywhere
A variable declared outside any function or block is in global scope. It can be accessed from anywhere in your program.
let appName = "MyApp"; // global — accessible everywhere
function showName() {
console.log(appName); // ✓ accessible inside a function
}
showName(); // "MyApp"
console.log(appName); // "MyApp" — also accessible outside
Block scope — visible only inside { }
let and const are block-scoped — they only exist inside the {} block where they were declared.
{
let message = "Hello from inside the block!";
console.log(message); // ✓ accessible here
}
console.log(message); // ❌ ReferenceError: message is not defined
The variable message only lives inside the {}. Once you step outside the block, it is gone.
A practical example — inside an if block:
let age = 20;
if (age >= 18) {
let status = "adult"; // block-scoped to this if block
console.log(status); // ✓ "adult"
}
console.log(status); // ❌ ReferenceError: status is not defined
Function scope — var lives inside functions
var is function-scoped — it lives inside the function it was declared in, but it is NOT limited to blocks like if or for. This is one of the reasons var causes bugs.
function greetUser() {
var greeting = "Hello!";
console.log(greeting); // ✓ "Hello!"
}
greetUser();
console.log(greeting); // ❌ ReferenceError: greeting is not defined
// BUT — var leaks out of blocks (unlike let/const):
if (true) {
var leakyVar = "I leaked!"; // declared with var inside a block
}
console.log(leakyVar); // ✓ "I leaked!" — var ignores block boundaries!
The leakyVar example shows exactly why var is problematic. A variable declared inside an if block leaks out into the surrounding scope — that is unexpected behaviour that leads to hard-to-find bugs.
Scope — simple visual summary
Outer scope (global)
┌──────────────────────────────────────────┐
│ let outerVar = "I am global"; │
│ │
│ if (true) { │
│ ┌────────────────────────────────────┐ │
│ │ let innerVar = "I am block only"; │ │
│ │ │ │
│ │ ✓ outerVar is visible here │ │
│ │ ✓ innerVar is visible here │ │
│ └────────────────────────────────────┘ │
│ │
│ ✓ outerVar is visible here │
│ ✗ innerVar is NOT visible here │
└──────────────────────────────────────────┘
Inner scopes can see outer variables. Outer scopes cannot see inner variables.
Diagrams
var, let, and const Comparison Table
┌─────────────────────────────────────────────────────────────┐
│ var vs let vs const — At a Glance │
│ │
│ Feature var let const │
│ ─────────────────── ────────── ────────── ────────── │
│ Reassign value ✅ Yes ✅ Yes ❌ No │
│ Re-declare ✅ Yes ❌ No ❌ No │
│ Initial value needed❌ No ❌ No ✅ Yes │
│ Scope Function Block Block │
│ Leaks out of blocks ✅ Yes ❌ No ❌ No │
│ Use in modern code ❌ Avoid ✅ Yes ✅ Yes │
│ │
│ Quick decision guide: │
│ ────────────────────────────────────────────────────── │
│ Value will never change? → const (const PI = 3.14) │
│ Value will change? → let (let score = 0) │
│ Old/legacy code you read? → var (recognise it, avoid) │
└─────────────────────────────────────────────────────────────┘
Scope Visualisation
┌─────────────────────────────────────────────────────────────┐
│ SCOPE VISUALISATION │
│ │
│ GLOBAL SCOPE │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ const appName = "MyApp"; ← visible everywhere │ │
│ │ let userCount = 0; ← visible everywhere │ │
│ │ │ │
│ │ function greet() { │ │
│ │ ┌─────────────────────────────────────────────────┐ │ │
│ │ │ FUNCTION SCOPE │ │ │
│ │ │ let message = "Hello!"; ← only inside greet() │ │ │
│ │ │ │ │ │
│ │ │ if (true) { │ │ │
│ │ │ ┌───────────────────────────────────────────┐ │ │ │
│ │ │ │ BLOCK SCOPE │ │ │ │
│ │ │ │ let status = "active"; ← only here │ │ │ │
│ │ │ │ ✓ can see: status, message, appName │ │ │ │
│ │ │ └───────────────────────────────────────────┘ │ │ │
│ │ │ │ │ │
│ │ │ ✓ can see: message, appName │ │ │
│ │ │ ✗ cannot see: status (block scope above) │ │ │
│ │ └─────────────────────────────────────────────────┘ │ │
│ │ │ │
│ │ ✓ can see: appName, userCount │ │
│ │ ✗ cannot see: message, status │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
│ Rule: Inner scopes see outer. Outer cannot see inner. │
└─────────────────────────────────────────────────────────────┘
Practice Assignment
Try these exercises in your browser console or in a .js file.
Task 1 — Declare your variables
Declare variables for your name, age, and student status. Then print them all.
const name = "Priya"; // your name will not change
let age = 21; // age can change (birthday!)
let isStudent = true; // might change after graduation
console.log("Name:", name);
console.log("Age:", age);
console.log("Is student:", isStudent);
// Output:
// Name: Priya
// Age: 21
// Is student: true
Task 2 — Update a let variable
Change the value of age and isStudent to see that let allows updates.
let age = 21;
let isStudent = true;
console.log("Before:", age, isStudent); // 21 true
age = 22;
isStudent = false;
console.log("After:", age, isStudent); // 22 false
Task 3 — Try reassigning a const
Observe what happens when you try to change a const.
const name = "Priya";
console.log(name); // "Priya"
name = "Rahul"; // ← type this and run it
// Expected output:
// TypeError: Assignment to constant variable.
This error is JavaScript protecting you. Once a value is declared with const, it cannot be changed — intentionally.
Task 4 — Explore data types with typeof
Declare one variable of each type and check them with typeof.
const userName = "Ananya";
const userAge = 19;
const isPremium = false;
const wishlist = null;
let lastLogin; // not yet assigned
console.log(typeof userName); // "string"
console.log(typeof userAge); // "number"
console.log(typeof isPremium); // "boolean"
console.log(typeof wishlist); // "object" ← the null quirk
console.log(typeof lastLogin); // "undefined"
Bonus — Put it all together
Build a small profile card using all five data types:
const fullName = "Ravi Sharma"; // string
const age = 24; // number
const isVerified = true; // boolean
const profilePic = null; // null — not uploaded yet
let lastActiveAt; // undefined — not yet known
console.log("=== User Profile ===");
console.log("Name:", fullName);
console.log("Age:", age);
console.log("Verified:", isVerified);
console.log("Photo:", profilePic);
console.log("Last active:", lastActiveAt);
// Output:
// === User Profile ===
// Name: Ravi Sharma
// Age: 24
// Verified: true
// Photo: null
// Last active: undefined
Quick Reference
// ─── Variable declaration ─────────────────────────────────
const name = "Priya"; // fixed — cannot change
let score = 0; // flexible — can change
var old = "avoid"; // legacy — avoid in new code
// ─── Updating values ──────────────────────────────────────
score = 95; // ✅ let allows this
name = "Rahul"; // ❌ const does not allow this
// ─── Five primitive data types ────────────────────────────
const str = "Hello"; // string
const num = 42; // number
const bool = true; // boolean
const empty = null; // null
let unset; // undefined
// ─── Check data type ──────────────────────────────────────
typeof "Hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof null // "object" ← quirk, not a real object
typeof undefined // "undefined"
// ─── String joining ───────────────────────────────────────
const greeting = "Hello, " + name + "!"; // "Hello, Priya!"
Wrapping Up
You have just learned one of the most foundational concepts in all of programming. Here is a summary of everything covered:
A variable is a named container that stores a value — like a labelled box
Use
constfor values that never change,letfor values that do, and recognisevarin old code but avoid writing it yourselfJavaScript has five primitive data types:
string(text),number(numeric),boolean(true/false),null(intentionally empty), andundefined(not yet assigned)Scope determines where a variable is visible —
letandconstare block-scoped, meaning they only exist inside the{}where they were declaredInner scopes can see outer variables — outer scopes cannot see inner ones
Every JavaScript concept you learn from here — functions, loops, conditionals, objects, APIs — will use variables. The clearer your understanding of this foundation, the faster everything else will click.
Happy coding! 🚀
Open your console right now and type these examples yourself. Even five minutes of hands-on practice beats an hour of reading.
