← All topics

LESSON 05 OF 10

Functions and Scope

Package steps, accept inputs, and return a result.

Before this lesson: complete the preceding lessons or review their examples. No installation or account is needed.

The idea

A function groups reusable behavior. Parameters name its inputs; arguments are the actual values passed when calling it. return sends a result back to the caller and exits that function.

At a glance

SyntaxPurpose
function name() {}Declare reusable behavior
returnSend a value back to the caller
parameterA local name for an input

Try it yourself

Call the same function with different arguments. Notice that declaring a function does not execute its body.

Ready. Run the example to open its preview.

Console output

Not run yet.

Page preview

Expected result
45
20

What to watch for

A variable declared inside a function is local to that function. let and const are also limited to their containing block. console.log displays a value; it does not replace return. Without an explicit returned value, a function normally returns undefined.

Your turn

Write a function double(number) that returns twice its input. Print double(7).

Show one solution
function double(number) {
  return number * 2;
}
console.log(double(7));

Check your understanding

What is the difference between returning and logging?

Returning lets other code use a result. Logging displays information for inspection.

Read alongside this lesson

W3Schools: Functions and Scope · All learning sources