JavaScript Functions - Exercise 2
An omitted parameter receives undefined unless the function provides a default value.
function greet(name = "friend") {
return `Hello, ${name}`;
}
console.log(greet()); // Hello, friendA rest parameter gathers remaining arguments into a real array.
function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
console.log(sum(2, 4, 6)); // 12A callback is a function passed to another function so it can be called later.
function runTask(task) {
return task();
}
console.log(runTask(() => "Complete"));A higher-order function accepts a function, returns a function, or does both.
function createMultiplier(factor) {
return (value) => value * factor;
}
const double = createMultiplier(2);
console.log(double(5)); // 10Function declarations are hoisted with their function body; function expressions are created when execution reaches the assignment.
sayHello();
function sayHello() {
console.log("Hello");
}
const sayBye = () => console.log("Bye");Return an object or array, then destructure the result at the call site.
function getCoordinates() {
return { x: 10, y: 20 };
}
const { x, y } = getCoordinates();
console.log(x, y);A pure function returns the same result for the same inputs and does not change outside state.
function add(left, right) {
return left + right;
}
console.log(add(2, 3)); // 5Small focused functions are easier to name, test, reuse, and compose into larger workflows.
function formatName(firstName, lastName) {
return `${firstName} ${lastName}`.trim();
}
console.log(formatName("Ada", "Lovelace"));