A function is a reusable block of code that performs a task.
Declaration and expression
JavaScript
// Function declaration (hoisted: can be called before it appears in the file)
function add(a, b) {
return a + b;
}
// Function expression (stored in a variable; not hoisted)
const multiply = function (a, b) {
return a * b;
};
// Arrow function (short form of an expression)
const square = x => x * x;
const area = (w, h) => {
return w * h;
};
console.log(add(2, 3)); // 5Parameters and return values
JavaScript
function greet(name = 'Guest', greeting = 'Hello') { // default parameters
return `${greeting}, ${name}!`;
}
greet(); // 'Hello, Guest!'
greet('Nimal'); // 'Hello, Nimal!'
function sum(...numbers) { // rest parameters
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10
function noReturn() { } // returns undefined- Parameters are the names in the definition; arguments are the values you pass in.
returnends the function and sends a value back. A function can return only one value, but that value can be an array or object.- Functions are values: you can pass them to other functions (callbacks), e.g.
arr.map(fn),setTimeout(fn, 1000). - A variable declared inside a function cannot be seen outside it (see Scope).
Try it: Write isPrime(n), factorial(n) (use a loop, then recursion), and average(...nums). Create an array of 5 student objects and use filter and map to list names of those with marks above 50.
Check yourself. The questions for this part are on the 7.11 Review Questions page, with answers to check your work.