DEV Community 👩‍💻👨‍💻

Cover image for All you need to know about functions in JavaScript
Emmanuel Fordjour  Kumah
Emmanuel Fordjour Kumah

Posted on

All you need to know about functions in JavaScript

Hello World, often in JavaScript programming, you might want to perform certain actions a number of times on your website.
For instance, you might want to display the current time when the user navigates to any page within the website.

To achieve that,typically, you write the set of statements to be executed on all the pages of your website. This is not very optimal as it introduces a lot of code repetition.

To avoid this code repetition, you should opt for a function. Function allows you to write the code only once and call it at any part of your website you need it.

In this article, we will learn about
-How to define a function.
-How to execute a function
-Function parameters,arguments, returning a function etc.

What is a function

Function in JavaScript is a procedure - a set of statements that performs a task or calculates a value.

It provides an effective way to structure larger programs,saves you repetitive coding, and makes your code easier to understand.
It also helps to give names to subprograms, and to separate these subprograms from each other.

For a procedure to qualify as a function, it should accept an input and return an output, and there should be an clear relationship between the input and the output.

What problem is function solving?

Assuming you have a website with several pages, and you want to display the current time to the user on each page he visits.
Typically,the set of statements to be executed might look like the below:

let now = new Date();
let hour = now.getHours();
let min = now.getMinutes();
console.log("Time is ", hour + ":" + min)
Enter fullscreen mode Exit fullscreen mode

