In this section, we will learn what the function is and how to use it in JavaScript.
What is a function?
A program is a combination of multiple tasks and instructions (AKA statements) that we set for that program to run.
Sometimes part of these instructions needs to be run multiple times.
For example, in a program, we might want to send the result or an operation to the browser’s console multiple times.
One option would be to write the statement that sends such output to the console in every place in the program that needs it.
This is basically a copy and paste operation because we use the same statement/s in multiple places in the same program.
Obviously it’s not a good practice and there is a better way, but before we show the better solution, first let’s see this problem in an example:
let name = "John" console.log("***Message***"); console.log(name); console.log("*****"); let lastName = "Doe"; console.log("***Message***"); console.log(lastName); console.log("*****"); let email = "[email protected]"; console.log("***Message***"); console.log(email); console.log("*****");
Output:
***Message*** John ***** ***Message*** Doe ***** ***Message*** [email protected] *****
In this example, the 3 statements mentioned below are repeated 3 times:
console.log("***Message***"); console.log(variable_name); console.log("*****");
In programming there’s a meme which says: “Don’t repeat yourself!”
This meme basically wants to say reuse your source code instead of repeating it in multiple places in a program.
If you think about it, repeating a set of statements in a program other than being a tedious task, it also brings more works in code maintenance afterward!
For example, if in the future we needed to change part of the repeated source code, we should remember all the places where this code has been used and modify all of them together.
This is one of the main reasons in which you should avoid writing repeated codes when developing a program.
On the other hand, the JavaScript’s functions can help to solve this problem.
A function is essentially a block of code (statements) that we know is going to be used in multiple places in a program.
Basically, when we know a set of statements will be used in multiple places, instead of copying them into those places of the program, we put all the instructions in one function and label it (set a name for that function).
After that, in any part of our program that we need these instructions, we only call the name of the function block and the JavaScript’s execution engine will go to that block and execute the instructions of that function.
Alright, before we get into the details of functions and its structure, let’s reactor the example above and see what it would look like if we use a function instead:
let name = "John" print(name); let lastName = "Doe"; print(lastName); let email = "[email protected]"; print(email); function print(param){ console.log("***Message***"); console.log(param); console.log("*****"); }
Output:
***Message*** John ***** ***Message*** Doe ***** ***Message*** [email protected] *****
If you look closely at this example, it’s definitely took a shorter amount of code and we didn’t repeat ourselves!
Here there’s a function block named `print` and we put the three statements that were repeated in the first example into this function.
Now, in any part of the program that needed these 3 statements, we only called the function that it contained the statements (the function `print` in this case).
The way we call a function needs more explanation, which you’ll see in the next section, but in short, when the execution engine sees the name of a function followed by a pair of parentheses; it knows that it should jump into the location where the body of the function is and run the statements in the block of that function.
After the execution of the function’s body ended, the execution engine will return to the place where the call to the function occurred and proceed to run the instructions after it.
So in this example:
- The variable `name` was created and the value `John` assigned to it.
- In the second statement, we’ve called the `print()` function and passed the value `name` as its input.
Note: functions can accept inputs and we set these inputs in the parentheses when we call them. This is exactly what we’ve done in this example. (In the next section, we will explain this in greater details).
- After calling the function, the execution engine jumps to the place in which the body of the function is defined.
- The first statement in the body of the function is to call the `console.log()` and send the message `***Message***` to the browser’s console.
- The next statement is to again call the `console.log()` and send the input value to the browser’s console.
- The last statement in this body is also to call the `console.log()` one more time and send the value `*****` to the browser’s console.
- After that, the body of the function reaches to its end and because there’s no other statement to run here, the execution engine will return to the place where the call to this function occurred.
- The execution engine will execute the next statement, which is creating a variable named `lastName` with the value `Doe`.
- In the next statement, there’s another call to the `print()` function and so the steps from 3 to 7 will be run again.
- After that, the next statement of this example will be run by the execution engine, which is creating another variable that is named `email` and is storing the value `[email protected]` in its memory.
- The last statement that the execution engine will run is another call to the `print()` function and so the steps from 3 to 7 will run again.
Notes:
- You might be wondering how the execution engine found the location of the `print` function. Or you might be asking in what order the execution engine executes the statements in the JavaScript programs. These are important questions and we answer them in two sections:
- Stack & heap section.
- Scope section.
- These two topics are very important, but before reading them, we recommend to first fully learn how functions work by reading the next couple of sections and then see the two sections mentioned above.
Declare function in JavaScript: function syntax in JavaScript
Alright, this is the structure of functions in JavaScript:
function functionName(parameters) { // code to be executed }
`function`: To create a function in JavaScript, we first start with the keyword `function`.
`functionName`: usually functions have names. The name of the function is used when we want to call that function.
Notes:
- When we use a function as the value of a variable (AKA function expression), the name of the function will be optional. In the function expression section, we will explain this in greater details.
- Also when we immediately invoke the target function (AKA IIFE), the use of the name for a function becomes optional as well. You’ll soon see what IIFE functions are and how to work with them.
`()`: when defining a function, after its name, we need to use a pair of parentheses. This pair of parentheses defines the signature of the function.
`parameters`: parameters are basically names separated via comma `,` and they are the local variables of the target function. We define one or more parameters in the parentheses of the target function to declare that this function needs one or more input values when it is being called in order to work properly. For example, if we set two parameters, that means when calling the function, we need to put two inputs (AKA arguments) to the function.
Note: functions are carefree! That means if we define 2 parameters for a function but call it with no arguments (inputs) or even more than 2 arguments (inputs) still the function works. You’ll soon see this in practice.
`{}`: Every function has a body. The body of a function starts from the opening brace `{` and ends at the closing brace `}` that comes after the pair of parentheses of that function. Within the body of a function we set the instructions that want to be run when calling that function.
Notes:
- A function can be created either inside another function or outside of any function as an independent one.
- A function that is declared inside another one can only be called within the body of the enclosing function. We will back to this topic in the closure section.
- Function declaration can happen in either part of our program. For example, at the beginning of the program or in the middle or even at the bottom of the source code.
- In JavaScript, we can design a program in a way that first calls a function and then define the body of that function. This is because of a concept named `hoisting` which is explained in later sections.
How to Call a Function in JavaScript
After we create a function, to call it, we only need the name of that function and put a pair of parentheses on the right side of that name.
Function in JavaScript Example:
function sayHi(){ console.log("Hi!"); } sayHi();
Output:
Hi!
As you can see, here we’ve created a function named `sayHi()` and after that, we’ve called the function name and put a pair of parentheses on the right side of it. When the execution engine sees this statement, it knows that we’re calling a function named `sayHi` and so it will go and find the body of that function and will execute the instructions in that body.
Alright, now that we are familiar with the structure of a function, let’s create one and call it:
sayHi("John"); function sayHi(name){ console.log(`Hello ${name}`); } sayHi();
Output:
Hello John Hello undefined
In this example, we’ve created a function named `sayHi()` that has one parameter that is named `name`. Again, a parameter is essentially the local variable of that function.
Note: As you’ll see in the next section, there are two types of variables: local and global. There are huge differences when it comes to the scope of a variable! We will get into this topic in the next section.
In the body of the `sayHi()` function, we have one statement and that is to send the input value of the function to the browser’s console via the `console.log();` statement.
Now, at the top of this program, we’ve called the `sayHi()` function with the input value (AKA argument) of “John”.
Consider this calling this way: The `name` parameter of the `sayHi` function is a local variable and when we call the function and pass an argument, this argument will be stored into that variable (`name`).
So here when we called the `sayHi()` function with the value `John`, it is stored as the value of the `name` parameter (variable).
Of course, when the execution engine sees this function call, it will go and find the body of the function and will start the execution of this function’s body.
So at this time, the statements within the body of the function runs and the value we sent to the function as its argument will be sent to the browser’s console.
After that, the execution engine will exit the function and back to where the call to the function happened and proceed to the next statements after the call to the function to run.
Note: In the scope section, you’ll see this in greater details but in short, the execution of a JavaScript program is a two steps process:
- Compiling: At compile time, the entire source code is checked and any function and variable declaration will be evaluated (registered) first. For example, here we had the `sayHi()` function declaration. So at compile time, this declaration will be resolved. This means the function will be registered in the memory and the execution engine will know that there is a function with the name `sayHi` in the memory and it can refer to it if there’s a call to that function.
Basically, at compile time, our source code from:
sayHi("John"); function sayHi(name){ console.log(`Hello ${name}`); } sayHi();
Will turn into:
sayHi("John"); sayHi();
These two statements with additional information about the location of the sayHi function’s body will be ready for the second step (the execution time).
- Execution: At the execution time, the execution engine only looks for statements to run. So here the first statement is the call to the `sayHi(“John”)` function and after resolving the call (executing the body of the `sayHi` function) the next statement is to call the `sayHi();` function without any argument.
Note: again, in the scope section, these steps are fully explained. So don’t worry if the picture is still sketchy for you.
Alright, after running the `sayHi(“John”);` statement, the next statement is calling the `sayHi()` function again, but this time without any value. This means the value of the `name` parameter (variable) this time is its default one, which is `undefined`.
Of course, the body of the function will be executed and the only statement in that function will run again.
This is the reason that we got the value `undefined` in the browser’s console when the second time the call to this function happened.
Definition of invoked function
In programming, you’ll hear many times in resources that they say `invoking a function` or `invoked function`, etc. and this basically means calling a function in order to execute its body instructions.
So in short:
- Invoking a Function: means calling a function in order to execute its body.
- Invoked Function: it means the function that already is called.
Parameter Function in JavaScript
As mentioned before, parameters are the local variables in a function! We use parameters because sometimes a function in order to work properly needs input values before even start to work!
For example, you might have a function that its job is to multiply two values to each other and then show the result on the browser’s console.
So how such a function can work if we don’t provide its initial two values?
This is where we use parameters.
For a function, we can define as many parameters as that function needs. Just remember to separate each parameter via a colon `,`.
JavaScript Function Parameters Syntax
function function_name (param1, param2, paramN){/*...*/}
Example: creating JavaScript function with parameters
function printName(firstName, lastName){ console.log(firstName + " "+ lastName); }
Here the function name is `printName` and it has two parameters.
The first parameter is called `firstName` and the second parameter is called `lastName`.
So when we want to call this function, it is expected to pass two input values to this function so that the first value will be assigned to the `firstName` and the second input value to the `lastName` parameter.
Note: passing values to parameters of a function is optional, and that means we can simply call a function but don’t pass any value to it. In a situation like this, those parameters will have their default values, which is `undefined`. You’ll learn more about this in the future lessons.
JavaScript Function Arguments
A function arguments are those values that we pass to a function when the function is being called.
So when you call a function and pass a few values as its input value, you can see that you’ve called a function and `passed a few arguments to that function`.
Example: invoking a function with arguments
const name = "John"; const lastName = "Doe"; function sayHi(firstName , lastName){ document.getElementById("link").innerText = `Hello ${name} ${lastName}`; } sayHi(name, lastName);
Besides of using a value as the argument of a function, we can also use variables and pass them as the argument of a function.
In this example, the `sayHi()` function defined two parameters or basically two local variables.
In the body of the function, the value of these two parameters will be set as the value of an element in the webpage that has an id of `link`. Because the `<p>` element has such id, its value will change when this function is called.
Also note that we have two other variables named `name` and `lastName` outside of the function. These are called the global variables, and each one has a value stored in it.
Note: a variable that is declared outside of any block (including function block) is considered a global variable, as you’ll see in the next section (The global and local variables section).
Alright, when we called the `sayHi()` function, we’ve passed the two global variables `name` and the `lastName` as the argument of the function.
So now the values that are stored in those variables are passed (copied) and stored in the parameters of the `sayHi()` function.
Basically, the value of the global variable `name`, is passed (copied) to the parameter `firstName` of the function. Also, the value of the global variable `lastName`, is passed (copied) to the parameter `lastName` of the function.
After calling the function with these arguments, the body of the function ran and the content of the `<p>` element changed and showed the values we’ve passed to the function.
JavaScript Functions Call Other Functions
Functions can call each other as well. This is as simple as calling one function within the body of another function.
Example: calling other functions within the body of other functions
const name = "John Doe"; funcOne(name); function funcOne(name){ funcTwo(name); } function funcTwo(name){ document.getElementById("link").innerText = name; }
Here, there are two functions defined in the program.
- funcOne()
- funcTwo
Both of these functions have one parameter.
In this program, we first called the `funcOne()` and passed the value of the global variable `name` as the argument of the function.
After that, the execution engine ran the body of the `funcOne()`. In this body, there’s a call to another function named `funcTwo` and also the value of the local variable `name` is passed as its argument.
So now the execution engine will move on to this second function to execute its body.
After executing the body of the second function, it will return to the first function and because there’s no other statement in the first function to run, the execution engine will exit the first function as well and returns to the place where the call to the first function happened.
After this returning, because there’s no other statement to run, the work of our JavaScript program is done.
Remember: As long as we don’t call a function, the body of that function will never run.
We can also pass a function as the parameter to another function. This is explained in the pass function as parameter argument section.
Return in JavaScript Function: return statement
Functions are also capable of returning a value as a result of calling them.
For example, you might have a function that takes two arguments, multiply those values and then returns the result.
So in order to get that result, we use a keyword called `return` in JavaScript.
If we use the return keyword and put a value on the right side of it, that value will be returned when the execution engine reached to this statement.
For example:
return value;
Note: after running the return statement, the execution engine will terminate the target function and basically will return from that function to where the call was occurred to proceed and run the next statements. More about this in the JavaScript return statement.
Example: JavaScript functions with return statement
function multiply(firstValue, secondValue){ return firstValue * secondValue; } const result = multiply(10, 10); console.log(result);
Output:
100
In this example, the `multiply` function takes two arguments, multiply them and finally it returns the result using the `return` statement.
So here in the `const result = multiply(10, 10);` statement, we’ve called this function with the values 10 and 10, and the result of this multiplication returned and stored into the `result` variable.
How to Determine Functions?
Using the typeof operator, we can determine if an identifier is pointing to a function or not.
If that identifier (variable) is in fact a function holder, then the result of calling the typeof operator will be the string value “function”, meaning the identifier is pointing to a function.
Example: determine a function via typeof operator in JavaScript
function multiply(firstValue, secondValue){ return firstValue * secondValue; } console.log(typeof multiply);
Output:
function
Parameter vs Argument in JavaScript
As mentioned before, parameters in JavaScript functions are those variables that we define for a function and are considered as the local variables of the target function. They can store the values that we pass to the target function.
On the other hand, arguments are those values that we pass to a function as its input values. So basically, the input values of a function are called arguments.
Nested JavaScript Functions
Functions can be defined inside the body of another function as well and this is known as the nested functions. Why we need a nested function and how this is actually done is covered in the closure section.
More to Read:
JavaScript IiFE: Immediately Invoked Function Expression