Home / Blog /
How to Use functions in JavaScript
//

How to Use functions in JavaScript

//
Tabnine Team /
9 minutes /
November 1, 2020

Functions are an essential component of any programming language, and JavaScript is no exception. Functions spark life into the code, making it more dynamic.

A function is a block of code designed to execute a task. This can be performing a calculation, printing something to the console, downloading a file, getting an input’s value, or more – functions are able to execute an endless variety of tasks.

A function’s code block can include multiple actions – these individual actions are like a list of instructions of how to get the task done, and when combined together they produce the function’s result.

Functions remain dormant until they are invoked (or called). If nothing invokes them, their code block, or task, will never be executed. Thus, in order to use functions in your code, you must first define a function and then invoke it.

Defining a function

To define a function:

  1. Use the function keyword, followed by the function’s name.
  2. Set its possible parameters enclosed in parentheses and separated by commas (the parentheses are required, the parameters are optional)
  3. Write the statements the function should carry out enclosed in curly brackets { }

Below is an example function:

function mult(num1, num2) {
    return num1 * num2
}
const multNum = mult(4, 5);
console.log(multNum); // Expected output: 20

In the example above, the function’s name, mult, comes right after the function keyword. This tells JavaScript that the name of this collection of actions is “mult”, and allows you to refer to it by name in code elsewhere in your application.

The same rules for naming variables apply to functions – their names can only contain letters, digits, underscores and dollar signs. No other character is allowed.

The function in the above example is expecting two parameters. The parameters’ names should indicate what type of arguments the function is expecting, but they do not impose any restrictions on the data you supply to your function. The parameter names are intended for yourself and your fellow programmers, and should be designed to make your code more readable, easy to predict, and easy to understand.

Note: Parameters are the names used while defining the function. Arguments are the values passed while invoking it. In the example above, num1 and num2 are parameters, 4 and 5 are the arguments.

Function’ core

The left curly brace signifies the beginning of the code block to be executed, and the right curly brace indicates the end of the block. Many functions also feature a return keyword, which halts function execution at that point (more on this later).

It is possible to have several statements in your function before either the right curly brace or the return statement are encountered. For example:

function mult(num1, num2) {
    num1 = num1 * 2;
    return num1 * num2
}
const multNum = mult(4, 5);
console.log(multNum); // Expected output: 40

This function has two statements between the curly braces. In the example above, the first statement doubles the value of num1, changing the action performed by our function. As a result of this, the return value is now 40 (4*2*5) instead of 20 as seen in the previous example.

Return value

The return keyword allows you to define an explicit value to be returned to the caller of your function. The code placed after the return keyword is the value that will be returned – in the above example, the value returned is the product of num1 and num2.

Every function returns something, even if the return keyword is omitted. If no return keyword is present, the function will return undefined. The following example demonstrates this in action:

function mult(num1, num2) {
    num1 * num2;
}
const multNum = mult(4, 5);
console.log(multNum); // Expected output: undefined

As we can see, when we leave out the return statement the function simply returns undefined.

Note: there are several other ways to declare functions. This approach is the most basic.

Note: functions can also be anonymous (see below).

For more information, see the section Function expressions below.

Invoking a function

Invoking a function is a simple matter of using the function’s name, followed by parentheses and any arguments needed.

You can generally recognize functions by the parenthesis that follows the function’s name. All functions can be recognized by the parenthesis after the name. This can be confusing when dealing with methods as well as functions – in the example above, log() is a console object’s method.

Note: while console.log() is a method, it is also a function. All methods are functions but not all functions are methods.

Parameters

For functions expecting parameters, you must pass in the required number of arguments for the function, with each argument separated by a comma. In the above example, the function mult() is assigned two arguments as parameters when invoked – 4 and 5.

When a function does not receive an argument for a parameter that has been specified in the function’s definition, the value of that parameter is set to undefined.

This can be seen using our example function above. If mult() is invoked using only a single argument (i.e. mult(4)), the function returns NaN (not a number). This is because the function attempts to multiply the value 4 by undefined, which is assigned to num2 as the second value is not provided when the function is invoked.

Default parameters

When defining parameters, it is possible to assign to them a default value. For example:

