Unit 7 ยท JavaScript

7.6Functions

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));       // 5

Parameters 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

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.