DEV Community

loading...
Cover image for Understanding JS Functions, Pt 1: Getting Started

Understanding JS Functions, Pt 1: Getting Started

Zachary Dinerstein
・6 min read

Functions are one of the most useful tools in your coding toolkit. Well-written functions can turn horrible spaghetti code into logical programs that are more easy 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.

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

To learn more, check out this video.

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.


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.

Alt Text

Once your CodeSandbox is set up, delete everything in index.js to start with a clean slate.


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

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):

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!

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();
Enter fullscreen mode Exit fullscreen mode

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

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.

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

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')
}
Enter fullscreen mode Exit fullscreen mode

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

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');
Enter fullscreen mode Exit fullscreen mode

This will log:

// Donny
// 5 Slacker Ave
// Los Angeles, CA 10001
Enter fullscreen mode Exit fullscreen mode

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

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');
Enter fullscreen mode Exit fullscreen mode

This works just fine.

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


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
Enter fullscreen mode Exit fullscreen mode

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

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

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

Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)