Every piece of information in JavaScript has a specific type. These types help JavaScript understand what kind of data you are working with. Learning data types is a fundamental step to writing good code. In this tutorial, you will learn about the different data types, how to use them, and why they are important.
1.9 JavaScript Data Types
1.9 JavaScript Data Types
When you write code, you are always working with data. This data can be numbers, text, or even more complex things. JavaScript needs to know what kind of data each piece is. This is called a data type. Knowing data types helps JavaScript perform the right actions with your data. For example, you can add numbers together, but you cannot add a number to a piece of text in the same way.
What are Data Types?
A data type is a classification that tells JavaScript what kind of value a variable holds.
Primitive Types
These are basic, single values like numbers, text, and true/false. They are stored directly.
Object Types
These are complex collections of data, like lists or structured information. They are stored by reference.
Dynamic Typing
JavaScript figures out the type of your data as your code runs. You do not have to tell it beforehand.
`typeof` Operator
This special tool helps you find out the data type of any value or variable in your code.
What are Data Types?
What are Data Types?
Imagine you have different kinds of toys. Some are blocks, some are dolls, and some are cars. Each toy is different and you play with them in different ways. In programming, data types are like these different kinds of toys. JavaScript has several built-in data types to categorize different kinds of values. We will start with the most common ones: numbers, strings, and booleans.
1// A 'number' data type holds numeric values2let age = 30;3console.log(typeof age); // This will print "number"45// A 'string' data type holds text, enclosed in quotes6let userName = "Alice";7console.log(typeof userName); // This will print "string"89// A 'boolean' data type holds true or false values10let isActive = true;11console.log(typeof isActive); // This will print "boolean"1213// You can also see the type of a value directly14console.log(typeof 123); // Prints "number"15console.log(typeof "Hello"); // Prints "string"
Beware of `null` and `undefined`
A common mistake for beginners is confusing null and undefined. undefined means a variable has been declared but not given a value. null means a variable has been assigned a value that represents 'nothing' or 'empty'. Even though typeof null returns "object", null is actually a primitive type. This is a historical quirk of JavaScript.
Primitive vs. Object Data Types
Primitive vs. Object Data Types
JavaScript data types are broadly split into two main groups: primitive types and object types. Primitive types represent single values. When you copy a primitive variable, you copy its actual value. Object types are more complex and can hold collections of data. When you copy an object variable, you copy a 'reference' to where the object lives in memory, not the object itself. This difference is very important for how your data behaves.
1// Primitive Type Example: 'number'2let score1 = 100; // score1 holds the value 1003let score2 = score1; // score2 gets a COPY of the value 1004score1 = 150; // Changing score1 does NOT change score25console.log("Primitive Example:");6console.log("score1:", score1); // 1507console.log("score2:", score2); // 100 (still the original copy)89// Object Type Example: 'object' (a simple object)10let player1 = { name: "Max", level: 5 }; // player1 holds a REFERENCE to the object11let player2 = player1; // player2 gets a COPY of the REFERENCE (points to the SAME object)12player1.level = 10; // Changing player1's object changes the SAME object player2 refers to13console.log("\nObject Example:");14console.log("player1:", player1); // { name: "Max", level: 10 }15console.log("player2:", player2); // { name: "Max", level: 10 } (changed because they share the same object)
let num1 = 5;let num2 = num1;num1 = 10;// num2 is still 5
let obj1 = { value: 5 };let obj2 = obj1;obj1.value = 10;// obj2.value is now 10
Checking Data Types with `typeof` and `instanceof`
Checking Data Types with `typeof` and `instanceof`
It is often useful to know what type of data you are working with. JavaScript provides two main ways to check data types: the typeof operator and the instanceof operator. Each has its own best use case. typeof is great for primitive types. instanceof is better for checking specific kinds of objects.
let myNumber = 42;console.log(typeof myNumber); // "number"let myString = "hello";console.log(typeof myString); // "string"let myBoolean = true;console.log(typeof myBoolean); // "boolean"let myUndefined;console.log(typeof myUndefined); // "undefined"console.log(typeof null); // "object" (historical quirk)
class Animal { constructor(name) { this.name = name; } }class Dog extends Animal { bark() { console.log("Woof!"); } }let myDog = new Dog("Buddy");console.log(myDog instanceof Dog); // trueconsole.log(myDog instanceof Animal); // true (Dog is an Animal)let myArray = [1, 2, 3];console.log(myArray instanceof Array); // trueconsole.log(myArray instanceof Object); // true (Arrays are objects)let myObject = { a: 1 };console.log(myObject instanceof Object); // true
let myNumber = 42;console.log(typeof myNumber); // "number"let myString = "hello";console.log(typeof myString); // "string"let myBoolean = true;console.log(typeof myBoolean); // "boolean"let myUndefined;console.log(typeof myUndefined); // "undefined"console.log(typeof null); // "object" (historical quirk)
class Animal { constructor(name) { this.name = name; } }class Dog extends Animal { bark() { console.log("Woof!"); } }let myDog = new Dog("Buddy");console.log(myDog instanceof Dog); // trueconsole.log(myDog instanceof Animal); // true (Dog is an Animal)let myArray = [1, 2, 3];console.log(myArray instanceof Array); // trueconsole.log(myArray instanceof Object); // true (Arrays are objects)let myObject = { a: 1 };console.log(myObject instanceof Object); // true
When to Use Which Operator
Use typeof when you want to check for primitive types (number, string, boolean, symbol, bigint, undefined). It gives a simple string result. Use instanceof when you want to check if an object is a specific type of object, like an Array, Date, or a custom class you created. It checks the 'ancestry' of an object.
Using Data Types in Real JavaScript
Using Data Types in Real JavaScript
Understanding data types is not just theoretical. It helps you write robust and error-free code. For example, you might need to ensure a user enters a number for their age, or that a password field contains text. Data types are essential for making sure your program handles different inputs correctly and performs the right operations. Here are some practical steps.
Declare Variables with Appropriate Types
Always think about what kind of data your variable will hold. Use let or const to declare variables.
1let userName = "Jane Doe"; // String for text2let userAge = 25; // Number for age3let isAdmin = false; // Boolean for true/false status
Validate User Input
When users type information into a form, it often comes as a string. You might need to check if it's a number or convert it.
1let inputAge = prompt("Enter your age:"); // prompt always returns a string23// Check if it's a number after trying to convert it4if (typeof Number(inputAge) === 'number' && !isNaN(Number(inputAge))) {5 console.log("Age is a valid number:", Number(inputAge));6} else {7 console.log("Invalid age input.");8}
Perform Type Conversion When Needed
Sometimes you need to change a value from one type to another. This is called type conversion or type casting. For example, converting a string to a number to do math.
1let stringNumber = "100";2let actualNumber = Number(stringNumber); // Converts string "100" to number 1003console.log(typeof actualNumber); // "number"45let numToString = String(500); // Converts number 500 to string "500"6console.log(typeof numToString); // "string"
Implicit Type Coercion Can Lead to Bugs
JavaScript can sometimes automatically change data types for you. This is called implicit type coercion. For example, "5" + 2 results in "52" (string concatenation), not 7 (addition), because JavaScript converts 2 to a string. This can cause unexpected bugs if you are not careful. Always be explicit with your types using Number(), String(), or Boolean() when needed.
JavaScript Data Type Reference
JavaScript Data Type Reference
Here is a quick overview of the main JavaScript data types, what they hold, and what the typeof operator will tell you. Understanding these will help you identify and work with different kinds of data more effectively in your programs.
| Data Type | Description | Example Value | `typeof` Result | |
|---|---|---|---|---|
| String | Textual data, enclosed in quotes. | "Hello World!" | "string" | |
| Number | Numeric data, including integers and decimals. | 10, 3.14 | "number" | |
| Boolean | Logical entity, either true or false. | true, false | "boolean" | |
| Undefined | A variable that has been declared but not assigned a value. | let x; | "undefined" | |
| Null | Intentional absence of any object value. | let y = null; | "object" (historical quirk) | |
| Symbol | A unique and immutable primitive value. | Symbol('id') | "symbol" | |
| BigInt | Integer values larger than what the Number type can hold. | 100n | "bigint" | |
| Object | A collection of properties. All non-primitive values. | { name: "Alice" }, [1, 2], function(){} | "object" | "function" (for functions) |
Test Your Knowledge
Test Your Knowledge
What will typeof "100" return in JavaScript?
Which of the following is NOT a primitive data type in JavaScript?
If you declare let myVar; and do not assign a value, what will typeof myVar return?
What is the result of 5 + "5" in JavaScript?
Quick Reference
Quick Reference
- 1Data Type — A classification that tells JavaScript what kind of value a variable holds.
- 2Primitives — Basic, single values like
number,string,boolean,null,undefined,symbol, andbigint. - 3Objects — Complex, collection-based values like arrays, functions, and plain objects. They are stored by reference.
- 4
typeofOperator — Used to check the data type of a value or variable. Returns a string like "number" or "string". - 5
instanceofOperator — Used to check if an object is an instance of a specific class or constructor, useful for complex object types. - 6Dynamic Typing — JavaScript determines data types at runtime; you do not declare them explicitly.
- 7Type Coercion — JavaScript's automatic conversion of one data type to another, which can be explicit (e.g.,
Number()) or implicit (e.g.,"5" + 2). - 8
nullvsundefined—undefinedmeans a variable exists but has no value.nullmeans a variable has been assigned an explicit 'empty' value. - 9
typeof nullis "object" — This is a historical error in JavaScript that cannot be fixed due to backward compatibility. - 10Arrays are Objects — Arrays are a special type of object. Use
Array.isArray()to check if a variable is specifically an array.
Type Conversion
Learn how to manually change data from one type to another, like string to number.
Operators
Explore how different operators (like +, -, ==) interact with various data types.
Objects in Depth
Dive deeper into how objects work, their properties, and methods.
Functions
Understand functions as first-class objects and how they handle different data types as arguments.
Congratulations!
You have successfully learned the fundamental concept of JavaScript data types. You now understand the difference between primitives and objects, how to check types, and why these concepts are crucial for writing correct and predictable code. Keep practicing and building your skills!
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.