Data Types: Primitives and Objects
What are Data Types?
When you store data in a variable, that data can come in different forms. You can store text, numbers, or even complex collections of data. These forms are called "Data Types".
JavaScript data types are divided into two main categories: Primitive Types and Object (Reference) Types.
Primitive Data Types
Primitives are the most basic data types. They hold a single, simple value.
- String: Text wrapped in quotes (single
'', double"", or backticks\``).let name = "Himubey"; - Number: Numbers, with or without decimals.
let age = 25; let price = 99.99; - Boolean: Represents a logical entity and can have only two values:
trueorfalse.let isLoggedIn = true; - Undefined: A variable that has been declared but has not yet been assigned a value.
let userScore; // currently undefined - Null: Represents the intentional absence of any object value. It is literally "nothing".
let currentTarget = null;
Object Data Types
Objects are complex data types that can hold collections of values or more complex entities.
- Object: A collection of key-value pairs.
let user = { name: "Himubey", age: 25 }; - Array: A list of items. (Technically a special type of object in JS).
let colors = ["Red", "Green", "Blue"];
To check the type of a variable, you can use the built-in typeof operator:
console.log(typeof 42); // Outputs: "number"
💡 Himanshu's Tip:
It's easy to get confused by null and undefined. Just remember: undefined means the JavaScript engine hasn't set a value yet. null means YOU (the developer) intentionally set it to have no value.
Interview Questions
- What is the difference between a Primitive data type and an Object data type?
- How do
nullandundefineddiffer? - Which data type is used to represent a logical
trueorfalse?