Data Structures
Data structures are ways to organize and store multiple pieces of data together. Instead of having separate variables for each piece of information, you can group related data. In this lesson, we'll learn about JavaScript's two most important data structures: arrays and objects.
What You'll Learn
- How to create and use arrays
- Common array methods and operations
- How to create and use objects
- How to access and modify object properties
- When to use arrays vs objects
Arrays
Arrays store lists of values in order. Think of an array as a numbered list where each item has a position (index) starting from 0.
Creating Arrays
// Create an array of numbers
let numbers = [1, 2, 3, 4, 5];
console.log("Numbers:", numbers);
// Create an array of strings
let fruits = ["apple", "banana", "orange"];
console.log("Fruits:", fruits);
// Arrays can hold different types
let mixed = [1, "hello", true, 3.14];
console.log("Mixed:", mixed);
// Empty array
let empty = [];
console.log("Empty array:", empty);
Accessing Array Elements
let fruits = ["apple", "banana", "orange", "mango"];
// Access by index (starts at 0)
console.log("First fruit:", fruits[0]);
console.log("Second fruit:", fruits[1]);
console.log("Last fruit:", fruits[3]);
// Get array length
console.log("Number of fruits:", fruits.length);
// Access last element using length
console.log("Last fruit:", fruits[fruits.length - 1]);
Modifying Arrays
let numbers = [1, 2, 3];
// Change an element
numbers[1] = 20;
console.log("After change:", numbers);
// Add to the end
numbers.push(4);
console.log("After push:", numbers);
// Remove from the end
let removed = numbers.pop();
console.log("Removed:", removed);
console.log("After pop:", numbers);
// Add to the beginning
numbers.unshift(0);
console.log("After unshift:", numbers);
// Remove from the beginning
let first = numbers.shift();
console.log("First removed:", first);
console.log("After shift:", numbers);
Array Methods
let numbers = [1, 2, 3, 4, 5];
// Find the index of an element
console.log("Index of 3:", numbers.indexOf(3));
// Check if array includes a value
console.log("Includes 4:", numbers.includes(4));
console.log("Includes 10:", numbers.includes(10));
// Join array into a string
let joined = numbers.join(", ");
console.log("Joined:", joined);
// Create a new array with a slice
let sliced = numbers.slice(1, 4);
console.log("Sliced (1 to 4):", sliced);
console.log("Original:", numbers);
Looping Through Arrays
let fruits = ["apple", "banana", "orange"];
// For loop
console.log("Using for loop:");
for (let i = 0; i < fruits.length; i++) {
console.log(i + ":", fruits[i]);
}
// For...of loop (modern way)
console.log("\nUsing for...of:");
for (let fruit of fruits) {
console.log(fruit);
}
// forEach method
console.log("\nUsing forEach:");
fruits.forEach(function(fruit, index) {
console.log(index + ":", fruit);
});
Objects
Objects store data as key-value pairs. Instead of using numbers like arrays, objects use names (keys) to identify values.
Creating Objects
// Create an object
let person = {
name: "Alice",
age: 25,
city: "New York"
};
console.log("Person:", person);
// Empty object
let empty = {};
console.log("Empty object:", empty);
Accessing Object Properties
let person = {
name: "Alice",
age: 25,
city: "New York",
isStudent: false
};
// Dot notation
console.log("Name:", person.name);
console.log("Age:", person.age);
// Bracket notation
console.log("City:", person["city"]);
// Bracket notation with variable
let property = "age";
console.log("Dynamic property:", person[property]);
Modifying Objects
let person = {
name: "Bob",
age: 30
};
console.log("Original:", person);
// Change a property
person.age = 31;
console.log("After age change:", person);
// Add a new property
person.city = "Boston";
console.log("After adding city:", person);
// Delete a property
delete person.age;
console.log("After deleting age:", person);
Objects with Methods
Objects can contain functions, called methods:
let calculator = {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
},
multiply: function(a, b) {
return a * b;
}
};
console.log("5 + 3 =", calculator.add(5, 3));
console.log("10 - 4 =", calculator.subtract(10, 4));
console.log("6 * 7 =", calculator.multiply(6, 7));
Looping Through Objects
let person = {
name: "Charlie",
age: 28,
city: "Chicago",
occupation: "Developer"
};
// For...in loop
console.log("Object properties:");
for (let key in person) {
console.log(key + ":", person[key]);
}
// Get all keys
let keys = Object.keys(person);
console.log("\nAll keys:", keys);
// Get all values
let values = Object.values(person);
console.log("All values:", values);
Arrays of Objects
Combining arrays and objects is very common:
// Array of objects
let students = [
{ name: "Alice", grade: 85 },
{ name: "Bob", grade: 92 },
{ name: "Charlie", grade: 78 }
];
console.log("Students:");
for (let student of students) {
console.log(student.name + " - Grade:", student.grade);
}
// Access specific student
console.log("\nFirst student:", students[0].name);
// Calculate average grade
let total = 0;
for (let student of students) {
total += student.grade;
}
let average = total / students.length;
console.log("Average grade:", average);
Nested Structures
Objects can contain arrays and other objects:
let school = {
name: "JavaScript High",
students: ["Alice", "Bob", "Charlie"],
location: {
city: "Boston",
state: "MA"
}
};
console.log("School:", school.name);
console.log("Students:", school.students);
console.log("City:", school.location.city);
// Loop through nested array
console.log("\nStudent list:");
for (let student of school.students) {
console.log("- " + student);
}
Try It Yourself
Practice with these exercises:
// 1. Create an array of your favorite foods and print each one
let foods = ["pizza", "sushi", "tacos"];
console.log("My favorite foods:");
for (let food of foods) {
console.log("- " + food);
}
// 2. Create an object representing a book
let book = {
title: "JavaScript Guide",
author: "Tech Writer",
pages: 300,
published: 2024
};
console.log("\nBook info:", book.title, "by", book.author);
// 3. Create an array of objects representing products
let products = [
{ name: "Laptop", price: 999 },
{ name: "Mouse", price: 25 },
{ name: "Keyboard", price: 75 }
];
console.log("\nProducts:");
for (let product of products) {
console.log(product.name + ": $" + product.price);
}
// 4. Calculate total price of all products
let totalPrice = 0;
for (let product of products) {
totalPrice += product.price;
}
console.log("Total price: $" + totalPrice);
// Try creating your own data structures!
Key Takeaways
- Arrays store ordered lists of values, accessed by index (0, 1, 2, ...)
- Use arrays when you need an ordered collection of similar items
- Objects store key-value pairs, accessed by property name
- Use objects when you need to group related properties together
- Arrays and objects can be nested to create complex data structures
- Common array methods:
push(),pop(),shift(),unshift(),indexOf(),includes() - Access object properties with dot notation (
obj.key) or bracket notation (obj["key"])
Next Steps
Congratulations! You've completed the fundamental JavaScript lessons. You now know:
- How to write basic JavaScript code
- How to work with variables and data types
- How to create and use functions
- How to control program flow with conditions and loops
- How to organize data with arrays and objects
Keep practicing by building small projects and experimenting with the code playground. The more you code, the better you'll get!
Pro Tip: The best way to master data structures is to use them in real projects. Try creating a todo list with an array of objects, or a contact book using nested objects. Practice makes perfect!