Data Types and Structures
Node.js uses JavaScript's data types. Some are primitives, some are objects. Let me walk you through what you will use.
Try it Yourself →Primitive Types
// String
const name = "Alice";
const greeting = `Hello, ${name}!`; // Template literal
// Number
const age = 25;
const price = 9.99;
const huge = 9007199254740991; // Max safe integer
// Boolean
const isActive = true;
// Null and Undefined
const nothing = null; // Intentionally empty
let notDefined; // undefined
// Symbol (unique identifier)
const id = Symbol("id");
// BigInt (for very large numbers)
const big = 9007199254740991n;
Objects
Objects store data as key-value pairs:
const user = {
name: "Alice",
age: 30,
email: "alice@example.com",
greet() {
return `Hi, I am ${this.name}`;
}
};
console.log(user.name); // Alice
console.log(user.greet()); // Hi, I am Alice
// Add new property
user.phone = "555-1234";
// Delete property
delete user.email;
Arrays
Arrays are ordered lists. Node.js gives you powerful array methods:
const fruits = ["apple", "banana", "cherry"];
// Add and remove
fruits.push("date"); // Add to end
fruits.pop(); // Remove from end
fruits.unshift("avocado"); // Add to beginning
fruits.shift(); // Remove from beginning
// Find and filter
const long = fruits.filter(f => f.length > 5);
const upper = fruits.map(f => f.toUpperCase());
const hasBanana = fruits.includes("banana");
// Sort
const sorted = [...fruits].sort();
Destructuring
Extract values from objects and arrays cleanly:
// Object destructuring
const { name, age, ...rest } = user;
// Array destructuring
const [first, second, ...others] = fruits;
// In function parameters
function greet({ name, age }) {
return `${name} is ${age}`;
}
Map and Set
These are built-in data structures for specific use cases:
// Map - key-value pairs with any key type
const cache = new Map();
cache.set("user:1", { name: "Alice" });
cache.get("user:1");
cache.has("user:1");
cache.size;
// Set - unique values
const unique = new Set([1, 2, 2, 3, 3]);
unique.size; // 3
unique.add(4);
unique.delete(1);