Functions in Javascript
Introduction
In our journey through JavaScript, we’ve covered variables, conditionals, loops, and strings, which are all essential building blocks for writing effective code. As we continue to write more and more complex programs, however, we need a way to organize our code make it resuable. This is where Javascript functions
come in. In this lesson, we will dive deep into the world of functions and learn how to define and call them, pass arguments, and return values.
Overview
By the end of this lesson, you should be able to:
- Define and call functions in JavaScript
- Understand the difference between function parameters and arguments
- Return values from functions
- Use functions to solve common programming problems and make code more efficient
Defining Functions
In JavaScript, functions are reusable blocks of code that perform a specific task or set of tasks. Functions help make our code more modular and “compact”. As you begin to write more and more complex programs, you will find that organizing your code in functions makes it much easier to debug and understand. Here is the syntax of a function:
function functionName() {
// code to be executed
}
As you can see, the function begins with the keyword function
, followed by the name of the function and parentheses. In the curly brackets is where we will be writing our code to be executed when the function is called.
The code above would write us a function, but we can’t actually execute the code unless the function is called. Here is how we call a function in JavaScript:
function functionName() {
// code to be executed
}
functionName() // Calls our function
To call a function, just write the name of your function with parentheses around it. Here is an example of us writing a function called sayHello
and then calling it:
function sayHello() {
console.log("Hello World!")
}
sayHello() // Logs "Hello World!" to the console
In line 5, the function sayHello
is being called, which executes any code inside sayHello
. In this case, Hello World!
is being logged to the console as a result of calling the function. Let’s look at one more example of a function and its function call:
function alertUser() {
alert("Welcome to our website!")
}
alertUser() // Going to alert the user "Welcome to our website!"
In the example above, we have a function called alertUser
. Take a look at line 5 where we are calling the function by doing alertUser()
. What do you think is going to happen?
Remember that when we call a function, whatever is inside of that function is going to get executed. In this instance, the expression alert("Welcome to our website!")
is going to get executed. Now what if we had multiple function calls? What do you think would happen? Take a look:
function sayHello() {
console.log("Hello")
}
sayHello()
sayHello()
sayHello()
sayHello()
If you guessed that "Hello"
would show up in the console 4 times — you are correct! Every time we call a function, whatever code inside the function will be executed. So when we called sayHello()
four times, we are essentially calling console.log("Hello")
four times since that’s what is being called inside our function.
Using Parameters
What we learned in the last lesson was the very basic form of functions in Javascript. We can make our functions more responsive and more complex by adding parameters. Here is the syntax for when we use parameters in our functions:
function functionName(param1, param2) {
// Execute some code
}
functionName(param1, param2) // When calling our function, we pass in parameters
This is better understood with an example. Here is a basic function that will take a name
variable as an input and then log a greeting based off of that variable.
function greetUser(name) {
console.log("Welcome to the website " + name)
}
greetUser("Bob") // Logs "Welcome to the website Bob"
greetUser("Rahul") // Logs "Welcome to the website Rahul"
Take a look at how we call our functions in lines 5 and 6. We are still calling the function normally, but also giving a parameter. On line 5, we are setting the value of name
to be Bob
, when it is run through the function. Same with line 6, except our name
variable is set to rahul
.
Let’s look at a bit more complex example where we are taking two parameters and adding them together:
function addTwoNumbers(num1, num2) {
const sum = num1 + num2
console.log("The sum is " + sum)
}
addTwoNumbers(4,3) // Logs "The sum is 7"
addTwoNumbers(298, 121) // Logs "The sum is 419"
In this example, we are taking in two numbers num1
and num2
as parameters. When we call our function (in lines 6-7), we give two numbers as a parameter and then our function will add them and log them! Let’s look at one more example which converts millimeters to meters
function millimetersToMeters(millimeters) {
let meters = millimeters / 1000
console.log(`${millimeters} millimeters is equal to ${meters} meters.`)
}
millimetersToMeters(10000) // Logs "10000 millimeters is equal to 10 meters"
millimetersToMeters(8753) // Logs "8753 millimeters is equal to 8.753 meters"
Here, we are taking millimeters
as a parameter, and then converting that to meters by divding it by 1000. When we call our functions (lines 6-7), we pass in a parameter to be our value for millimeters
Returning Values
The last thing we need to understand when writing functions are return values. In JavaScript, a return value is the value that a function gives back after it’s done running. It’s like a gift that the function sends back to whoever called it. You can think of it as a way for the function to share information with the rest of the program.
Since it is a new keyword, let’s take a look at the syntax for the return
statement.
function addNumbers(num1, num2) {
const sum = num1 + num2;
return sum;
}
console.log(addNumbers(3,4)) // Logs 7
console.log(addNumbers(12,33)) // Logs 45
Take a look at line 3. The line of code return sum
is where we specify the value that the function will return to the caller. After performing the necessary computations, the function will return the value of the sum variable to the caller. This allows the result of the function to be used in other parts of the program or stored in a variable for later use.
If we had just done console.log(sum)
in line 3, we might be able to see the sum, but we won’t be able to actually use it anywhere. It’s generally good practice to return a value from a function so that it can be used in later parts of the code if needed.
Let’s see one more example!
function findLargerNumber(num1, num2) {
if (num1 > num2) {
return num1;
} else if (num2 > num1) {
return num2;
} else {
return "They are equal"
}
}
findLargerNumber(5,7) // Returns 7
findLargerNumber(12,12) // Returns "They are equal"
Here we have a function named findLargerNumber
which takes in two numbers as paramaters. We first start by checking whether num1
is greater than num2
. If it is, we will return num1
. If num1
is not greater than num2
, we will move onto the else if
statement where we check whether num2
is greater than num1
, and if it is, we will return num2
. Finally, if none of those conditions are true, then we know that both of the numbers have to be equal, so we return the string "They are equal"
.
So far, we have just seen how we can return values, but we haven’t seen where this is actually applicable. The main point of functions returning a certain value is so that the value can be used elsewhere. Here is an example showing us using the functions add
, subtract
, divide
, and multiply
in the function calculator
. Take a look below(the code may look a bit long, but we’ll take our time to go over it!)
function add(num1, num2) {
return Number(num1) + Number(num2)
}
function subtract(num1, num2) {
return num1 - num2
}
function divide(num1, num2) {
return num1 / num2
}
function multiply(num1, num2) {
return num1 * num2
}
function calculator() {
let operation = prompt("Choose an operation: add, subtract, divide, multiply")
let firstnumber = prompt("What is the first number?")
let secondnumber = prompt("What is the second number?")
if (operation === "add" ) {
// Calling "add" function
let addedNums = add(firstnumber, secondnumber)
console.log(addedNums)
} else if (operation === "subtract") {
// Calling "subtract" function
let subtractedNums = subtract(firstnumber, secondnumber)
console.log(subtractedNums)
} else if (operation === "divide") {
// Calling "divide" function
let dividedNums = divide(firstnumber, secondnumber)
console.log(dividedNums)
} else if (operation === "multiply") {
// Calling "multiply" function
let multipliedNums = multiply(firstnumber, secondnumber)
console.log(multipliedNums)
} else {
alert("Oops, you typed in something wrong! Try again.")
}
}
Note:
- We added a space in between all the
else if
statements so it’s easier to read. The code will work fine regardless of the spaces. - You may notice that in the
add
function, we are sayingNumber(num1)
instead of justnum1
like the other functions. The reason why is because JavaScript is a bit weird when it comes to adding Strings. When JavaScript adds strings together, instead of actually adding them, it’ll concatenate them instead. Without theNumber()
in the function, if we did something likeadd(15,15)
, we would get1515
instead of30
- We added a space in between all the
Wow. There’s a lot to unpack here, so let’s go through this step by step. The first things that we need to understand are our operation functions. On lines 1 – 15, we can see the add
, subtract
, divide
, and multiply
functions. All of these functions take in two numbers as parameters and then return their specific operation on those two numbers. For example, the function subtract
will return the subtraction of num1
and num2
.
Going back to our operation functions, notice how we are not using our returned values anywhere? This is where the calculator
function comes in. Let’s start by taking a look at the first 3 lines of calculator
. Lines 18 – 20. In these lines, we are asking the user for which operation they want to do, and then we ask the user for two numbers to apply the operation on.
Lastly, we have the else if
loop going from lines 22 – 40. These lines are the most important ones to understand because we are using our operation functions to get the value of the operation that the user asked for. Let’s say the user said they wanted to add. We would next get the two numbers that the user wants to add with these lines:
let firstnumber = prompt("What is the first number?")
let secondnumber = prompt("What is the second number?")
Once we have the operation and the two numbers, we move onto the else if
loop. The first statement says if (operation == "add")
. We know the user wants to subtract, not add, so we’ll skip over that entire block. Next we move onto the condition if (operation == "subtract")
. Since the user wanted to subtract, whatever is inside this will be executed. Take a close look at line 29. Here, we are calling the subtract
function, and passing in the firstnumber
and secondnumber
values as parameters. subtract
is going to return the value of firstnumber
– secondnumber
and that value is stored in subtractedNums
. Finally, we log subtractedNums
to the console.
Understanding how to use functions in other functions can be a bit confusing at first. It is highly encouraged to paste in the code above by clicking copy
in the top right and playing around with the code/see how it works. Make sure that when you paste in the code, you’re calling the function. The code above does not have a function call to calculator
. You can add one by pasting in this line of code:
calculator() // Calls the function "calculator"
Note:
- A function that does not include a return statement will return the value
undefined
- A function can only return 1 value at a time (remember that lists can be returned too!)
- Any lines of code after a return statement will not be executed, the function will be halted.
- A function that does not include a return statement will return the value
Function Scope
Before we start practicing writing functions, there is still one more thing left for us to understand and that is function scope. In JavaScript, function scope means that any variable or function created inside a function can only be used within that function or inside nested functions. This means that any variable or function created inside a function can’t be accessed or used outside of that function.
Here is an example showing us function scope:
function myFunction() {
let x = 20
console.log(x)
}
myFunction() // This will log 20
console.log(x) // This will log a error
In this example, x
is defined as 20
within the function, but when we try to log it outside the function (line 7), you can see that we get an error. This is because when we define variable inside of functions, they can not be accessed out of the function they are defined in.
Here is another example that will help better visualize function scope:
let x = 10 // Defined in GLOBAL scope
function myFunction() {
let x = 20 // Defined in function scope
console.log(x)
}
myFunction() // Logs 20
console.log(x) // Logs 10
When we declared x
for the first time in line 1, that x
is declared in global scope. It can be accessed and changed by any function, any line of code throughout our JavaScript file.
In line 4, when we declare x
again, that x
is declared in function scope. It can only be accessed by any code within the function it is defined in (which is myFunction()
). This is why when we log both x
‘s in lines 8-9, we get different values for x
.
Understanding function scope is important because variables and functions declared inside a function are only accessible within that function. This can prevent unexpected changes to variables and helps keep code organized.
Extra resources will be linked down below!
Practice
- Additional Resources:
- This lesson on Mozilla Web Docs over JavaScript functions on a deeper level
- This w3schools lesson goes over scope in-depth and covers global, block, and function scope.
- Let’s go ahead and practice writing functions!
- Exercise #1
- Write a function called
multiply
which takes two number parameters and then logs the multiplication of both of the numbers. - For example,
multiply(3,5)
should log15
to the console andmultiply(8,3)
should log24
to the console.
- Write a function called
- Exercise #2
- Write a function called
sumUp
which takes a list as a paramter, and then logs the sum of all the numbers in the list. - For example,
sumUp([1,2,3])
should log6
to the console andsumUp([11,1,2.3])
should log14.3
to the console. - If you’re stuck, refer back to our lesson on iterating through lists in our for loop lesson.
- Write a function called
- Exercise #3
- Write a function called
targetCount
which takes 2 paramters. The first is a list and the second is atarget
. The function will return the amount of times the target is found within the list. - For example,
targetCount(["a","b", "a", "c"], "a")
should log2
to the console andtargetCount([1,2,1,3,3,4], 4)
should log1
to the console. - If you’re stuck, think about how we can loop through our list. When we find our target in a list, we want to increment a variable and then log that variable.
- Write a function called
- Exercise #1
We know that understanding and writing functions can be hard initially. If you really don’t understand something, head onto our discord server and one of our instructors will walk you through the problem!
Find an issue/typo/error with our content? Please report it here