Essential JavaScript

Going Further

Functions

A function is a set of instructions for the computer to run.

Functions can take in data, work with it, and return a result. The practice editor contains a function named returnFive that returns the value 5.

Try running the practice editor and see what happens.

Calling a Function

Functions are like recipes. Writing a recipe and following a recipe are two different things. Just because we write a recipe down on paper doesn't mean we automatically get food. We have to actually follow the recipe.

We just declared a function, but that's all we did. We just wrote our recipe down on paper.

In order to run the function (follow our recipe and get a result), we have to call it. To call a function, use the function's name with parentheses behind it:

returnFive();

A function call -- when you put parentheses behind a function's name -- is an expression.

You can log an expression with console.log:

console.log(returnFive());

Make sure your parentheses are correct:

  • You need a pair of parentheses after the function name
  • You need a separate pair of parentheses after console.log, which go around the function call
  • This means you have two closing parentheses: ))

Once we call the function and log its value, we should see 5 in the console output.

Summary

Functions are important because they allow us to reuse code. After we write a function once, we can use that function over and over again in other places in our code.

Learning Goals

  • I know what a function is

  • I can declare a function with the function keyword

  • I know the difference between declaring a function and calling a function

  • I can use the return keyword to return a value from a function

  • I know why functions are important in programming

Code Editor

Click "Run Code" to execute your JavaScript in a secure sandbox and see the output below.

Console Output

// Console output will appear here...

0 output lines