TOC
Functions:

Introduction

In programming, a function is usually defined as a piece of functionality, given an appropriate name, so that you may call it multiple times instead of having to write the same code again and again. When you factor in functionality like parameters and return values, you will truly see why functions should be an essential part of your toolbox, but we'll get to that later on.

First, let's illustrate how a function can do what we just described: Do a specific task as many times as you want to, without having to write out the same line(s) of code each time. Let's say you want to output an error message to the user under certain conditions. You could simply call the alert() method with your message:

alert("Sorry, your input is invalid - please try again!");

Writing all that text each time is cumbersome, so let's instead define a function for it.

Defining and calling a function

In JavaScript, defining a function is quite simple - just use the function keyword, followed by a name, a set of parentheses and then the block of code which the function should perform. Here's an example, based on the use case described above:

function ShowError()
{
	alert("Sorry, your input is invalid - please try again!");
}

We now have a function called ShowError(), which we can call whenever we want to show our error message to the user. And calling a function in JavaScript is as simple as writing its name, followed by parentheses, and as mentioned, you can call it as many times as you want:

function ShowError()
{
	alert("Sorry, your input is invalid - please try again!");
}

ShowError();
ShowError();
ShowError();

Function parameters

When looking at the example above, you may think: "But what if I wanted to customize the message?". That's a great question and this is where one of the real powers of functions comes in, because we can make our function a lot smarter by allowing it to take input.

When you pass information to a function in programming, its referred to as parameters (or sometimes arguments), and as the one who defines the function, you also get to define the parameter(s) it can take. Let's try defining a function with a parameter to validate user input:

function ValidateAge(age)
{
	if(age < 18)
		alert("Sorry, you have to be 18 years or older!");
	if(age > 120)
		alert("Sorry, that's too old!")
}

var age = prompt("Please input your age:");
ValidateAge(age);

We have now defined a function called ValidateAge(), and you will notice that I have added something between the parentheses: A parameter, called age. By doing so, I can now reference this parameter inside the function, as you can see me doing. Passing the parameter is just as easy - just put the value inside the parentheses, as you see me doing in the last line of the example.

Function return values

In some programming languages, the functions we have just used wouldn't be called functions, but procedures. The difference is the fact that a procedure does something without returning anything, while a function would have a return value. We don't really distinguish like that in JavaScript though - a function can return a value or not, it doesn't matter.

But the ability to return a value is another one of those things that makes functions SO useful! For instance, it allows us to rewrite our validation function from the example above to be more generic - instead of communicating with the user, let's handle that part ourselves and only use the function to tell us whether an age is valid or not. This will allow you to use the functionality in different places and react differently depending on the situation. Here's the rewritten version:

function IsValidAge(age)
{
	if((age < 18) || (age > 30))
		return false;
	return true;
}

var age = prompt("Please input your age:");
if(IsValidAge(age))
	alert("Welcome to the disco!");
else
	alert("Sorry, that age is not allowed here!");

Our function now simply checks whether the supplied age parameter is between 18 and 30 - if not, we return false, using the return keyword. Otherwise, we return true. When we call the function, we can now react to the result and have full control over what happens next.

Function scope

Scope is an important aspect of most programming languages and it's especially relevant to discuss when it comes to functions. So far, we have mostly talked about global variables, where the global part refers to the fact that the variables can be accessed from all parts of your code.

However, when you enter the inner body of a function, you also enter a new scope. When declaring a variable in a function, or when referring to one of the parameters, you are using something that is only available as long as you are inside of the function. At the same time, you can still access members (e.g. variables or other functions) declared outside of the function. Have a look at this example:

let n1 = 5, n2 = 10;

function DoStuff()
{
	let n2 = 42;
	alert("Value of n2 (function scope): " + n2);
	n1 = 42;
}

DoStuff();
alert("Value of n1 (global scope): " + n1);
alert("Value of n2 (global scope): " + n2);

I declare two variables, n1 and n2, and set them to 5 and 10. Then I define a function, where we define a variable called n2 - we already used that name, but because we're now in a new scope, we are allowed to define it again. We set the value of n2 to 42 inside of the function, alert() it to prove that it has indeed changed, and then we also change the value of the global variable n1 to 42.

Outside of the function declaration, we invoke the function and then we alert the values of n1 and n2. As you can see, only the value of n1 has changed to 42 - the global version of n2 still has the value of 10, because we made changes only to the one defined inside the function scope:

Value of n2 (function scope): 42
Value of n1 (global scope): 42
Value of n2 (global scope): 10

Understanding the scope, especially when dealing with functions and classes, is very important. Hopefully the above example has made it a bit more clear.

Summary

Functions allow you to encapsulate and reuse functionality from multiple places. The functionality of a function can be customized by accepting input in the form of parameters, and it can either just perform an action or return some kind of result based on the code of the function.

This was just a brief introduction to the most basic aspects of JavaScript functions. In the next articles, we'll dig deeper into the more advanced parts of functions.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!