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?
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.
1// A string holds text2let userName = "Alice";34// A number holds whole numbers or decimals5let userAge = 30;6let productPrice = 19.99;78// A boolean holds true or false values9let isLoggedIn = true;10let hasPermission = false;1112// null means 'no value' or 'empty value'13let selectedItem = null;1415// undefined means a variable has been declared but not given a value yet16let favoriteColor; // This variable is undefined1718// Symbol creates a unique identifier (often used for object properties)19const uniqueId = Symbol('id');2021// BigInt handles very large numbers that 'number' cannot22const 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.
1let message = "Hello"; // 'message' now holds the string value "Hello"23// We try to change the string by making it uppercase4message.toUpperCase(); // This operation creates a NEW string "HELLO", but doesn't change 'message'56console.log(message); // Output: "Hello" (the original value remains the same)78// To actually 'change' the variable, you must assign a new value to it9message = message.toUpperCase(); // Now, 'message' holds the NEW string "HELLO"1011console.log(message); // Output: "HELLO"1213let 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
let greeting = "Hi";greeting[0] = 'h'; // This will NOT change the stringconsole.log(greeting); // Output: "Hi" (strings are immutable)
let greeting = "Hi";greeting = 'h' + greeting.substring(1); // Create a new string and assign itconsole.log(greeting); // Output: "hi"// Or, if you want to change the whole value:greeting = "Hello"; // This replaces the old string with a new oneconsole.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.
let firstName; // Variable declared but not assigned a valueconsole.log(firstName); // Output: undefined// If a function doesn't return anything, it implicitly returns undefinedfunction doNothing() {// No return statement}console.log(doNothing()); // Output: undefined// Accessing a property that doesn't exist on an objectconst user = {};console.log(user.age); // Output: undefined
let lastName = null; // Variable explicitly assigned 'no value'console.log(lastName); // Output: null// You might set a variable to null to clear its value laterlet currentSelection = "item1";// ... later, clear the selection ...currentSelection = null;console.log(currentSelection); // Output: null// Often used to represent an intentionally absent value
let firstName; // Variable declared but not assigned a valueconsole.log(firstName); // Output: undefined// If a function doesn't return anything, it implicitly returns undefinedfunction doNothing() {// No return statement}console.log(doNothing()); // Output: undefined// Accessing a property that doesn't exist on an objectconst user = {};console.log(user.age); // Output: undefined
let lastName = null; // Variable explicitly assigned 'no value'console.log(lastName); // Output: null// You might set a variable to null to clear its value laterlet 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.
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.
1let userName = "CodingKid"; // A string for the user's name2let userScore = 1500; // A number for their game score
Check User Status
Next, we use a boolean to keep track of whether the user is logged in. This helps our program make decisions.
1let isLoggedIn = true; // A boolean to show if the user is logged in23if (isLoggedIn) {4 console.log("Welcome back, " + userName + "!");5}
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.
1let userPreference = null; // No preference selected yet (intentionally empty)23// Later, maybe the user sets a preference4userPreference = "dark-mode";56if (userPreference !== null) {7 console.log("User preference: " + userPreference);8} else {9 console.log("No preference set.");10}
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.
1let itemPrice = 25.50;2let quantity = 3;3let totalPrice = itemPrice * quantity; // Multiply numbers to get total4console.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
| Type | Description | Example | `typeof` Result |
|---|---|---|---|
| String | Textual data, enclosed in quotes. | `"Hello World"` | `"string"` |
| Number | Integers or floating-point numbers. | `42`, `3.14` | `"number"` |
| Boolean | Represents truth values: `true` or `false`. | `true`, `false` | `"boolean"` |
| Null | An intentional absence of any object value. | `null` | `"object"` (historical bug) |
| Undefined | A variable that has been declared but not yet assigned a value. | `let x;` | `"undefined"` |
| Symbol | A unique and immutable value, often used as object property keys. | `Symbol('id')` | `"symbol"` |
| BigInt | Integers with arbitrary precision (can store very large numbers). | `100n` | `"bigint"` |
Test Your Knowledge
Test Your Knowledge
Which of the following is NOT a primitive data type in JavaScript?
What does 'immutability' mean for primitive data types?
What will console.log(typeof null) output?
When is undefined typically used?
Quick Reference
Quick Reference
- 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
trueorfalse, 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
numbertype. - 10
typeofOperator — Usetypeofto check the data type of a variable or value, e.g.,typeof 10returns"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.