SPREAD OPERATOR SUM
// Function to calculate the sum of numbers
function sum(...numbers) {
let total = 0; // Initialize total to 0
for (let num of numbers) {
total += num; // Add each number to total
}
return total; // Return the total sum
}
// Array of numbers
const numbersArray = [1, 2, 3, 4, 5];
// Using the spread operator to pass the array elements as arguments
const total = sum(...numbersArray);
console.log(`The sum is: ${total}`); // Output: The sum is: 15
Comments
Post a Comment