What Are Data Types in JavaScript: Simple Explanation and Examples
data types are categories that tell the computer what kind of value a variable holds, such as string, number, or boolean. These types help JavaScript understand how to store and use the data correctly.How It Works
Think of data types like different kinds of containers for information. Just like you wouldn't put soup in a shoe box, JavaScript uses data types to keep values organized and meaningful. For example, a string holds text like a name, while a number holds numeric values like age or price.
JavaScript has two main groups of data types: primitive types and objects. Primitive types are simple and hold one value, such as a number or true/false. Objects are more complex and can hold many values or properties, like a list of items or a user profile.
This system helps JavaScript decide what actions you can do with the data, like adding numbers or joining text.
Example
This example shows different data types in JavaScript and how to check their type using the typeof operator.
const name = "Alice"; const age = 30; const isStudent = false; const hobbies = ["reading", "sports"]; const person = { name: "Alice", age: 30 }; console.log(typeof name); // string console.log(typeof age); // number console.log(typeof isStudent); // boolean console.log(typeof hobbies); // object console.log(typeof person); // object
When to Use
Understanding data types helps you write code that works correctly and avoids errors. Use string for text like names or messages, number for calculations or counts, and boolean for true/false decisions like checking if a user is logged in.
Objects and arrays are useful when you need to group related data, such as a list of products or details about a user. Knowing the type helps you choose the right tools and methods to work with your data.
Key Points
- JavaScript data types tell the computer what kind of value is stored.
- Primitive types include
string,number,boolean,null,undefined,symbol, andbigint. - Objects and arrays hold collections of data and are more complex types.
- The
typeofoperator helps identify the type of a value. - Choosing the right data type makes your code clearer and less error-prone.