Categories
JavaScript

Beginner’s guide to JavaScript functions

One of the most useful concepts to learn and master in the JavaScript programming language is functions.

Once you understand how they work, everything else in JavaScript becomes relatively easy.

This guide will help you understand functions in the JavaScript language, specifically function syntax and how to write, name and call the functions you create.

What is a function?

Functions are a way to keep your statements organized reusable and easy to reference.

In JavaScript, you’ll usually have to write a number of statements to arrive at a desired result.

For example, if I wanted to ask a visitor to my website their first name and then write their name in a popup box I’d need to write a few statements.

Here’s what the statements would look like:

var userName;
userName = window.prompt("What is your name?");
alert(username);

Each of the statements, or lines, in the code snippet above, is working together to accomplish the task of getting the user’s name and then displaying it in a popup box.

Since the goal of each statement is the same, they would be suitable to group into a function.

Here’s what they would look like grouped together as a function:

var myFirstFunction = () => {
var userName; 
userName = window.prompt("What is your name?"); 
alert("Hello" + userName);
};

Adding a function to these statements was as simple as wrapping them in the function syntax. In this instance, we wrapped the statements in a function named myFirstFunction.

The function syntax extracted from the example above looks like this:

var myFirstFunction = () => {
};

The above syntax wrapped around the statements turning them into a function.

As mentioned, functions help keep your statements organized reusable and easy to reference. We just saw how they help keep your statements organized and easy to reference. But how do we use them?

To use the statements in the function above you’ll need to call the function. When you want to execute the statements in a function this is referred to as calling the function.

To call the function you use the name you gave the function followed by ().

Let’s try to create and call this function in your browser console.

First, copy-paste the code below into your JavaScript console:

var myFirstFunction = () => {
var userName;
userName = window.prompt("What is your name?");
alert("Hello" + userName); 
};

Then call the function by typing this into your console and pressing enter:

myFirstFunction()

You should see something like this:

A screenshot demonstrating JavaScript functions.

Why use functions?

Functions have many benefits, not only do they keep your statements organized, reusable, and easy to reference, but they also make your code easier to maintain, faster to write, and simpler to debug.

Here are two reasons, with associated examples, why functions are extremely useful.

Reusable

Functions allow you to execute the collection of statements by calling the function instead of having to write the statements over and over again.

Using our previous example, imagine you had the following group of statements.

var userName;
userName = window.prompt("What is your name?");
alert(userName); 

Now imagine you wanted to add these statements to multiple pages on your website.

With a function, you’d simply wrap the statements in the function syntax and then call them where you’d like them to run:

Wrapping the statements in a function:

var myFirstFunction = () => {
var userName;
userName = window.prompt("What is your name?");
alert("Hello" + userName); 
}; 

Calling the function:

myFirstFunction();
myFirstFunction();
myFirstFunction();

Without a function:

var userName;
userName = window.prompt("What is your name?");
alert(userName);

var userName;
userName = window.prompt("What is your name?");
alert(userName);

var userName;
userName = window.prompt("What is your name?");
alert(userName);

Easier to maintain

When you adjust the statements within a function, every single instance where the function was called will have the same adjustment.

This is extraordinarily handy as it means you only need to adjust the code in a single location.

Imagine you had a website with hundreds of pages and imagine you had the following JavaScript statements that you needed to execute across them all:

var welcomeToMyWebsite;
welcomeToMyWebsite = alert("Welcome to my website!");

And let’s say you wanted to change the alert from "Welcome to my website!" to "Thanks for visiting my website!"

If you had the above statement written out hundreds of times across hundreds of pages you’d need to change every instance of the code in the hundreds of places it appears across your website.

This would take days and would be incredibly tedious.

If you had used a function, you’d only need to change the code once, in the function, and have it change everywhere the function was called across your website.

In other words, making the change from:

var welcomeToMyWebsite;
welcomeToMyWebsite = alert("Welcome to my website!"); 

to:

var welcomeToMyWebsteFunction = () => { 
var welcomeToMyWebsite;
welcomeToMyWebsite = alert("Thanks for visiting my website"); 
};

would cause every instance where the function below is called to change.

 welcomeToMyWebsteFunction()

Function syntax in ES6

ES6 is short for ECMAScript6. ECMAScript is the standardized form of JavaScript.

Don’t let this terminology confuse you, it’s really just JavaScript.

There are two types of function syntax in JavaScript: ES6 and ES5. You’ll likely come across both, but I recommend you use ES6 as it is faster and more up-to-date than ES5.

As such, I’ll only cover ES6 functions in this guide.

Dissecting ES6 function syntax

This is the function we wrote earlier. It is written with ES6 syntax.

var myFirstFunction = () => {
var userName;userName = window.prompt("What is your name?");
alert("Hello" + userName); 
};

Let’s explore the parts of the function above to better understand function syntax.

First, let’s simplify things by removing the statements within this function since they are not necessary to understand function syntax.

This is what the function looks like without the statements.

var myFirstFunction = () => {
};

You should be familiar with the following line:

var myFirstFunction =

This is simply creating a variable named myFirstFunction.

Where things get interesting is the portion of the code below that follows var myFirstFunction = as it is the unique syntax related to functions in ES6:

() => {
};

() allows you to pass parameters into the function. You write the parameters between the (). There are no parameters in the function example we used above, so it’s empty and looks like this:

()

Here’s a function would look like with a parameter X added:

var myFirstFunction = (X) => {
};

Notice the X is within the (), this means parameter X can now be used when calling the function.

I’ll explain more about calling functions and calling functions with parameters later in this guide.

=> tells JavaScript that you want to create a function. That’s it. Nothing too complex here.

{} is the function body, everything between the opening { and closing } make up the function. You can put any kind of statement within the function body, from logic to variable declarations and more. When you call the function the browser will execute each line within the {}.

Calling a function in ES6

After you’ve written your function you’ll now need to tell your browser how to execute the function, you do this by calling the function with the function name followed by a ().

Here’s what you would type if you wanted to call the function we created previously named myFirstFunction:

myFirstFunction()

That’s it, pretty simple.

Here’s what you would type to call it with a parameter of 5:

myFirstFunction(5)

Practicing writing and calling a function in ES6

Now that we’ve dissected the syntax of a function and how to call it, let’s write a function line by line and call it in our console.

I’m thinking a function that pops up a simple welcome message will be a good example. Let’s write this function.

Begin by opening up this page in a new browser window and placing it beside this window with the JavaScript console open.

Type the following function in your console and press enter. Don’t forget the spaces after Hello and before welcome to my website!

var welcomeMessage = (x) => {
alert("Hello " + x + " welcome to my website!");
};

You should see something like this:

A screenshot demonstrating JavaScript functions.

Ok, let’s now call the function with a parameter passed into it.

Type the following into your console and press enter:

welcomeMessage("Dan");

You should see something like this:

A screenshot demonstrating JavaScript functions.

Pretty straightforward right?

I know the function syntax can seem confusing at first, but writing enough examples out will ensure you master this concept.

If you now feel comfortable with functions, congratulations! You are now well on your way to an intermediate level of JavaScript knowledge.

If you are still unclear about some aspects of the function syntax I’d suggest having another read of this guide, otherwise post any questions you may have in the comment section below and I’ll be happy to assist.

Next up, let’s take a look at lists in JavaScript. An underrated but extremely useful data type.