javascript

Primitive Data Types

Learn JavaScript's fundamental building blocks: primitive data types. Understand numbers, strings, booleans, null, undefined, symbol, and bigint with simple examples.

10 min read 8 sections Tutorial
Share

In JavaScript, data types tell us what kind of value a variable holds. Think of them as categories for information. This tutorial will teach you about **primitive data types**, which are the most basic kinds of values you can use. You will learn what each primitive type is, how to use it, and why they are important for building any JavaScript program.

Primitive Data Types

Primitive Data Types

In JavaScript, data types tell us what kind of value a variable holds. Think of them as categories for information. This tutorial will teach you about primitive data types, which are the most basic kinds of values you can use. You will learn what each primitive type is, how to use it, and why they are important for building any JavaScript program.

What are Primitive Data Types?

Primitive data types are the most fundamental and basic kinds of values in JavaScript that are immutable, meaning their value cannot be changed after they are created.

Basic Building Blocks

Primitives are the simplest forms of data, like single pieces of information that make up bigger structures.

Immutable Values

Once a primitive value is created, it cannot be changed; you can only replace it with a new value.

Seven Core Types

JavaScript has seven primitive types: string, number, boolean, null, undefined, symbol, and bigint.

Passed by Value

When you copy a primitive, the actual value is copied, not just a reference to it.

What Are Primitive Data Types?

Getting Started

What Are Primitive Data Types?

Primitive data types are like the basic atoms of data in JavaScript. They represent single values. There are seven primitive types: string, number, boolean, null, undefined, symbol, and bigint. Each one helps you store a different kind of simple information.

javascript
1// A string holds text
2let userName = "Alice";
3
4// A number holds whole numbers or decimals
5let userAge = 30;
6let productPrice = 19.99;
7
8// A boolean holds true or false values
9let isLoggedIn = true;
10let hasPermission = false;
11
12// null means 'no value' or 'empty value'
13let selectedItem = null;
14
15// undefined means a variable has been declared but not given a value yet
16let favoriteColor; // This variable is undefined
17
18// Symbol creates a unique identifier (often used for object properties)
19const uniqueId = Symbol('id');
20
21// BigInt handles very large numbers that 'number' cannot
22const largeNumber = 1234567890123456789012345678901234567890n; // 'n' at the end makes it a BigInt

A Common Beginner Confusion: typeof null

When you use the typeof operator on null, it returns 'object'. This is a long-standing bug in JavaScript and not actually true. null is a primitive value, not an object.

Understanding Immutability

Understanding Immutability

The word 'immutable' means 'cannot be changed'. This is a very important rule for primitive data types. When you create a string or a number, its value is fixed. If you try to change it, JavaScript actually creates a brand new primitive value instead. This is different from how 'objects' work, which you will learn about later.

javascript
1let message = "Hello"; // 'message' now holds the string value "Hello"
2
3// We try to change the string by making it uppercase
4message.toUpperCase(); // This operation creates a NEW string "HELLO", but doesn't change 'message'
5
6console.log(message); // Output: "Hello" (the original value remains the same)
7
8// To actually 'change' the variable, you must assign a new value to it
9message = message.toUpperCase(); // Now, 'message' holds the NEW string "HELLO"
10
11console.log(message); // Output: "HELLO"
12
13let score = 100;
14score = score + 50; // This doesn't change '100'; it creates a NEW number '150' and assigns it to 'score'
15console.log(score); // Output: 150
✗ BadWrong (Misunderstanding Immutability)
let greeting = "Hi";
greeting[0] = 'h'; // This will NOT change the string
console.log(greeting); // Output: "Hi" (strings are immutable)
✓ GoodCorrect (Reassigning a New Value)
let greeting = "Hi";
greeting = 'h' + greeting.substring(1); // Create a new string and assign it
console.log(greeting); // Output: "hi"
// Or, if you want to change the whole value:
greeting = "Hello"; // This replaces the old string with a new one
console.log(greeting); // Output: "Hello"

Null vs. Undefined

Different Primitive Types

While all primitive types are simple, some have very specific meanings. Two common primitives that often confuse beginners are null and undefined. They both mean 'no value', but they are used in slightly different situations. Understanding their difference is key to writing clear and correct code.

Undefined (System-assigned)
let firstName; // Variable declared but not assigned a value
console.log(firstName); // Output: undefined
// If a function doesn't return anything, it implicitly returns undefined
function doNothing() {
// No return statement
}
console.log(doNothing()); // Output: undefined
// Accessing a property that doesn't exist on an object
const user = {};
console.log(user.age); // Output: undefined
VS
Null (Programmer-assigned)
let lastName = null; // Variable explicitly assigned 'no value'
console.log(lastName); // Output: null
// You might set a variable to null to clear its value later
let currentSelection = "item1";
// ... later, clear the selection ...
currentSelection = null;
console.log(currentSelection); // Output: null
// Often used to represent an intentionally absent value

