What Is a Callback Function, and How Does It Work with the forEach Method?
Imagine you have a function that performs a task, and you want to do something after that task is complete. Instead of writing all the code in one big function, you can pass a second function (the callback) to be executed when the first function is done.
let numbers = [1, 2, 3, 4, 5];
numbers.forEach((number, index, array) => {
console.log(`Element ${number} is at index ${index} in array ${array}`);
});
What Is Method Chaining, and How Does It Work?
const result = " Hello, World! "
.trim()
.toLowerCase()
.replace("world", "JavaScript");
console.log(result); // "hello, JavaScript!"
const transactions = [
{ amount: 100, type: "credit" },
{ amount: 20, type: "cash" },
{ amount: 150, type: "credit" },
{ amount: 50, type: "cash" },
{ amount: 75, type: "credit" }
];
const totalCreditWithBonus = transactions
.filter((transaction) => transaction.type === "credit")
.map((transaction) => transaction.amount * 1.1)
.reduce((sum, amount) => sum + amount, 0);
console.log(totalCreditWithBonus); // 357.5
How Does the Sort Method Work?
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits); // ["Apple", "Banana", "Mango", "Orange"]
How Do the every() and some() Methods Work?
The every() method returns true if the provided function returns true for all elements in the array. If any element fails the test, the method immediately returns false and stops checking the remaining elements.
const numbers = [2, 4, 6, 8, 10];
const hasAllEvenNumbers = numbers.every((num) => num % 2 === 0);
console.log(hasAllEvenNumbers); // true
While every() checks if all elements pass a test, some() checks if at least one element passes the test. The some() method returns true as soon as it finds an element that passes the test. If no elements pass the test, it returns false.
const numbers = [1, 3, 5, 7, 8, 9];
const hasSomeEvenNumbers = numbers.some((num) => num % 2 === 0);
console.log(hasSomeEvenNumbers); // true
Top comments (0)