Drawn to coding: JS functions, pt 1
Tags: javascript, frontend, beginners, functions
Published: 2021-07-26 19:23:00

Functions are maybe the most useful tool in your coding toolkit. Well-written functions can turn horrible spaghetti code into logical programs that are easier to understand and maintain.

In this tutorial, we'll explain what JavaScript functions are, why they're important, and how you can put them to good use. Let's dive in! 🤿


> **Who is this tutorial for?**
> Everything here is for total beginners – you don't need to know anything about programming, web development or JavaScript.

{% details Some tech terms that might be new %}
**Console**
The console is part of your browser. It's used to log errors and debug issues with your code. If there's problem with your internet connection for instance, you'll probably see an error message pop up in the console. 

In this tutorial, we'll make sure our code is working by logging messages there. 

If you're using Chrome, you can open the console by pressing Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux). 

![Example of Chrome's Console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lwoequbfb5krq1644qqq.png)

To learn more, [check out this video](https://www.youtube.com/watch?v=q9jAFZjPFHo).


**Browser**
A browser is a program your computer uses to open a webpage (you probably know this because you're using one right now to read this sentence). Examples of browsers are Chrome, Firefox and Safari to name a few. 

{% enddetails %}
{% details How to code along with this tutorial %}

There's an empty CodeSandbox interface at the bottom of this article you can use to practice along with each exercise. 

You can also create your own CodeSandbox on their website if you want to save your program and reopen it later. [Checkout CodeSandbox here](https://codesandbox.io/s/).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cbekyvj2bk7y0i1lf1dm.png)

Once your CodeSandbox is set up, delete everything in index.js to start with a clean slate. 
{% enddetails %}
## What Are Functions?

> **Analogy**
> Think of functions as little factories. You turn them on and they spit out a desired result on command. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/asxtcbzkzuou167ejzle.jpg)

Let's say you want to write a program that logs your name and address to the console.

You could write something like this (open 'console' below to see output):

{% codesandbox suspicious-snowflake-0zs9l view=split %}

This works fine, but let's say you want to log your name and address three times. How would you do this? 

You could copy and paste that code over and over, but that's pretty repetitive. And the first rule of programming is DRY (Don't Repeat Yourself).

Instead, let's write (you guessed it) a function!

{% codesandbox nostalgic-yonath-hepny view=split %}

Much better! When this function's called, it will execute everything between those curly brackets – what we call the *body* of our function. 

But as you can see, we haven't logged anything to our console. Why is that?

We didn't log anything because we didn't actually *call* our function.

To call (also known as *invoke*) a function, you write the function's name and add parentheses to the end, like this:

```
logName();
```

{% codesandbox pensive-margulis-k0gms view=split %}

BOOM. We just wrote AND called our first function. Give yourself a pat on the back.

> **Analogy**
> Think of the parens on the end of the function name like a red ball on the end of a lever. In order to start our factory (*call* our function), we need to PULL on that giant lever. 
> Adding the parens to the end of the function name is how we pull that lever and start our factory running. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/41l0u76d9sg0v06xofdt.jpg)

Now we can call that function as many times as we want, logging multiple strings to the console. ('Strings' are what text is called in JavaScript.) This saves us from writing tons of code. Let's try. 

{% codesandbox sleepy-brattain-2fqk3 view=split %}

Much nicer. See how this code is easier to read? We're not cluttering up our program by pasting gobs of console logs over and over.

> **Important**
> When you write function or variable names, capitalization counts. logName is not the same as LogName. 

**Parts of a function**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zte9kburekw5dqvprhe0.png)
## Making Your Functions More Flexible

Our function's off to a great start, but it's a little rigid. It only does one thing: log a specific name and address. 

Coming back to our factory analogy, let's say you built a factory that produces red Honda sedans. If you wanted to switch it up and produce *blue* Honda sedans one day of the week, what would you do? Build an entirely new factory that manufactures Hondas, only in blue?

You could, but that's a giant waste of resources and time. 

Instead, being the industrious entrepreneur you are, you'd probably set up your factory to produce a different colored car based on whatever color you loaded into it that day. This approach is MUCH better, because it makes your factory flexible. If you want yellow cars, you load in yellow. If you want purple cars, you load in purple, and on and on.

We want our functions to be this flexible. 

Here's how we might redesign our code to print *any* name to the console, not just 'The Dude'.

```
function logName(name){
     console.log(name);
     console.log('5 Slacker Ave')
     console.log('Los Angeles, CA 10001')
}
```
We made two changes to logName. First, we added a parameter inside the parentheses. Second, we included that same parameter inside the function's body (the code between the brackets).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/93nnhgumg7sgbv2eodqv.png)

These changes look small, but they're powerful.

This allows us to pass any string into the function, and then use that string inside the function. 

For example:

```
logName('Donny');
```

This will log:

```
// Donny
// 5 Slacker Ave
// Los Angeles, CA 10001
```
Amazing! Now our function can log whatever we pass it. 

> **Analogy**
> The parentheses in a function declaration act as a kind of loading dock for our factory. Anything we load in through those parentheses we can then use inside our factory. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nw9gl8lj9u9npe8aowki.jpg)

> **Important**
> We can name our parameters whatever we want. If we want to use that parameter in the function's body however, we need to match that name *exactly*. Just like with our function names, spelling and capitalization count. 

For example:

```
function logName(orange){
     console.log(orange);
     console.log('5 Slacker Ave');
     console.log('Los Angeles, CA 10001');
}

logName('Walter');
```

This works just fine.

The examples below however will log 'Undefined' or send an error to the console:

{% codesandbox sweet-bartik-437sh view=split %}
{% codesandbox hidden-resonance-tojnp view=split %}

## What Else Can We Do With Parameters?

We're not limited to just one – we can add as many parameters as we want to our functions.

```
function logAddress(name, street, cityStateZip){
     console.log(name);
     console.log(street);
     console.log(cityStateZip);
}

logAddress('Walter', '10 Aggression Ave', 'Los Angeles, CA 10001')

// Walter 
// 10 Aggression Ave
// Los Angeles, CA 10001
```

Just make sure each parameter is separated by a comma, that the arguments are also separated by commas, and that they're in matching order. The first argument corresponds to the first parameter, the second corresponds to the second, and so on…

("Arguments" are what we call parameters when they appears inside a function call.)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/brjpjbimh7hj5crzjv6f.png)

## Now It's Your Turn!
Use the CodeSandbox below to test what you've learned.

1. Write a function that logs the name of your first pet, type of animal and their favorite toy. 

2. Update the function so it uses parameters and arguments

{% codesandbox exciting-noyce-kmqq6 view=split %}

{% details Our Solution %}

```
// Question 1
function logPet() {
  console.log("Mac");
  console.log("Dog");
  console.log("Bone");
}

// Question 2
function logPet2(name, animal, toy) {
  console.log(name);
  console.log(animal);
  console.log(toy);
}

logPet();
// Mac
// Dog
// Bone

logPet2("Raptor", "Iguana", "Warm rock");
// Raptor
// Iguana
// Warm rock

```
{% enddetails %}

That's it for now! In part 2 – coming soon – we'll learn about return statements, arrow functions and other JS function stuff. If you liked this tutorial, please let me know, and feel free to include requests of topics you want me to cover in the future. Happy coding!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u4dgmu0vm7wxcdpe8ibd.jpg)