Functions are reusable blocks of code that are an integral component of any programming language.
In this tutorial, I will teach you how to use and write JavaScript functions.
Table of Contents
You can skip to any specific section of this tutorial using the table of contents below:
- How to Tell How Many Arguments a JavaScript Function Accepts
- The Difference Between JavaScript Function Parameters and Arguments
- JavaScript Methods vs. JavaScript Functions
- Final Thoughts
What is a JavaScript Function?
Functions allow us to group sets of statements in JavaScript and then call those statements to be executed together.
As a quick reminder, JavaScript statements are anything that ends with the ;
character. Examples of JavaScript statements include:
- Creating a variable
- Modifying a variable
- Performing a mathematical operation
- Printing something to the console using
console.log
Functions can accept arguments
, which are data that are passed into the function's brackets to be used in some way by the function. Functions typically return an output
, which is often dependent on the value of the argument
.
Let's consider a few examples.
An Example of a Function That Accepts No Arguments
First, let's explore an example of a function that accepts no arguments. The Math.random()
function is a perfect example of this:
Math.random()
//Returns a random number between 0 and 1
The Math.random()
function accepts no argument, and outputs a random number between 0 and 1.
An Example of a Function That Accepts One Argument
Let's consider a different function that does accept an argument. Specifically, the Math.round()
function:
Math.round(2.6)
//Returns 3
The Math.round()
function accepts a number as its sole argument, and returns the closest integer to that number.
An Example of a Function That Accepts Multiple Arguments
Functions can also accept multiple arguments. The Math.min()
function is an example of this:
Math.min(2.1, 4, 7, 9)
//Returns 2.1
The Math.min()
function accepts multiple numbers as its arguments and returns the smallest number.
Return to the Table of Contents
How to Tell How Many Arguments a JavaScript Function Accepts
If you are unsure how many arguments that a JavaScript function is intended to accept, you can run the function with no arguments and examine its output.
As an example, I created a function called myFunction
that required 1 argument, and tried to execute the function without any arguments. Here is the error message generated by my web browser:
VM453:1 Uncaught TypeError: Failed to execute `myFunction`: 1 argument required, but only 0 present.
at <anonymous>:1:11
In this case, it is clear from reading the error message that the function I am attempting to call should accept 1 argument, but I have tried to run the function with no arguments present.
Return to the Table of Contents
Important Built-In Functions in JavaScript
Before learning how to build our own JavaScript functions, I wanted to provide a broad overview of some of the most important built-in functions in the JavaScript programming language. We go through these functions one-by-one in the following sections.
The console.log
Function
We have used console.log
numerous times in this course. However, I wanted to pause for a moment to explain that there is nothing special or magical about console.log
. It is simply just another JavaScript function!
The parseInt
Function
The parseInt
function allows you to pass in a string (which contains numbers) and generate a new data point whose type is number
, with no decimal places. In other words, the parseInt
pulls an integer from a string.
In order for the parseInt
function to work properly, the number must be at the beginning of the string.
Let's examine a few cases of the parseInt
function in action:
parseInt("10")
//Returns 10
parseInt("An integer is 10")
//Returns NaN since the number is not at the beginning of the string
parseInt("10 is an integer")
//Returns 10
parseInt("10.12")
//Returns 10
parseInt("10.9")
//Returns 10, because the parseInt function simply
//reads the digits up to the decimal and does not round numbers
The parseFloat
Function
The parseFloat
function is similar to the parseInt
function except that, as its name implies, it parses a floating-point number instead of an integer.
If you're not familiar with the term "floating-point number", this is simply a computer science term that means a number that has decimals associated with it.
Let's look at a few examples of the parseFloat
function in action:
parseFloat("50")
//Returns 50
parseFloat("50.678")
//Returns 50.678
parseFloat("An example of a floating-point number is 50.3648")
//Returns NaN since the number is not at the beginning of the string
parseFloat("50.3648 is an example of a floating-point number")
//Returns 50.3648 since the number is at the beginning of the string
The Date.now
Function
JavaScript contains a built-in Date
object that includes functionality for working with dates. Within this Date
object, there is a useful now
function that returns a number representing the current point in time.
The Date.now()
function requires no arguments. Let's see how it works:
Date.now()
The output of this function is below:
1588682607399
Wait - that's not a date! What is the problem?
Well, the Date.now()
function (and all other dates in JavaScript) work in a special format that represents the number of milliseconds that have passed since January 1, 1970. There are a number of converters available on the Internet that allow you to convert a JavaScript timestamp into a human-readable date.
The scrollTo
Function
The scrollTo
function is definitely not one of the most important built-in functions in the JavaScript programming language. However, it is an excellent example of how functions can be useful without having any return associated with them.
The scrollTo
function allows you to scroll your browser's viewport to a specific spot on the screen. It takes two values: an x
coordinate and a y
coordinate.
The scrollTo
method does not return anything, but it still changes our web page in a useful way. Later on in this course you will learn how to pair similar methods with the HTML and CSS contained in a web page to create web content that changes in response to the user's activities.
Moving On
Working with JavaScript's built-in functions is interesting, but we have only scratched the surface of the capabilities of JavaScript functions.
In the next section of this tutorial, you will learn how to create your own custom JavaScript functions from scratch.
Return to the Table of Contents
How to Create Your Own Functions in JavaScript
Let's begin writing our own JavaScript functions!
To start, it's important to note that every JavaScript function shares similar syntax.
Specifically, JavaScript functions:
- Are defined with the
function
keyword - Have a name that is specified by the user
- Have round brackets that contain the function's arguments, if any exist. If the function accepts no arguments, then the round brackets should still be included but contain nothing, like this:
()
- Are composed of the function block, which begins with
{
and ends with}
and contains all of the logic included in the function
Let's create a basic function called printHello
which contains the basic logic of console.log("Hello")
:
function printHello(){
console.log("Hello");
};
Now that this function has been created, what can we actually do with it?
If you run this function declaration in a JavaScript application or in your browser's console, it will return undefined
. That does not seem very useful!
However, that's not the point. The purpose of a function declaration is to create logic that we can easily refer back to later.
After declaring printHello
, we can easily call the function by typing printHello()
. This will run the console.log("Hello");
statement and cause Hello
to be printed in our console.
Over the rest of this section, we will explore several more examples of JavaScript functions with increasing complexity so that you can solidify your knowledge of how to create custom JavaScript functions from scratch.
Example 1: The printName
Function
Let's create a function called printName
that is similar to printHello
but instead of simply printing Hello
, it will print a name that is passed into the function as an argument.
Let's start by defining the function and leaving the function block empty:
function printName(){
};
We need to specify an argument that will be printed. Let's use the keyword name
:
function printName(name){
};
Next, we need to add the console.log(name)
statement to the function block:
function printName(name){
console.log(name);
};
Just like that, our printName
function is complete!
Example 2: The calculateSalesTax
Function
Let's write a function called calculateSalesTax
that takes in the price of a sale and calculates the amount of sales tax that will be generated from the transaction.
Where I live, we have a 15% sales tax on everything we buy (oof), so that's the sales tax amount that we'll use.
To start, let's create the function with no arguments and nothing inside the function block:
function calculateSalesTax(){
};
Next, let's create an argument called price
that represents the dollar value of the transaction:
function calculateSalesTax(price){
};
The last thing we need to do is return price*0.15
, which is 15% of the value of price
and represents the amount of sales tax for the purchase:
function calculateSalesTax(price){
return price*0.15;
};
Example 3: The calculateNetWorth
Function
An individual's net worth is defined as their total assets minus their total liabilities. Let's write a function called calculateNetWorth
that accepts assets and liabilities as arguments and returns the individual's net worth.
As before, let's start by assignment our function name to an empty function block:
function calculateNetWorth(){
};
Next, let's create two arguments: assets
and liabilites
:
function calculateNetWorth(assets,liabilities){
};
The last step of creating calculateNetWorth
is to calculate the different between our two arguments, and return that value:
function calculateNetWorth(assets,liabilities){
return assets - liabilities;
};
Example 4: Revisiting The calculateSalesTax
Function
Let's revisit our calculateSalesTax
function. Specifically, let's improve the function in two ways:
- We will allow the user to specify the sales tax rate that is applicable in their location.
- If no sales tax rate is specified, then my local rate of 15% will be used.
As a quick refresher, here is the original calculateSalesTax
function:
function calculateSalesTax(price){
return price*0.15;
};
Let's add a second argument called taxRate
and replace the 0.15
in the return
statement with this variable:
function calculateSalesTax(price, taxRate){
return price*taxRate;
};
To specify a default value for the taxRate
argument, simply assign it a value within the round brackets where it is first introduced:
function calculateSalesTax(price, taxRate = 0.15){
return price*taxRate;
};
Now, the calculateSalesTax
function can be used with a single argument (price
):
calculateSalesTax(10)
//Returns 1.5
Or it can be used with multiple arguments:
calculateSalesTax(10, 0.05)
//Returns 0.5
Return to the Table of Contents
The Difference Between JavaScript Function Parameters and Arguments
In this course, we have often used the terms arguments and parameters interchangeably. This is because they are very similar elements in JavaScript. However, there are subtle differences, and I wanted to clarify this before proceeding further.
A parameter is the term that is specified when a function is originally created. An argument is a specific instance of a parameter.
Consider the following code as an example:
function calculateSalesTax(price, taxRate = 0.15){
return price*taxRate;
};
calculateSalesTax(10, 0.05)
In this example, price
and taxRate
are parameters while 10
and 0.05
are arguments.
Return to the Table of Contents
The Difference Ways to Create JavaScript Functions
JavaScript functions are extremely diverse. They can be manipulated and referred to just like every other piece of data in a JavaScript application.
This creates some interesting possibilities. Specifically, there are a number of different ways to create JavaScript functions.
We will discuss alternative methods for defining JavaScript functions in this section of this tutorial.
How to Create Anonymous Functions in JavaScript
Let's consider a function that we created earlier in this tutorial:
function printHello(){
console.log("Hello");
};
Let's transform this function into an anonymous function - which is a function without a name.
To do this, all we need to do is just remove the printHello
name from the function declaration statement:
function(){
console.log("Hello");
};
If you actually run this function in a JavaScript program, your developer tools will return the following error:
Uncaught SyntaxError: Function statements require a function name
If anonymous functions return an error in JavaScript, then why do they exist?
Anonymous functions can be combined with variable assignment to create a special type of function called a function expression
. We will discuss this type of JavaScript function next.
How to Create Function Expressions in JavaScript
A function expression is when a JavaScript function is created and subsequently assigned to a variable name using the const,
let,
or var
keywords.
Here is an example of a function expression from the Mozilla Developer Network:
const getRectArea = function(width, height) {
return width * height;
};
console.log(getRectArea(3, 4));
// expected output: 12
In the case of the printHello
function that we have been working with, we can refactor that function into a function expression like this:
printHello = function(){
console.log("Hello");
};
Notice how the right side of the equals sign in this function expression is identical to the anonymous function that we created earlier. Unlike the previous example, however, this anonymous function does not generate an error.
There is only one real difference between normal functions and function expressions in JavaScript. That difference is called hoisting
.
We will have an entire lesson later in this course dedicated to hoisting, but for now, it is sufficient to understand that hoisting allows normal functions to be used before their declaration. On the other hand, function declarations cannot be used before their declaration.
As an example, the following code returns an error, since printHello()
- which is a function expression - is being called before the function expression is declared:
printHello();
const printHello = function(){
console.log("Hello");
};
Conversely, the following code works as intended because hoisting applies to this regular JavaScript function:
printHello();
const function printHello(){
console.log("Hello");
};
Hoisting is rarely used intentionally among JavaScript developers (I have literally never used it in my career), but it is important to know as it could be a job interview question or a source of errors in your code later in your career.
One last note on function expressions. You may from time to time hear that function expressions are bad to include in your code because their error logging is not as clear as normal functions.
This was true in the past, but with upgrades to the developer tools contained in web browsers over time, this is no longer the case for modern JavaScript developers.
How to Write Arrow Functions in JavaScript
Arrow functions are a new way that developers can write JavaScript functions. They were introduced in ES6, which was a major update to JavaScript introduced in 2015 that included dozens of new features.
A nice feature of arrow functions is that they can be written on a single line. In many cases, this can make your code more readable.
Interestingly, arrow functions are anonymous functions. As we learned earlier in this tutorial, this means that they do not have a name. Arrow functions must always be assigned to a variable name using const
, let
, or var
as a result of this.
Let's see our first arrow function in action. Specifically, let's write an arrow function called poundToKG
that converts a weight measured in pounds to a weight measured in kilograms.
For context, here is how you would write this function using the syntax of a regular JavaScript function:
function poundToKG(pounds){
return pounds/2.2;
};
We'll convert poundToKG
to an arrow function step-by-step throughout the rest of this section.
The first thing we need to do is transform poundToKG
to an anonymous function. To do this, let's remove the name poundToKG
and assign the function to a const
variable that is also named poundToKG
:
const poundToKG = function(pounds){
return pounds/2.2;
};
This is an anonymous function, but it is not yet an arrow function.
To transform this into an arrow function, we need to remove the function
keyword and add the =>
characters (the arrow) after the closing round parentheses. Computer programmers often refer to =>
as a fat arrow
while ->
is referred to as a skinny arrow
. We are using the fat arrow
in this case.
Here's what our function looks like after making these modifications:
const poundToKG =(pounds) => {
return pounds/2.2;
};
The next change that we need to make is adding an implicit return
statement, which is a method for returning a value from a function without using the return
keyword. When you do use the return
keyword (as we have throughout this course), this is called an explicit return
.
We need to make a few changes to our poundToKG
variable to transform the arrow function to one with implicit return. First, move the curly bracket code block onto the same line as the variable declaration:
const poundToKG =(pounds) => {return pounds/2.2;};
Next, delete the curly brackets and the return
keyword. You will also want to delete the duplicate ;
character:
const poundToKG =(pounds) => pounds/2.2;
Lastly, if your function only takes in a single argument, you can remove the round brackets around the sole parameter like this:
const poundToKG = pounds => pounds/2.2;
This is our finalized arrow function.
As you can see, this is much more readable than our original arrow functions. Because of brevity and enhanced readability, arrow functions are excellent tools for creating basic JavaScript functions.
When looking at someone else's JavaScript code, there are three telltale signs that you can use to determine whether or not they are using implicit return:
- There is no
return
keyword. - There are no curly brackets.
- The entire function is written on one line.
Keep this in mind if you are unsure whether a statement is an arrow function in the future.
Immediately Invoked Function Expressions (IIFE)
The next type of JavaScript function that we will be discussing is the immediately invoked function expression, or IIFE for short (pronounced 'iffy'). IIFEs are used when you want a JavaScript function to run immediately on page load in the web browser.
To see how to write an IIFE, let's consider the original function poundToKG
that we worked with earlier in this tutorial:
function poundToKG(pounds){
return pounds/2.2;
};
To transform a normal function into an IIFE, you need to do three things:
- Transform the function into an anonymous function
- Wrap the entire function declaration in round brackets
- Pass in a variable in another set of round brackets at the end of the function declaration
Let's work through each of these steps one-by-one.
First, let's transform the function into an anonymous function:
function (pounds){
return pounds/2.2;
};
Next, let's wrap this function in round brackets:
(function (pounds){
return pounds/2.2;
});
Finally, let's pass in a variable in another set of round brackets at the end of the function declaration:
(function (pounds){
return pounds/2.2;
})(45);
This IIFE will run immediately on page load, returning the following value:
20.454545454545453
Return to the Table of Contents
JavaScript Methods vs. JavaScript Functions
So far in this course, I have used the terms method
and function
largely interchangeably. It is important to note that there is indeed a subtle difference.
In JavaScript, a method is a function that lives inside of an object.
A great example of this is the console.log
method that we have often used in this course. console
is an object that is built into every web browser, while log
is a method that is contained in that object.
If you're curious, you can actually look at what the entire console
object looks like by typing the console
keyword into your console:
The best way to understand how methods can live inside of an object is to see a real example.
Let's create an object called me
that contains two elements:
- An attribute called
name
with a value ofNick McCullum
- A method called
introduction
which printsHi, I'm Nick
to the console
Here's how we would do this:
const me = {
name: 'Nick McCullum',
introduction: function() {
console.log(`Hi, I'm Nick`);
}
};
Once you create the object using the code block above, you can access the name
attribute by invoking me.name
. You can also call the introduction
method by invoking me.introduction
.
If methods still seem a bit hazy, don't worry. We will see many more examples of how to create methods within objects throughout the rest of this course.
Return to the Table of Contents
Final Thoughts
In this tutorial, we covered how to create and use JavaScript functions. We will solidify this knowledge in the next section by working through numerous practice exercises.