DEV Community

Cindy Hernandez
Cindy Hernandez

Posted on • Updated on

JavaScript functions

What are functions?

Functions are like recipes.
They execute a set of instructions on data or variables and return the result.

  1. Functions can be recycled
  2. Helps keep your code DRY ("Don't repeat yourself")

If you are like me and need an example to visualize what functions do here is one.

Example:
Let's just say we have an espresso machine that can be programmed to make customized drinks.

It allows you to enter a command that will instruct the machine to brew espresso, add hot cocoa mix, and froth milk. Can you imagine how tedious it can be to type all steps every morning? What if we have more than one type of drink, when some drinks require more steps.

Instead of typing each step everyday, what if we could create functions with all the steps in the code block?

For the sake of this example, I used keywords that relate to the explanation above.

Function example

How to create a function:

  1. Use the function keyword

  2. Name the function

  • In this case we named it makeMochaLatte
  1. We add a set of parenthesis and curly brackets
  • makeMochaLatte(){}
  1. The first curly bracket is the beginning point and the second bracket is the end point of the function

  2. Everything inside of the curly brackets is called the block of code

  3. Lastly, we call the function makeMochaLatte();

Now that we learned the simplest form of a function. What if instead of just saying makeMochaLatte(); we do something like this.

parameters and arguments

In the example above we see the word "cups" in makeMochaLatte(cups){}, we call this a parameter, the word cups is used like a variable that is bound to the input.
Now when we call the function makeMochaLatte(3); we are giving it an input of 3, this is called an argument.

By giving it an input of 3 we are essentially specifying that now we have a variable named cups that is equal to 3.

This is not the only way to write functions, but that is another topic we can dive in the next blog.
I will go over various ways you can write functions, such as arrow functions, expression functions, and functions with multiple parameters, and arguments.

Sources:

  1. "Methods and Functions", CodeCademy https://www.codecademy.com/article/fwd-js-methods-functions

  2. Yu, Dr. A. "Functions Part 1"
    https://www.udemy.com/course/the-complete-web-development-bootcamp/learn/lecture/12371950#questions

  3. Yu, Dr. A. "Functions Part 2"
    https://www.udemy.com/course/the-complete-web-development-bootcamp/learn/lecture/12373850?start=0#overview

Top comments (0)