JavaScript Data Types Explained: The Complete Beginner's Guide
Every program ever written — from Instagram to your bank's website — is just data being moved around and transformed. A user's name is data. Their age is data. Whether they've checked 'I agree to the terms' is data. JavaScript, the language that powers almost every website you've ever visited, needs a system for organising all this data so it can work with it correctly. That system is called data types, and understanding it is the single most important foundation you can build as a JavaScript developer.
The 7 Primitive Data Types — JavaScript's Building Blocks
JavaScript splits all data into two big families: primitives and objects. Primitives are the simple, indivisible atoms of data — the most basic values you can work with. Think of them like individual Lego bricks, not a finished model. There are seven primitive types in modern JavaScript: String, Number, BigInt, Boolean, Undefined, Null, and Symbol.
A String holds text — anything wrapped in quotes. A Number holds any numeric value (whole or decimal). BigInt handles numbers so astronomically large that a regular Number can't hold them accurately. A Boolean is a coin flip — it's either true or false, nothing in between. Undefined means a variable was created but you never gave it a value — like an empty, unlabelled box. Null means you deliberately set a variable to 'nothing' — like an explicitly empty box with a 'EMPTY' label on it. Symbol is an advanced type used to create unique identifiers, and you won't need it for a while.
You don't need to memorise all of them right now. But you WILL use String, Number, and Boolean every single day, so let's really nail those.
// ── STRINGS ────────────────────────────────────────────── // A string is any text wrapped in quotes (single, double, or backtick) const userName = 'Alice'; // single quotes ✓ const welcomeMessage = "Welcome to TheCodeForge!"; // double quotes ✓ const greeting = `Hello, ${userName}!`; // backtick (template literal) — can embed variables console.log(userName); // Alice console.log(welcomeMessage); // Welcome to TheCodeForge! console.log(greeting); // Hello, Alice! console.log(typeof userName); // 'string' ← typeof tells you the data type // ── NUMBERS ────────────────────────────────────────────── // JavaScript uses ONE Number type for both whole numbers and decimals const userAge = 28; // whole number (integer) const productPrice = 9.99; // decimal number (float) const temperature = -5; // negative numbers work too console.log(userAge); // 28 console.log(productPrice); // 9.99 console.log(typeof userAge); // 'number' // ── BOOLEANS ───────────────────────────────────────────── // A boolean is ONLY ever true or false — no quotes, no capitals const isLoggedIn = true; // the user IS logged in const hasPremiumPlan = false; // the user does NOT have premium console.log(isLoggedIn); // true console.log(typeof isLoggedIn); // 'boolean' // ── UNDEFINED ──────────────────────────────────────────── // A variable declared but never assigned a value is automatically undefined let userNickname; // no value assigned yet console.log(userNickname); // undefined console.log(typeof userNickname); // 'undefined' // ── NULL ───────────────────────────────────────────────── // Null is a VALUE you deliberately assign to mean 'intentionally empty' let selectedProduct = null; // no product chosen yet — on purpose console.log(selectedProduct); // null console.log(typeof selectedProduct); // 'object' ← FAMOUS BUG in JS — see Gotchas section!
Welcome to TheCodeForge!
Hello, Alice!
string
28
9.99
number
true
boolean
undefined
undefined
null
object
The Object Type — When You Need to Group Related Data Together
Primitives are great for a single piece of data. But what happens when you need to describe something more complex — like a user profile, a product in a shop, or a blog post? You need to bundle multiple pieces of data together. That's exactly what Objects do.
An object is like a form. A job application form has fields: 'Name', 'Age', 'Experience'. Each field has a label (called a key) and a value. JavaScript objects work the same way — a collection of key-value pairs, all wrapped in curly braces {}.
Arrays are a special kind of object designed for ordered lists. Instead of named keys, arrays use numbered positions (called indexes, starting at 0). Think of an array like a numbered queue. Position 0 is the front of the line. This is crucial — the first item in an array is ALWAYS at index 0, not 1. Newcomers trip over this constantly.
Objects and arrays can hold ANY type of data inside them — including other objects and arrays. This nesting is how real-world data structures are built, from simple to-do lists all the way up to complex API responses from servers.
// ── OBJECTS ─────────────────────────────────────────────── // An object groups related data under one variable name // Syntax: { key: value, key: value } const userProfile = { firstName: 'Alice', // string value lastName: 'Chen', // string value age: 28, // number value isPremiumMember: true, // boolean value favouriteColor: null // null — she hasn't set this preference yet }; // Access a value using dot notation: objectName.keyName console.log(userProfile.firstName); // Alice console.log(userProfile.age); // 28 console.log(userProfile.isPremiumMember); // true // You can also use bracket notation — useful when the key is dynamic console.log(userProfile['lastName']); // Chen console.log(typeof userProfile); // 'object' // ── ARRAYS ──────────────────────────────────────────────── // An array is an ordered list of values, wrapped in square brackets [] // Each item has an index — STARTING AT 0, not 1! const shoppingCart = ['Apple', 'Banana', 'Mango', 'Blueberries']; // indexes: 0 1 2 3 console.log(shoppingCart[0]); // Apple ← index 0 is the FIRST item console.log(shoppingCart[2]); // Mango ← index 2 is the THIRD item console.log(shoppingCart.length); // 4 ← .length tells you how many items console.log(typeof shoppingCart); // 'object' ← arrays ARE objects in JS // ── REAL-WORLD COMBO: Object containing an Array ────────── // This is the kind of data you'll receive from a real API const blogPost = { title: 'JavaScript Data Types Explained', author: 'Alice Chen', publishedAt: '2024-01-15', tags: ['javascript', 'beginners', 'web-dev'], // array nested inside object isPublished: true }; console.log(blogPost.title); // JavaScript Data Types Explained console.log(blogPost.tags[0]); // javascript ← dot notation + array index combined console.log(blogPost.tags.length);// 3
28
true
Chen
object
Apple
Mango
4
object
JavaScript Data Types Explained
javascript
3
Static Typing vs Dynamic Typing — Why JavaScript Is Both Flexible and Dangerous
Here's something that makes JavaScript fundamentally different from languages like Java or C++: JavaScript is dynamically typed. That means you don't declare what type a variable will hold — JavaScript figures it out automatically at runtime based on the value you assign.
In Java you'd write: int userAge = 28; — you're locking that variable to hold only integers, forever. In JavaScript, you just write: let userAge = 28; — and JavaScript quietly labels it a Number behind the scenes. If you then reassign userAge = 'twenty-eight', JavaScript shrugs and changes the type to String. No error. No warning.
This flexibility is incredibly convenient when you're learning. But it also means JavaScript won't stop you from doing something accidentally incorrect — like adding a number to a text string. When you do that, JavaScript tries to be 'helpful' by converting one type to match the other. This process is called type coercion, and it's the source of some of JavaScript's most infamous and confusing behaviours.
Understanding that JavaScript silently changes types behind your back is one of the most important mental models you can build early on. It explains why so many bugs that look impossible actually happen.
// ── DYNAMIC TYPING ──────────────────────────────────────── // JavaScript lets you reassign a variable to a completely different type. // This is unlike Java, C++, or C# which would throw a compile error. let score = 100; // score is a Number console.log(typeof score); // 'number' score = 'One Hundred'; // reassigned to a String — JavaScript allows this console.log(typeof score); // 'string' ← the type changed! // ── TYPE COERCION — JavaScript's 'helpful' auto-converting ─── // When you mix types, JS tries to convert them automatically. // Sometimes this is useful. Often it creates baffling bugs. // Example 1: Number + String = String (JS converts the number to text) const itemsInCart = 3; const message = 'You have ' + itemsInCart + ' items'; console.log(message); // 'You have 3 items' ← works as intended here console.log(typeof message); // 'string' // Example 2: Unintended coercion — a classic beginner bug const quantityFromInput = '5'; // user typed '5' — it came back as a STRING const taxRate = 0.1; const totalTax = quantityFromInput * taxRate; // * forces number conversion console.log(totalTax); // 0.5 ← multiplication happened to work const wrongTotal = quantityFromInput + 10; // + with a string = concatenation! console.log(wrongTotal); // '510' ← NOT 15! JS joined the strings instead! // THE FIX: Always convert user input to a number explicitly const correctQuantity = Number(quantityFromInput); // convert FIRST const correctTotal = correctQuantity + 10; console.log(correctTotal); // 15 ← now it's correct arithmetic // ── EXPLICIT TYPE CONVERSION ────────────────────────────── // Don't rely on coercion — convert deliberately const priceAsString = '29.99'; const priceAsNumber = Number(priceAsString); // String → Number console.log(priceAsNumber + 5); // 34.99 ✓ const stockCount = 42; const stockAsString = String(stockCount); // Number → String console.log('Stock level: ' + stockAsString); // 'Stock level: 42' const isActive = Boolean(1); // Number → Boolean (0 = false, anything else = true) console.log(isActive); // true
string
You have 3 items
string
0.5
510
15
34.99
Stock level: 42
true
Common Mistakes Beginners Make With JavaScript Data Types
Knowing the types exist isn't enough — you need to know where the traps are. These mistakes aren't signs of being a bad developer. They're universal rites of passage. Every senior developer you've ever admired has hit every single one of these. The difference is knowing how to spot them and fix them fast.
The first trap is assuming typeof null returns 'null'. It doesn't — it returns 'object'. This is a bug in JavaScript that's been present since 1995 and can never be fixed because too much existing code depends on it behaving this way. The fix is to explicitly check: value === null.
The second trap is treating NaN like a regular number. NaN stands for 'Not a Number' — it appears when you try to do maths with something that isn't numeric, like Number('hello'). The brutal irony is that typeof NaN returns 'number'. And NaN === NaN is false — NaN is the only value in JavaScript that is not equal to itself. Use Number.isNaN() to check for it safely.
The third trap is confusing null and undefined. Both mean 'no value' but in completely different contexts. Undefined happens automatically; null is intentional. Mixing them up leads to logical errors that are hard to track down.
// ── MISTAKE 1: typeof null returns 'object', not 'null' ── const selectedItem = null; // ❌ WRONG WAY — this doesn't work as expected if (typeof selectedItem === 'null') { console.log('Nothing selected'); // this NEVER runs — typeof null is 'object' } // ✅ RIGHT WAY — use strict equality to check for null if (selectedItem === null) { console.log('Nothing selected'); // this runs correctly } // ── MISTAKE 2: Mishandling NaN ──────────────────────────── const userInput = 'forty-two'; // user typed text instead of a number const parsedValue = Number(userInput); // can't convert text → NaN console.log(parsedValue); // NaN console.log(typeof parsedValue); // 'number' ← NaN is ironically typed as number! // ❌ WRONG WAY — NaN is never equal to anything, even itself if (parsedValue === NaN) { console.log('Invalid number'); // NEVER runs — NaN !== NaN } // ✅ RIGHT WAY — use Number.isNaN() if (Number.isNaN(parsedValue)) { console.log('Invalid number — please enter digits only'); // runs correctly } // ── MISTAKE 3: Confusing null and undefined ─────────────── // undefined = variable exists but was never given a value let deliveryAddress; // forgot to assign it console.log(deliveryAddress); // undefined ← JS set this automatically // null = deliberately set to empty let discountCode = null; // user hasn't entered a code yet — intentional console.log(discountCode); // null ← YOU set this on purpose // ❌ WRONG — treating them interchangeably causes subtle logic bugs if (deliveryAddress == null) { // == (loose equality) treats both null AND undefined as 'nullish' // so this catches BOTH — sometimes not what you want console.log('Catches both null and undefined'); } // ✅ RIGHT — use === to distinguish them precisely if (deliveryAddress === undefined) { console.log('Address was never set — bug in our code?'); } if (discountCode === null) { console.log('No discount code entered — that is fine'); }
NaN
number
Invalid number — please enter digits only
undefined
null
Catches both null and undefined
Address was never set — bug in our code?
No discount code entered — that is fine
| Type | Example Value | typeof Result | When You'd Use It |
|---|---|---|---|
| String | 'Hello, Alice' | string | Any text: names, messages, URLs |
| Number | 42 or 3.14 | number | Maths, ages, prices, quantities |
| BigInt | 9007199254740993n | bigint | Extremely large integers (finance, crypto) |
| Boolean | true or false | boolean | Flags, toggles, conditions (isLoggedIn, hasAccess) |
| Undefined | undefined | undefined | Variable declared but not yet assigned — often a bug signal |
| Null | null | object ← BUG! | Intentional empty value — deliberately set by you |
| Symbol | Symbol('id') | symbol | Unique object keys (advanced — rarely needed early on) |
| Object | { name: 'Alice' } | object | Grouping related data together |
| Array | ['a', 'b', 'c'] | object | Ordered lists of items |
🎯 Key Takeaways
- JavaScript has 7 primitive types (String, Number, BigInt, Boolean, Undefined, Null, Symbol) and one complex type (Object — which includes arrays and functions)
- JavaScript is dynamically typed — variables don't have fixed types and can be reassigned to a completely different type at any time, which is both its superpower and its biggest trap
- typeof null returns 'object' — this is a 30-year-old bug in the language that will never be fixed; always use === null to check for null values explicitly
- The + operator does two completely different things: it concatenates strings AND adds numbers — always convert user input with Number() before doing arithmetic to avoid silent string-joining bugs
⚠ Common Mistakes to Avoid
- ✕Mistake 1: Using typeof to check for null — typeof null returns 'object' (not 'null'), so typeof myVar === 'null' will always be false and your null-check silently never runs — Fix: always use strict equality: myVar === null
- ✕Mistake 2: Adding a string and a number with + expecting arithmetic — '5' + 10 produces '510' (string concatenation) instead of 15 because + converts the number to a string when one operand is already a string — Fix: convert first with Number(): Number('5') + 10 === 15
- ✕Mistake 3: Comparing NaN with === expecting it to match — NaN === NaN is always false because NaN is the only value not equal to itself — Fix: use Number.isNaN(value) which is the only reliable way to detect a NaN value
Interview Questions on This Topic
- QWhat is the difference between null and undefined in JavaScript — can you give a real example of when you'd use each one deliberately?
- QWhat does typeof null return, and why? Is this a bug or a feature?
- QIf I run '5' + 3 in JavaScript I get '53', but '5' - 3 gives me 2. Why does JavaScript behave differently for + versus - with mixed types?
Frequently Asked Questions
How many data types does JavaScript have?
JavaScript has 8 data types in total: 7 primitives (String, Number, BigInt, Boolean, Undefined, Null, Symbol) and one complex type called Object. Arrays and functions are technically subtypes of Object — which is why typeof [] and typeof function(){} both return 'object' and 'function' respectively.
What is the difference between null and undefined in JavaScript?
Undefined means a variable was declared but never assigned a value — JavaScript sets it automatically. Null means a variable was deliberately set to represent 'no value' — YOU set it on purpose. Use undefined as a signal that something hasn't been initialised yet, and null to explicitly clear a value you previously held.
Why does typeof null return 'object' instead of 'null'?
This is a well-known bug that has existed in JavaScript since its creation in 1995. In the original implementation, values were stored with type tags, and the null pointer happened to share the same type tag as objects. By the time it was identified as a bug, too much existing code on the internet relied on this behaviour, so fixing it would have broken the web. It's never been corrected — use value === null to check for null reliably.
Written and reviewed by senior developers with real-world experience across enterprise, startup and open-source projects. Every article on TheCodeForge is written to be clear, accurate and genuinely useful — not just SEO filler.