Functions
Functions are reusable blocks of code that perform specific tasks. They help organize code and make it more modular.
Declaring and Calling Functions
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Outputs: Hello, Alice!
Arrow Functions
ES6 introduced a shorter syntax for writing functions:
const greet = (name) => {
return "Hello, " + name + "!";
};
// For single expressions, you can shorten it further:
const greetShort = name => `Hello, ${name}!`;
Arrays
Arrays are ordered lists of values. They can contain any type of data.
Creating and Accessing Arrays
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Outputs: apple
// Adding elements
fruits.push("date");
console.log(fruits); // Outputs: ["apple", "banana", "cherry", "date"]
Common Array Methods
forEach()
: Executes a function for each array element
fruits.forEach(fruit => console.log(fruit));
map()
: Creates a new array with the results of calling a function for every array element
let upperFruits = fruits.map(fruit => fruit.toUpperCase());
filter()
: Creates a new array with all elements that pass the test implemented by the provided function
let longFruits = fruits.filter(fruit => fruit.length > 5);
Objects
Objects are collections of key-value pairs. They’re used to store and organize related data.
Creating and Accessing Objects
let person = {
name: "John",
age: 30,
isStudent: false
};
console.log(person.name); // Outputs: John
console.log(person["age"]); // Outputs: 30
Methods in Objects
Objects can also contain functions (methods):
let car = {
brand: "Toyota",
model: "Corolla",
start: function() {
console.log("The car is starting!");
}
};
car.start(); // Outputs: The car is starting!
Putting It All Together
Let’s combine functions, arrays, and objects in a practical example:
let library = {
books: [
{title: "1984", author: "George Orwell"},
{title: "To Kill a Mockingbird", author: "Harper Lee"},
{title: "The Great Gatsby", author: "F. Scott Fitzgerald"}
],
listBooks: function() {
this.books.forEach(book => {
console.log(`${book.title} by ${book.author}`);
});
},
addBook: function(title, author) {
this.books.push({title: title, author: author});
}
};
library.listBooks();
library.addBook("The Catcher in the Rye", "J.D. Salinger");
library.listBooks();
Practice Exercise
Create an object representing a shopping cart. It should have an array to store items, a method to add items, and a method to calculate the total price. Each item should be an object with a name and price.
Conclusion
This lesson covered three crucial concepts in JavaScript: functions, arrays, and objects. These form the building blocks of more complex JavaScript programs. In the next lesson, we’ll explore more advanced topics like DOM manipulation and event handling.
Remember to practice these concepts by creating your own examples and experimenting with different combinations!