Beginner 11 min

Functions and scope

Break JavaScript into named operations and identify where a variable can be read.

Pass inputs as arguments

A function defines its parameters. A call supplies arguments to those parameters and executes the body. A return statement makes the value available to the caller. If execution reaches the end without a return, the result is undefined.

How it works

Give a function one job that you can state simply, such as computing a total from values it receives. A return hands the result back. A local variable can help calculate it without becoming a name available throughout the script.

Keep variables near their work

A const or let variable defined in a function is available inside that function’s block. Code outside that block cannot read it. Returning one value exposes the needed result without making temporary variables global.

Code example

function minutesToSeconds(minutes) {
  const secondsPerMinute = 60;
  return minutes * secondsPerMinute;
}

console.log(minutesToSeconds(3) + 15);

Check your understanding

Convert the whole minutes into seconds and add the extra seconds.

See the example and explanation
Example 1
Given 2 minutes, 5 seconds
Answer 125
Example 2
Given 0 minutes, 12 seconds
Answer 12

Return minutes * 60 + seconds. For 2 minutes and 5 seconds, that is 120 plus 5.

Open practice problem
Next lessonArrays and objects