Writing Functions In JavaScript
Functions are a foundational concept in programming, and an essential part of writing code in JavaScript.
In this lesson you'll learn about the importance of functions, how to write them, and how they can be used to create programs.
We will cover:
- What a function is
- Function syntax
- Declaring functions
- Calling functions
- Function parameters
- Return values
- Arrow functions
What is a function?
A function is a block of code that is written to perform a specific task. For example, we could create a function to carry out some arithmetic, or to output the name of a user.
The advantage of functions is that they are reusable - you can define a function once and call it many times. You can call the same function with different values to produce different results.
Programs can easily grow to become very complicated. Functions are used to divide complex code into smaller, simpler pieces. This helps to make programs both easier to understand and easier to maintain.
Function syntax
Here is an example of a function and its syntax:
function doSomething() {
// Code to run
}
A function is defined using the function
keyword, followed by the function's name. You can name a function anything you'd like, as long as it conforms to JavaScript's variable naming conventions.
After the name we add parentheses ()
, followed by curly braces {}
to open a code block. We include any code to be executed within this block.
Within the parentheses ()
we can also declare any parameters that the function requires as inputs, separated with a comma:
function doSomething(param1, param2) {
// Code to run
}
Parameters are entirely optional, and we'll explore them in more detail shortly.
Declaring a new function
Let's create a function that logs a welcome message to the console. We'll start by declaring the function using the function
keyword and giving it a name:
function welcomeUser() {
}
Now let's add some functionality with a log statement:
function welcomeUser() {
console.log('Welcome, user!');
}
Calling functions
In order to execute its functionality, a function must be called or invoked. We invoke a function by referencing its name followed by parentheses ()
:
function welcomeUser() {
console.log('Welcome, user!');
}
welcomeUser(); // Welcome, user!
When we run the above code, the message 'Welcome, user!'
will be outputted to the terminal.
A single function can be invoked as many times as we wish, and it will generate the same results:
welcomeUser(); // Welcome, user!
welcomeUser(); // Welcome, user!
welcomeUser(); // Welcome, user!
Parameters
This function works, but it's not very welcoming! It would be better if the user's name was dynamic in order to output a personalised message.
This would allow us to use the same welcome message, but output a different name unique to each user. We can achieve this using function parameters.
Functions take parameters as inputs, and these parameters can be used within the body of the function.
In this case our welcomeUser()
function will accept a user's first name as a parameter:
function welcomeUser(firstName) {
console.log('Welcome, user!');
}
Now we can use string concatenation to include the user's name in the message dynamically:
function welcomeUser(firstName) {
console.log('Welcome, ' + firstName + '!');
}
When the function is invoked, we now need to provide the user's name:
function welcomeUser(firstName) {
console.log('Welcome, ' + firstName + '!');
}
welcomeUser('Frodo'); // Welcome, Frodo!
Running the code, we should see the dynamic message 'Welcome, Frodo!'
printed to the console.
Again, we can invoke the function multiple times, but now we can provide different values for the firstName
parameter:
function welcomeUser(firstName) {
console.log('Welcome, ' + firstName + '!');
}
welcomeUser('Frodo'); // Welcome, Frodo!
welcomeUser('Samwise'); // Welcome, Samwise!
welcomeUser('Bilbo'); // Welcome, Bilbo!
Using a dynamic parameter, each user receives a personalised welcome message!
In addition to function parameters, you may have also come across the term arguments. They essentially refer to the same thing, however the context matters. The term parameter is used to refer to the parameters in a function declaration, while the term argument is used to describe the parameter value when the function is invoked.
Multiple parameters
As mentioned earlier, functions can take multiple parameters. To demonstrate this, let's add a second parameter in order to output the user's full name:
function welcomeUser(firstName, lastName) {
console.log('Welcome, ' + firstName + ' ' + lastName + '!');
}
Notice that the string concatenation has also changed in order to incorporate the lastName
parameter in the message.
Now we need to provide both the user's first and last names as arguments when invoking the function:
function welcomeUser(firstName, lastName) {
console.log('Welcome, ' + firstName + ' ' + lastName + '!');
}
welcomeUser('Frodo', 'Baggins'); // Welcome, Frodo Baggins!
welcomeUser('Samwise', 'Gamgee'); // Welcome, Samwise Gamgee!
welcomeUser('Bilbo', 'Baggins'); // Welcome, Bilbo Baggins!
Returning values
In the examples so far we have simply logged a message to the console. In addition to carrying out some kind of functionality, a function can also return a value.
When a function does not explicitly return a value, it is said to return a type of void
. This is useful to know if you ever go on to learn TypeScript, or any statically typed language.
To demonstrate this we'll create a function that multiplies two numbers together and returns the result:
function multiply(x, y) {
return x * y;
}
This function takes in two numbers as parameters and multiplies them together using the multiplication *
operator.
Note that we use the return
keyword to return the result of the calculation from the function when it is invoked.
Now that the function returns a value, we can assign the value to a variable whenever we invoke the function:
function multiply(x, y) {
return x * y;
}
const result = multiply(2, 5);
To prove that this works, let's log the value of result
to the console:
function multiply(x, y) {
return x * y;
}
const result = multiply(2, 5);
console.log(result); // 10
When you run the code, you should see the number 10
outputted to the terminal.
Arrow functions
So far we have declared functions using the function
keyword. In 2015 the ECMAScript specification introduced a more concise syntax for declaring functions known as arrow function syntax.
To demonstrate, let's create a new version of our multiply()
function in the arrow function style. The most common format is to store the result of the function in a variable, so we'll start by declaring one:
const arrowMultiply;
Next we'll set this variable equal to the arrow function:
const arrowMultiply = (x, y) => {
return x * y;
}
First we write parentheses to contain the parameters, followed by the equals symbol combined with the greater than symbol =>
(commonly referred to as the 'fat arrow').
Finally we open up a code block with curly braces {}
in the same way as before, and include the necessary functionality.
Invoking arrow functions
We invoke an arrow function in exactly the same way as a standard function (the only thing that changes is the declaration syntax):
const arrowMultiply = (x, y) => {
return x * y;
}
const arrowResult = arrowMultiply(2, 5);
console.log(arrowResult);
When you execute the above code you should see exactly the same output, where 10
is logged to the terminal.
Implicit return
Currently, however, this isn't that much more concise than when we used the function
keyword.
In scenarios where only a single statement is returned from the function, like in the above example, we can remove the curly braces and return
keyword, reducing the function declaration to a single line:
const arrowMultiply = (x, y) => x * y;
In this way, the result of x * y
is implicitly returned from the arrow function. This syntax may look a little confusing at first, but don't worry! It will soon become second nature.
No parameters
If a function has no parameters, we simply remove them from the parentheses ()
, for example:
const welcomeUser = () => console.log('Welcome, user!');
Single parameter
If a function has just one parameter, we can omit the parentheses altogether:
const divideByTwo = num => num / 2;
If you're using a formatter like Prettier, the parentheses ()
may get added back in automatically when saving, depending on the rules that have been configured. However, removing parentheses when a function has a single parameter is perfectly valid syntax in JavaScript.
Summary
To recap, functions are a fundamental part of programming and are therefore a foundational part of the JavaScript language.
As you have seen, we are able to define a function once and then call it as many times as we wish.
Furthermore, functions can accept parameters and we can manipulate those parameters to generate a new value.
When a function accepts parameters, we can pass in different arguments to produce different results.