Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 5

JavaScript Functions

Defining and calling reusable blocks of code, plus anonymous functions.


JavaScript Functions

A function is a reusable block of code that performs a specific task. It eliminates repetition and breaks complex programs into manageable pieces.

function functionName(param1, param2) {
  // code to be executed
  return value;   // optional
}

function multiply(a, b) {
  return a * b;
}

document.getElementById("demo").innerHTML = multiply(4, 3);  // 12

Define once, call many times — with different arguments each time!

Function Invocation

  1. Function invocation — a direct call using the function name and arguments.
  2. Method invocation — called as a method on an object, using dot notation.
  3. Constructor invocation — used with the new keyword to create object instances.

Example: Temperature Converter

function toCelsius(fahrenheit) {
  return (5 / 9) * (fahrenheit - 32);
}

var result = toCelsius(77);
document.write("The temperature is " + result + " Celsius");
// Output: "The temperature is 25 Celsius"
  • The return statement sends the computed value back to the caller; execution stops at return.
  • Parameters are placeholders in the definition; arguments are the actual values you pass when calling.

Anonymous Functions

An anonymous function has no name. Instead, it is assigned to a variable or passed as an argument to another function.

// Anonymous function assigned to a variable
var multiply = function (a, b) {
  return a * b;
};
multiply(4, 3);   // 12

// Named function (for comparison)
function multiplyNamed(a, b) {
  return a * b;
}

Anonymous functions are commonly used as callbacks — functions passed as arguments to other functions (event handlers, setTimeout, array methods like forEach, map, filter).

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

Complete the function definitions.

multiply(a, b) {
a * b;
}
 
document.getElementById("demo").innerHTML = multiply(4, 3); // 12
 
// Anonymous function assigned to a variable
var divide = (a, b) {
return a / b;
};