Imagine we were creating a sandwich-making program for a store. The four instructions could be to add bread, add peanut butter, add jelly, and then add another bread on top. Sounds easy, right?

But imagine needing to write enough code for 1000 sandwiches? That requires us to write a lot more code over and over again. Luckily, we can use functions to make this process easier!

A function is a named sequence of instructions, packaged as a unit, that performs a specific task. Functions make code flexible, reusable, and well-organized. Let’s take a look at a sample function:

function makeSandwich() { Add bread Add peanut butter Add jelly Add bread }

Our makeSandwich() function will execute all the instructions inside of it anytime it is called in a program. Now we can easily make a sandwich whenever we need one!

However, no store only sells peanut butter and jelly sandwiches - our program needs to be able to make all kinds of sandwiches. Instead of writing a different function for each type of sandwich, we can have one function that can make them all!

function makeSandwich(topping1, topping2) { Add bread Add topping1 Add topping2 Add bread }

We’ve updated our function makeSandwich() by giving it two inputs, or parameters. Parameters are variables that can be used inside the function body. Each time we call the function, we’ll give actual values for each parameter, called arguments.

For example, we make a ham-and-cheese sandwich with makeSandwich("ham", "cheese"). We call the function with the arguments “ham” and “cheese”. Those will be the values for the topping1 and topping2 parameters.


Call the makeSandwich() function with the arguments "ham" and "cheese".

Notice how the instructions change with different inputs.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?