These statements will be repeated on each page of the website to display the time of day. With this approach, we will introduce a lot of code repetition in our program violating the principle of DRY (Don't repeat yourself).

A better approach is to use a function. With function you write the set of statements only once, give it a name, and anytime you call the name, the block of code (set of statements) will be executed.

Defining a function

To define a function (also called function declaration), follow these steps:

An open declaration statement that includes the:

  • function keyword
  • the name of the function
  • A list of parameters to the function, enclosed in paratheses () and separated by commas.
  • An opening and closing curly braces {...} to enclose the set of statements

Syntax for a function

Below is the synxtax for a function:

function name(parameter1, parameter2, ...parameterN){
//block of code or set of statements to be executed
}
Enter fullscreen mode Exit fullscreen mode

Example of a function to display a welcome message to the user will be written as below:

function greetUser(){
alert("Welcome user"); // statement to be executed
}
Enter fullscreen mode Exit fullscreen mode

Function Declarations

Let's write the initial set of statements to display time on each page the user visits using a function

function showTime(){
let now = new Date();
let hour = now.getHours();
let min = now.getMinutes();
console.log("Time is ", hour + ":" + min)
}
Enter fullscreen mode Exit fullscreen mode

The code to show time has now been packaged as a function. Here are the parts:

  • The function keyword
  • The name giving to the function showTime
  • Parentheses () that identify it as a function
  • An curly bracket {} to enclose the body of the function. The body is where the statements to be executed or tasks to be done will be written

By convention, the function name should be in camelCase, and must start with a verb that demonstrate the action to be performed. Eg. showTime, fetchData, getResult.

Calling or invoking the function

A function will be executed only when it is called.Calling a function is also known as invoking a function.

To call a function, write its name followed by arguments enclosed in parenthesis

The syntax is as below:

functionName(arguments)
Enter fullscreen mode Exit fullscreen mode

Let's invoke or call the showTime function we have defined.

showTime()
Enter fullscreen mode Exit fullscreen mode

The call to showTime() executes the set of statements in the function's body (between the {}).

  • Writing showTime() is now the only code you'll need in order to make the whole block execute

Example 2: Defining and calling a function

The task is to show a welcome message to the vistor on each page visit.
Let's see how to achieve that using a function

function greetUser(){
alert("Welcome to my site"); //code to display the welcome message
}
Enter fullscreen mode Exit fullscreen mode

To display the welcome message, we call the function by name greetUser followed by the () like below:

greetUser()
Enter fullscreen mode Exit fullscreen mode
  • We can now use the function greetUser anywhere in the code by calling it
  • If we need to change or modify the set of statement in the body of the function,** we will modify the code in one place** (where the function was declared), and the change will take effect anywhere the function was called.

Passing data to function

When calling a function, the parentheses that is written after the function name doesn't have to be empty. If you put some data inside the parentheses, you can pass that data to the function body.

The data you are passing to the function is termed argument.

An argument is the value that is passed to the function when it is called.

functionName(argument)
Enter fullscreen mode Exit fullscreen mode

Let's call the greetUser function and pass it some argument (data)

greetUser("Emmanuel")
Enter fullscreen mode Exit fullscreen mode

In the code above, we are passing the data Emmanuel to the function's body. However, the data Emmanuel needs to be assigned to a variable before it can be used in our function. The variable is termed parameter

A parameter is the variable listed inside the parentheses in the function declaration

Expanding the greetUser function to enable us pass some data to it

function greetUser(userName){
alert("Welcome to my site" + " " + userName)
}
/* calling the function */

greetUser("Emmanuel")
Enter fullscreen mode Exit fullscreen mode
  • When the greetUser is called, the given value Emmanuel (which is the argument) is copied to the local variable userName (which is the parameter).
    • In the function's body, you can now use the passed data (argument) by simply writting the local variable (parameter)
    • Anytime the userName variable is used in the function's body, the value Emmanuel will be outputted.

As mentioned earlier, a function makes a statements of code reuasable.

  • If we want to pass a different data to the function, we only need to change the argument.
greetUser('Stephen')
Enter fullscreen mode Exit fullscreen mode
  • Now calling greetUser('Stephen') will output
Welcome to my site Stephen
Enter fullscreen mode Exit fullscreen mode

Passing multiple data(values) to a function

We can pass more than one data or value to a function, to be executed in the function's body.
With such situations, we need to have two or more local variables (parameters) to store the arguments (data to be passed).

  • In the code below, the function showMessage has two parameters: text and from
  • We then call the function showMessage() and pass the actual data we want to display when the code is executed.
  • These data are the arguments. The argument should be seperated by a , (comma)
  • Below, we passed two arguments: How is the day going?, and Emmanuel
  • The first argument How is the day going? will be copied to the first parameter text
  • The second argument Emmanuel will be copied to the second parameter from.
  • Now, anywhere we use the parameter text and from in the function's body, we are basically outputing the data or arguments we passed to the function
  • We can now use the showMessage function several times, each time passing it different data.

See the code as below

function showMessage(text,from){
alert(text + " Sender : " + from)
}
// calling the function and passing the actual data 
showMessage("How is the day going?","Emmanuel"); 

showMessage("I'll be there at 1:00pm.", "Daniel");
Enter fullscreen mode Exit fullscreen mode

Now anywhere we call the function,the output will be either

How is the day going? Sender: Emmanuel
I'll be there at 1:00pm. Sender: Daniel
Enter fullscreen mode Exit fullscreen mode

Accessing outer variables

A function can access any variable which is not defined in the code block, these are outer or global variables.

let timeOfDay = "Evening"

function greetUser(){
alert('Good' + " " + timeOfDay)
}

greetUser()
Enter fullscreen mode Exit fullscreen mode

The output will be

  • Good Evening

Passing default values

You can declare a function and give it some parameter. However, when you call or invoke the function and do not provide it with an argument or data, the local variable (parameter) will store the value undefined

For instance

function showMessage(text,from){
console.log(text + " Sender : " + from)
}

showMessage("How are you today")
Enter fullscreen mode Exit fullscreen mode
  • Because only one argument was passed to the function, the first argument will be copied to the first parameter text.
  • A second parameter from was provided, but no argument was passed to it
  • Because no data has been copied to the parameter from, the code will still run, but will assign the value of undefined to the from parameter.

The output of the function will be

How are you today Sender : undefined
Enter fullscreen mode Exit fullscreen mode

To avoid outputting undefined, we can specify the "default value" to use for a parameter if no value was passed

  • We assign a default value to use for the from parameter using the =.

Let's rewrite the code, and assign a default value of anonymous to the from parameter

function showMessage(text, from = "anonymous"){
console.log(text + " Sender : " + from)
}
showMessage("How are you today")
Enter fullscreen mode Exit fullscreen mode

Now the output will be

How are you today Sender: anonymous
Enter fullscreen mode Exit fullscreen mode

Returning a value

A function can return a value to be used as the result.
When a function is called, it implicitly returns undefined unless you clearly specify the value to return.

For example

function showMessage(message){

console.log(message)
}
const result = showMessage("Hello World");

console.log ("The return value will be ",result)
Enter fullscreen mode Exit fullscreen mode

The output will be

"Hello World"
"The return value will be " undefined
Enter fullscreen mode Exit fullscreen mode
  • In the showMessage function, we did not specify the value to be returned
  • Doing so, undefined is the value that is implicitly returned
  • The value is now stored in the result variable, hence when we console.log the returned valued witll be undefined

Specifying a return value

To specify a return value, you should use the return statement followed by an expression

return expression
Enter fullscreen mode Exit fullscreen mode

Let's see an example

function addNum(firstNum, secondNum){
  return firstNum + secondNum;
}

const retrndVal = addNum(2, 5);
console.log('The value we get back will be ', retrndVal)
Enter fullscreen mode Exit fullscreen mode

The output will be

"The value we get back will be "
7
Enter fullscreen mode Exit fullscreen mode
  • first we used the return statement followed by the expression to be evaluated firstNum + secondNum
  • The expression will be evaluated first, and since we want to output the value of the expression, we used the return statement
  • When the function addNum is called, we passed it the arguments the argumets get copied into the parameters, and the expression will be evalued.
  • Since we want to now use the value, we use the return statement which will be stored in the retrndVal variable.
  • The return statement can be in any place of the function.During execution, the function stops at the return, evaluates the expression, and the value is returned to the calling code or assigned to a variable.
  • When there is no expression following the return, it causes the function to exit immediately.

Summary

  • Function in JavaScript is a procedure - a set of statements that performs a task or calculates a value
  • To declare a function use the function keyword
  • A function will only perform a task when it is called
  • Call a function using functionName()
  • Get a value from a function using the return statement

I trust, this article gave you a better appreciation of function? Did you learn anything new, do you have some suggestions to add ? I will love to hear from you. Dont forget to share this article on all your social platforms.
Follow me on Twitter @emmanuelfkumah
Written with love from Ghana

Latest comments (0)

What image format should you use in your next project? 🤔