JavaScript: Functions

Reusable blocks of code. Parameters in, results out.

Defining functions

// Declaration (hoisted)
function add(a, b) {
  return a + b;
}

// Expression
const multiply = function (a, b) {
  return a * b;
};

// Arrow function
const greet = (name = 'friend') => `Hello, ${name}!`;

console.log(add(2, 3));        // 5
console.log(multiply(2, 3));   // 6
console.log(greet('Ahbab'));   // Hello, Ahbab!

Parameters and scope

let message = 'global';

function demo(param) {
  const local = 'local';
  console.log(message, param, local);
}

demo('value');
// console.log(local); // ❌ ReferenceError: local is not defined

Practice

  1. Write a sum function that sums an array of numbers.
  2. Create a function that formats a user's full name from first/last.
  3. Convert a declaration to an arrow function.

Next up

Quick Check

What keyword immediately returns a value from a function?