function mult(num1, num2 = 5) {
    return num1 * num2
}
const multNumDef = mult(4);
console.log(multNumDef); // Expected output: 20 
const multNum = mult(4, 2);
console.log(multNum); // Expected output: 8 

In the example above, mult() is being invoked twice. The first invocation has a single argument of 4 being passed, while the second invocation passes two arguments – 4 and 2. Where before passing a single argument resulted in the return value being NaN, because we’ve set a default value for the num2 parameter we will now see a numeric result. When no value is passed for an argument, the default value is used and the second parameter is assigned the value 5 instead of undefined as before. Thus, the above example gives us a numeric result for both invocations.

Optional parameters

Some functions have optional parameters, meaning the function can be properly invoked with fewer arguments than the function can receive.

By assigning a default value to a parameter, we make that parameter optional. In the original example code, before we set a default value for num2, the parameter was required and the function would not be able to complete its task without it. After setting the default value of num2 to 5, it became possible to invoke the function with only one argument, instead of 2, making the second parameter optional (e.g. mult(4)).

Any parameter can be made optional, at any point in the parameter list. This requires a modification of how we call the function, as the default behavior of function invocation is to assign arguments to parameters in-order. If we wish to use the default value for an item earlier in the list than our other arguments, we need to assign a placeholder value like undefined, null, or the empty string when calling the function (the correct argument to pass depends upon the function’s code block). This signifies to JavaScript that it should use the default value for the parameter.

For example, we can modify our mult() function so that only the first argument is optional. This is done as follows:

function mult(num1 = 4, num2) {
    return num1 * num2
}
const multNumDef = mult(undefined, 5);
console.log(multNumDef); // Expected output: 20
const multNum = mult(5);
console.log(multNum); // Expected output: NaN

While in the above example we have made the first parameter optional, you still cannot simply send a single argument – you can see in the code that calling mult(5) returns a value of NaN, indicating that the second parameter had a value of undefined. However, if we assign undefined as the first argument, the default value of 4 will be used for num1, and the expected result of 20 will be returned. This is because JavaScript knows to use the default value when num1 is undefined, assigning 5 to num1 instead.

Function expressions

Another way to create a function is by using a function expression. Take the following code, for example:

const multiply = function mult(num1, num2) { return num1 * num2 };
const res = multiply(4, 5);
console.log(res); // Expected output: 20

const multiply now points to function mult(num1, num2). This allows you to refer to the function as multiply() instead of mult() by storing the function into a variable.

If you wish to invoke function mult(), you need to use the variable which points to it, which in the above example is “multiply”.

In the code above, const res is assigned the value of const multiply which points to function mult(). Because const multiply points to function mult(), it can now accept a list of arguments – these arguments will be passed to the function’s parameters.

By assigning the function to a variable, we are no longer able to refer to the function by its original name, as you can see below:

console.log(mult(5, 6)); 
// Expected output: Uncaught ReferenceError: mult is not defined

Note: function expressions are not hoisted! See below – Hoisting.

Function expressions allow you to pass a function as an argument in another function call, as well as allowing you to store them as a value in an object. The following example demonstrates this functionality at work:

const multiply = function (num1, num2) { return num1 * num2 };
const obj = {
    myFunc: multiply
};
console.log(obj.myFunc(4, 5)); // Expected output: 20

As we see above, we first assigned an anonymous function to our constant multiply. We then created an object with a member variable – myFunc – set to the constant multiply we defined. This allows us to call the member variable myFunc as a function, and see the value returned.

As we can see above, function expressions can make your code cleaner and more readable.

Note: to invoke mult() while it is stored inside an object, you must refer to the object’s key. This key points to the function. For more information about this follow this link.

When using function expressions, the function name can be omitted.

Anonymous functions

Anonymous functions are functions with no name provided. For example:

const multiply = function (num1, num2) { return num1 * num2 };
const res = multiply(4, 5);
console.log(res); // Expected output: 20

In the code above, no name is assigned after the function keyword. That means that this code creates an anonymous function.

Function expressions can also be defined using another type of function declaration – arrow functions.

Arrow functions

Arrow functions are functions that are defined using a different syntax, one that is much shorter:

const multiplying = (num1, num2) => {
    return num1 * num2
}
console.log(multiplying(6, 3)); // Expected output: 18