When to Use Null vs. Undefined

Use undefined when a variable has not been given a value yet. JavaScript often sets this automatically. Use null when you, the programmer, want to intentionally say 'this variable should have no value here'. It's like an empty box that you deliberately put nothing into.

Using Primitives in Your Code

Using Primitives in Your Code

Primitive data types are everywhere in JavaScript. You use them for almost every task. From storing simple facts like a user's name to making decisions based on true or false values, primitives are fundamental. Here's how you might use them in a small program.

1

Store User Information

First, we can store basic user details using string and number types. These are simple pieces of data that describe a user.

javascript
1let userName = "CodingKid"; // A string for the user's name
2let userScore = 1500; // A number for their game score
2

Check User Status

Next, we use a boolean to keep track of whether the user is logged in. This helps our program make decisions.

javascript
1let isLoggedIn = true; // A boolean to show if the user is logged in
2
3if (isLoggedIn) {
4 console.log("Welcome back, " + userName + "!");
5}
3

Handle Missing Data

Sometimes, a piece of information might not exist yet. We can use null or undefined to represent this. Here, userPreference is intentionally set to null if no preference is chosen.

javascript
1let userPreference = null; // No preference selected yet (intentionally empty)
2
3// Later, maybe the user sets a preference
4userPreference = "dark-mode";
5
6if (userPreference !== null) {
7 console.log("User preference: " + userPreference);
8} else {
9 console.log("No preference set.");
10}
4

Perform Calculations

Numbers are used for math! You can add, subtract, multiply, and divide them easily. This is how you update scores or calculate prices.

javascript
1let itemPrice = 25.50;
2let quantity = 3;
3let totalPrice = itemPrice * quantity; // Multiply numbers to get total
4console.log("Total price: $" + totalPrice);

Beware of Type Coercion and NaN

JavaScript sometimes tries to guess what you mean when you mix different types, which is called 'type coercion'. This can lead to unexpected results, like trying to do math with a string that isn't a number. If you try to perform a mathematical operation that doesn't make sense, JavaScript might give you NaN (Not a Number), which is a special number primitive indicating an invalid numerical result. For example, 10 / "hello" would result in NaN.

Primitive Data Types Overview

Primitive Data Types Overview

TypeDescriptionExample`typeof` Result
StringTextual data, enclosed in quotes.`"Hello World"``"string"`
NumberIntegers or floating-point numbers.`42`, `3.14``"number"`
BooleanRepresents truth values: `true` or `false`.`true`, `false``"boolean"`
NullAn intentional absence of any object value.`null``"object"` (historical bug)
UndefinedA variable that has been declared but not yet assigned a value.`let x;``"undefined"`
SymbolA unique and immutable value, often used as object property keys.`Symbol('id')``"symbol"`
BigIntIntegers with arbitrary precision (can store very large numbers).`100n``"bigint"`

Test Your Knowledge

Test Your Knowledge

Test Your Knowledge

Quick Check

Which of the following is NOT a primitive data type in JavaScript?

Quick Check

What does 'immutability' mean for primitive data types?

Quick Check

What will console.log(typeof null) output?

Quick Check

When is undefined typically used?

Quick Reference

Quick Reference

Quick Reference

Pro Tips
  • 1Primitive Data Types — These are the most basic and fundamental types of data in JavaScript.
  • 2Immutability — Primitive values cannot be changed after they are created; any apparent change results in a new value.
  • 3String — Used for text, enclosed in single (') or double (") quotes, e.g., let name = "John";
  • 4Number — Used for both whole numbers and decimals, e.g., let age = 25;, let price = 9.99;
  • 5Boolean — Represents truth values, either true or false, crucial for conditional logic.
  • 6Null — Represents an intentional absence of any object value, explicitly set by a programmer.
  • 7Undefined — Indicates that a variable has been declared but has not yet been assigned a value by the system.
  • 8Symbol — Creates a unique identifier, guaranteeing no conflicts, often used for object property keys.
  • 9BigInt — Handles extremely large integers beyond the safe limit of the regular number type.
  • 10typeof Operator — Use typeof to check the data type of a variable or value, e.g., typeof 10 returns "number".

Non-Primitive Data Types

Explore objects and arrays, which are mutable and can hold collections of data.

Type Coercion

Understand how JavaScript automatically converts data types and how to handle it safely.

Operators in JavaScript

Learn about arithmetic, comparison, and logical operators that work with data types.

Variables and Constants

Deepen your knowledge of let, const, and var for declaring variables that hold these data types.

Congratulations!

You've successfully learned about primitive data types in JavaScript! You now understand the basic building blocks of data, their immutability, and how to use string, number, boolean, null, undefined, symbol, and bigint. This knowledge is fundamental to writing any JavaScript code.

Try it in the Javascript Compiler

Run and experiment with Javascript code right in your browser — no setup needed.

Continue Learning