A function is a collection of statements designed to perform specific tasks, which can be managed separately from the main program. Functions enable the creation of reusable code packages that are more portable and easier to debug. Here are some advantages of using functions:
The following section will show you how to define and call functions in your scripts.
The declaration of a function starts with the function
keyword, followed by the name of the function you want to create, then parentheses ()
, and finally placing your function's code between curly brackets {}
. Here is the basic syntax for declaring a function:
Here is a simple example of a function that will display a hello message:
// Defining function
function sayHello() {
alert("Hello, welcome to this website!");
}
// Calling function
sayHello(); // 0utputs: Hello, welcome to this website!
Once a function is created, it can be called from anywhere in the document by typing its name followed by parentheses, like sayHello()
in the example above.
Note: A function name must begin with a letter or an underscore, not with a number. It can then be followed by more letters, numbers, or underscores. Function names are case sensitive, just like variable names.
When you define your function, you can include parameters to accept input values at run time. These parameters act as placeholder variables within the function; they get replaced by the actual values (known as arguments) when the function is called.
Parameters are set on the first line of the function inside the parentheses, like this:
The displaySum()
function in the following example takes two numbers as arguments, adds them together, and then shows the result in the browser.
// Defining function
function displaySum(num1, num2) {
var total = num1 + num2;
alert(total);
}
// Calling function
displaySum(6, 20); // Outputs: 26
displaySum(-5, 17); // Outputs: 12
You can define as many parameters as you want. However, for each parameter you specify, you must pass a corresponding argument to the function when it is called; otherwise, its value will be undefined
. Consider the following example:
// Defining function
function showFullname(firstName, lastName) {
alert(firstName + " " + lastName);
}
// Calling function
showFullname("Clark", "Kent"); // Outputs: Clark Kent
showFullname("John"); // Outputs: John undefined
With ES6, you can now set default values for function parameters. This means if no arguments are provided when the function is called, these default values will be used. This is a highly anticipated feature in JavaScript. Here's an example:
function sayHello(name = 'Guest') {
alert('Hello, ' + name);
}
sayHello(); // Outputs: Hello, Guest
sayHello('John'); // Outputs: Hello, John
Before ES6, to achieve the same result, you had to write something like this:
function sayHello(name) {
var name = name || 'Guest';
alert('Hello, ' + name);
}
sayHello(); // Outputs: Hello, Guest
sayHello('John'); // Outputs: Hello, John
To learn about other ES6 features, please check out the JavaScript ES6 features chapter.
A function can return a value to the script that called it using the return
statement. The value can be of any type, including arrays and objects.
The return
statement is usually placed as the last line of the function before the closing curly bracket and ends with a semicolon, as shown in the following example.
// Defining function
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}
// Displaying returned value
alert(getSum(6, 20)); // Outputs: 26
alert(getSum(-5, 17)); // Outputs: 12
A function cannot return multiple values. However, you can achieve similar results by returning an array of values, as demonstrated in the following example.
// 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
The syntax we've used previously to create functions is called a function declaration. There's another way to create a function called a function expression.
// 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;
};
Once a function expression is stored in a variable, that variable can be used as a function:
var getSum = function(num1, num2) {
var total = num1 + num2;
return total;
};
alert(getSum(5, 10)); // Outputs: 15
var sum = getSum(7, 25);
alert(sum); // Outputs: 32
Note: 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: In JavaScript, functions can be stored in variables, passed into other functions as arguments, returned from functions, and created at run-time.
The syntax of a function declaration and a function expression looks very similar, but they differ in how they are evaluated. Check out the following example:
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!");
};
As seen in the above example, the function expression threw an error when it was called before being defined, but the function declaration worked fine.
JavaScript parses function declarations before the code runs. Thus, the program can call the function before it's defined because JavaScript hoists the function to the top of the current scope. Function expressions are not evaluated until they are assigned to a variable, so they remain undefined if called before assignment.
ES6 introduced an even shorter syntax for writing function expressions called arrow functions. To learn more, check out the JavaScript ES6 features chapter.
You can declare variables anywhere in JavaScript. However, the location of the declaration determines where the variable can be accessed within the program. This is known as variable scope.
By default, variables declared inside a function have local scope, meaning they cannot be accessed or manipulated from outside that function, as 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
However, any variables declared outside of a function in a program have global scope, meaning they will be accessible to all scripts, whether those scripts are inside a function or outside. Here's an example:
var greet = "Hello World!";
// Defining function
function greetWorld() {
alert(greet);
}
greetWorld(); // Outputs: Hello World!
alert(greet); // Outputs: Hello World!