Welcome to another tutorial, here you will learn how to define and call a function in JavaScript.
A function is a group of statements that performs a specialized task and can be set aside and maintained distinctly from the main program. It provides ways to create reusable code packages that are more portable and easier to debug.
Below are three important advantages of using functions:
In the sections below, you will learn how to define and call functions in your scripts.
A function can be declared by starting with the function keyword, then the name of the function you want to create, and finally by the parentheses i.e. (), and lastly place the function code between curly brackets{}. Below is a basic syntax for declaring a function:
function functionName() {
// Code to be executed
}
Take a look at a simple example of a function that will show a ‘hello’ message:
Example:
// Defining function
function sayHello() {
alert("Hello, welcome to Tutorial with example!");
}
// Calling function
sayHello(); // 0utputs: Hello, welcome to Tutorial with example!
Just like the example above, once you define a function it can be called from anywhere in the document by typing its name and then a set of parentheses, e.g sayHello().
Note: it is important to know that the name used for a function must start with a letter or an underscore character and not with a number, but can be followed by more letters, numbers, or underscore characters. Just like variables names, function names are also case sensitive.
Parameters can be specified when a function is defined to accept input values at run time. Parameters behave like placeholder variables within a function and replace a run time by the values (also, known as argument) provided to the function at the time call. They are set on the first line of a function inside the set of parentheses, like this
function functionName(parameter1, parameter2, parameter3) {
// Code to be executed
}
From the example above the display Sum() function takes two numbers as arguments, by simply adding them together and then displaying the result on the browser.
Example:
// Defining function
function displaySum(num1, num2) {
var total = num1 + num2;
alert(total);
}
// Calling function
displaySum(6, 20); // 0utputs: 26
displaySum(-5, 17); // 0utputs: 12
When using a function you can define as many parameters as you like, but for every parameter you specify, a corresponding argument needs to be passed to the function when it is invoked, or else it will return an undefined value. Let's consider the example below:
// Defining function
function showFullname(firstName, lastName) {
alert(firstName + " " + lastName);
}
// Calling function
showFullname("Clark", "Kent"); // 0utputs: Clark Kent
showFullname("John"); // 0utputs: John undefined
Using ES6, you can specify default values to any function parameter. Therefore, if no arguments are provided to a function when it is called ( or invoked) these default parameter values will be used instead. In JavaScript, this is one of its unique features. This is an example:
function sayHello(name = 'Guest') {
alert('Hello, ' + name);
}
sayHello(); // 0utputs: Hello, Guest
sayHello('John'); // 0utputs: Hello, John
From the example above, before ES6, to achieve the same we had to write something like this ‘0’
function sayHello(name) {
var name = name || 'Guest';
alert('Hello, ' + name);
}
sayHello(); // 0utputs: Hello, Guest
sayHello('John'); // 0utputs: Hello, John
For more information on ES6 features, check out the JavaScript ES6 features tutorial.
The return statement makes it possible for a value to be returned to the script that called its function. The value may exist in any type, such as objects and arrays.
The return statement is placed at the last line of the function before the closing curly bracket and it ends with a semicolon, this is shown in the following example.
// Defining function
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}
// Displaying returned value
alert(getSum(6, 20)); // 0utputs: 26
alert(getSum(-5, 17)); // 0utputs: 12
Note: A function cannot return multiple values, but you can obtain similar results by returning an array of values, as demonstrated in the example below.
// Defining function
function divideNumbers(dividend, divisor){
var quotient = dividend / divisor;
var arr = [dividend, divisor, quotient];
return arr;
}
// Store returned value in a variable
var all = divideNumbers(10, 2);
// Displaying individual values
alert(all[0]); // 0utputs: 10
alert(all[1]); // 0utputs: 2
alert(all[2]); // 0utputs: 5
A function expression is another syntax for creating a function, just like the function declaration.
// Function Declaration
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}
// Function Expression
var getSum = function(num1, num2) {
var total = num1 + num2;
return total;
};
If a function expression is stored in a variable, the variable can be used as a function, as shown below;
Example:
var getSum = function(num1, num2) {
var total = num1 + num2;
return total;
};
alert(getSum(5, 10)); // 0utputs: 15
var sum = getSum(7, 25);
alert(sum); // 0utputs: 32
You should know that there is no need to put a semicolon after the closing curly bracket in a function declaration. However, function expressions should always end with a semicolon.
Tip: JavaScript functions can be stored as variables, passed into other functions as arguments, passed out of function as return values, also, constructed at run time.
For instance, the example below shows how the syntax of the 'function declaration and function expression' look alike, but differ in the way they are evaluated.
declaration(); // Outputs: Hi, I'm a function declaration!
function declaration() {
alert("Hi, I'm a function declaration!");
}
expression(); // Uncaught TypeError: undefined is not a function
var expression = function() {
alert("Hi, I'm a function expression!");
};
So, you can see from the example above, that the function declaration was executed successfully, while the function expression threw an exception when it was called before being defined.
Hence, JavaScript parses the declaration function before the program executes. The function declaration is not affected if the program invokes the function before it is defined, as JavaScript has hoisted the function to the top of the current scope behind the scenes. While, the function expression cannot be evaluated until it is assigned to a variable; so, it remains undefined when invoked.
The ES6 has introduced an even shorter syntax for writing function expression and is called the arrow function. You can refer back to the JavaScript ES6 features tutorial to learn more about it.
Variables can be declared anywhere in JavaScript, but the location of the declaration ascertains the extent of a variable's availability within the JavaScript program (i.e. the place where the variable can be accessed or used). A variable's accessibility is known as variable scope.
Usually, By default, variables declared within a function have what is known as a local scope ( meaning cannot be viewed or manipulated from outside of that function). It is shown in the example below:
// Defining function
function greetWorld() {
var greet = "Hello World!";
alert(greet);
}
greetWorld(); // Outputs: Hello World!
alert(greet); // Uncaught ReferenceError: greet is not defined
While, global scope means the declared variable will be available to all scripts, whether that script is inside a function or outside. This is an example:
var greet = "Hello World!";
// Defining function
function greetWorld() {
alert(greet);
}
greetWorld(); // Outputs: Hello World!
alert(greet); // Outputs: Hello World!