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

JavaScript Functions

6 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 5 deck

JavaScript Functions
Fullscreen for presentation · Print / PDF for a handout
1 / 6
Lesson

JavaScript Functions

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

JavaScript 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!

JavaScript Functions

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.
JavaScript Functions

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.
JavaScript Functions

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).

JavaScript Functions

Activity — complete the code

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;
};