Learn
Functions
Functions for Flexibility

Not everyone wants to eat hamburgers.

We could write a new function for each new sandwich type, but that takes a lot of work and risks making mistakes.

Instead, we’ll generalize the hamburger function to a sandwich function. This new sandwich function will still make a bread-topping-topping-bread combination, but the toppings may change based on inputs to the function:

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

We’ve renamed the function makeSandwich() and given it two inputs, or parameters. Each time we call the function, we’ll give actual values for each input, 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.

Instead of writing a different function for each type of sandwich, we have one function that can make them all!

Instructions

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

Notice how the instructions change with different inputs.

Folder Icon

Take this course for free

Already have an account?