In this tutorial, we will explore the basics of using collections in JavaScript, such as arrays and dictionaries (also known as objects in JavaScript). You'll learn how to create, manipulate, and access data within these collections.
By the end of this tutorial, you will understand how to:
Prerequisites: Basic knowledge of JavaScript and HTML is required.
Collections are data structures that hold multiple values. The two main types of collections in JavaScript are arrays and dictionaries (objects).
An array is a collection of items stored in contiguous memory locations. You can declare an array in JavaScript using square brackets ([]).
Example:
let fruits = ['apple', 'banana', 'cherry'];
Accessing an item in the array is done by using its index. Remember, arrays in JavaScript are zero-indexed!
console.log(fruits[0]); // Outputs: apple
In JavaScript, dictionaries are called objects. They store data in key-value pairs. You can declare an object using curly braces ({}).
Example:
let student = {
name: 'John',
age: 20,
grade: 'A'
};
Accessing a value in the object is done by using its key.
console.log(student.name); // Outputs: John
// Defining an array
let numbers = [10, 20, 30, 40, 50];
// Accessing array elements
console.log(numbers[2]); // Outputs: 30
// Changing an array element
numbers[2] = 60;
console.log(numbers); // Outputs: [10, 20, 60, 40, 50]
// Adding to the array
numbers.push(70);
console.log(numbers); // Outputs: [10, 20, 60, 40, 50, 70]
// Defining an object
let car = {
make: 'Toyota',
model: 'Camry',
year: 2020
};
// Accessing object properties
console.log(car.make); // Outputs: Toyota
// Changing a property
car.year = 2021;
console.log(car); // Outputs: { make: 'Toyota', model: 'Camry', year: 2021 }
// Adding a property
car.color = 'Red';
console.log(car); // Outputs: { make: 'Toyota', model: 'Camry', year: 2021, color: 'Red' }
In this tutorial, we've learned how to create and manipulate collections in JavaScript, including arrays and dictionaries (objects). We've also discussed how to retrieve data from these collections.
To continue your learning journey, consider exploring more advanced topics, such as nested collections and the various built-in methods for arrays and objects.
Some useful resources include the Mozilla Developer Network's JavaScript documentation and the W3Schools JavaScript tutorial.
Solutions:
// Exercise 1
let favoriteFoods = ['pizza', 'pasta', 'ice cream'];
console.log(favoriteFoods[0]); // Outputs: pizza
console.log(favoriteFoods[favoriteFoods.length - 1]); // Outputs: ice cream
// Exercise 2
let book = {
title: 'To Kill a Mockingbird',
author: 'Harper Lee',
pages: 281
};
console.log(book.title); // Outputs: To Kill a Mockingbird
// Exercise 3
favoriteFoods[2] = 'sushi';
console.log(favoriteFoods); // Outputs: ['pizza', 'pasta', 'sushi']
Happy coding!