Lesson 6: Objects and Arrays in JavaScript
Objects and arrays are used to store collections of data in JavaScript. They provide powerful ways to manage and organize data in your programs.
Objects
1. Creating an Object
Objects are collections of key-value pairs. Each key is a string (or symbol), and each value can be of any type.
const person = { name: "John", age: 30, greet: function() { console.log("Hello, my name is " + this.name); } };
Example of Object:
const car = { brand: "Toyota", model: "Camry", year: 2021, start: function() { console.log("The car is starting."); } }; car.start(); // Output: The car is starting. console.log(car.brand); // Output: Toyota
2. Accessing Object Properties
Object properties can be accessed using dot notation or bracket notation.
console.log(person.name); // Dot notation console.log(person["age"]); // Bracket notation
Example of Accessing Properties:
console.log(car["model"]); // Output: Camry console.log(car.year); // Output: 2021
3. Modifying Objects
Object properties can be modified directly using dot notation or bracket notation.
person.age = 31; // Modify using dot notation person["name"] = "Jane"; // Modify using bracket notation
Example of Modifying Object:
car.year = 2022; car["brand"] = "Honda"; console.log(car.year); // Output: 2022 console.log(car.brand); // Output: Honda
Arrays
1. Creating an Array
Arrays are ordered collections of values. Each value in an array is called an element and can be accessed using its index.
const numbers = [1, 2, 3, 4, 5];
Example of Array:
const fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits[1]); // Output: Banana
2. Array Methods
JavaScript arrays come with various built-in methods to manipulate and interact with the array elements.
fruits.push("Orange"); // Add an element to the end of the array fruits.pop(); // Remove the last element of the array fruits.shift(); // Remove the first element of the array fruits.unshift("Strawberry"); // Add an element to the beginning of the array
Example of Array Methods:
fruits.push("Mango"); console.log(fruits); // Output: ["Strawberry", "Apple", "Banana", "Cherry", "Mango"] fruits.pop(); console.log(fruits); // Output: ["Strawberry", "Apple", "Banana", "Cherry"]
Assignment
Create a program that:
- Creates an object representing a book with properties for title, author, and year. Include a method to display the book details.
- Creates an array of numbers and finds the maximum and minimum values.
- Uses array methods to manipulate a list of students (e.g., add, remove, and sort).