The function in the example above is not only anonymous, it has the function keyword omitted as well. This definition is known as an “arrow function”.

In arrow functions, the function keyword is removed, and instead replaced with => following the parentheses containing the parameters.

If there is only one parameter, the parentheses can be omitted as well, as we see below:

const salting = val => {
    return 'Adding salt to ' + val
}
console.log(salting('fries'));
// Expected output: Adding salt to fries

When an arrow function takes no parameters, the syntax specifies that we include empty parentheses, followed by the arrow (=>), then followed by the code block for the function surrounded by curly braces:

const greet = () => {
    return 'Hello World!!'
};
console.log(greet()); // Expected output: Hello World!!

Note: Arrow functions do not have a this value.

Immediately Invoked Function Expression (IIFE)

With some minor modifications to our function definition, we can immediately invoke the function by creating an Immediately Invoked Function Expression (IIFE). These functions are invoked as soon as they are defined. This means that these functions will automatically execute their code block when they are encountered. The following example demonstrates how to create an IIFE:

(function () {
    console.log('Executing...');
})();
// Expected output: Executing...

In the example above, an anonymous function is declared. Its sole task is to print ‘Executing…’ to the console. This task will be executed once the code is read by the interpreter.

The syntax is similar to that of an anonymous function with two extra sets of parentheses. The first set envelopes the entire function (the open parenthesis stands before the function keyword, and the close parenthesis appears after the closing curly bracket which signifies the end of the code block). Immediately after the first set of parentheses comes the second set – their duty is to invoke the function.

Important facts about functions

1. Functions are Objects

In JavaScript, functions are considered Objects. However, when applying the typeof operator to a function the return value is “function”, as seen below:

const greet = () => {
    return 'Hello World!!'
};
const obj = { name: 'Kenny', age: 24 };
console.log(typeof (greet)); // Expected output: function
console.log(typeof (obj)); // Expected output: object

2. Hoisting

Functions are hoisted by the JavaScript interpreter. This means that when your code is being processed, functions – regardless of their location in the code – are being pulled “upwards” to the top of the code file. Therefore, unlike variables, you can use a function in your code before it has been declared:

console.log(mult(4, 5)); 
// Expected output: 20
console.log(num); 
// Expected output: Uncaught ReferenceError: Cannot access 'num' before initialization
const num = 4;
function mult(num1, num2) {
    return num1 * num2
}

In the examples above, the console.log() statements appear before the declaration of const num and function mult(). The usage of function mult() succeeds, while the usage of const num results in a reference error.

Note: function mult() is being invoked as a part of the console.log() execution.

Important: Only declared functions are hoisted! Function expressions are not hoisted.

Function scope

Scope is a very important subject in programming defining which variables can be accessed in which contexts.

In short, scope determines the visibility of variables within a block of code. A visible variable is a variable that can be accessed.

JavaScript has two types of scopes – Local and Global.

Functions create their own scope. Variables declared inside a function are local variables, and cannot be accessed from outside the scope of the function.

Variables declared outside of a function, by comparison, are declared in the global scope. The function itself can access any variable in the global scope, as seen below:

const car = { name: 'Alpha', distance: 60 };
function updateCarDistance(laps) {
    const lapLength = 30;
    const totalDistance = laps * lapLength;
    car.distance += totalDistance;
    return car
}
updateCarDistance(4);
console.log(car);
// Expected output: {name: "Alpha", distance: 180}
console.log(lapLength);
// Expected output: Uncaught ReferenceError: lapLength is not defined

In the example above const car is a global variable, and const lapLength is a local variable created inside the function.

The updateCarDistance() function can access the global variable const car and manipulate it (changing its distance key value). Once the function executes, the value of const car has been changed – its distance is now 180 (result of 4*30 + 60).

The variable const lapLength, on the other hand, is a local variable of function updateCarDistance() and thus is not accessible outside of the function’s scope. Therefore, the second console.log(), which is in the global scope, returns a reference error when it tries to access the variable lapLength. In the global scope const lapLength is not visible, so the code treats it as undefined.

 

Related Articles

JavaScript – Global Variable

JavaScript – Data types

JavaScript – How to Use Asynchronous Functions