A function in JavaScript is a block of code that contains a group of instructions to perform a particular task.
In other words, a function groups a number of program statements in a single unit to perform a particular task.
For example, write() is an in-built JavaScript function that is used to print a statement.
A function does not execute until it is called. That is, a function will execute when “someone” invokes it.
When a function gets called, the code inside the function executes. We can call a function from other parts of the program when needed.
In JavaScript programming, we can define our own functions, called user-defined functions as well as use built-in functions already defined in JavaScript. For example, we have used the in-built functions, such as:
- document.write()
- window.alert()
- parseInt()
When to Use Function in JavaScript?
A function makes the code reusable multiple times to perform several tasks in a program. It eliminates the need to write the same piece of code again and again in the entire program. It saves the programmer time for writing a lot of repetitive code.
For example, a function can be useful when we need repeatedly to perform a calculation or action throughout a program. We can define the function to write messages to the user, calculate the total tax on an order, or estimate the shipping date for an item.
Another use of JavaScript functions is to link actions on a web page with JavaScript code. For example, button presses, mouse clicks, text selection, and other user actions can invoke functions by including suitable tags in HTML source for the page.
With the help of functions, we can break a huge program into several small and manageable functions which eventually reduces the redundancy.
Like any other programming language, JavaScript also allows us to write logic inside functions that we are going to learn in this tutorial.
JavaScript Function Syntax declaration
Like variables, we must create a function in the program before you can call it. Creating a function in a JavaScript program is pretty easy.
We define a function by using the function keyword, which is followed by a unique name of the function, a list of parameters (that could be empty or optional), and a statement block surrounded by curly braces that contain their associated code.
The general syntax to declare a function in JavaScript is as follows:
Function nameOfFunction(parameters-list) { // Lines of code to be executed to perform a specific task. }
From the above syntax,
1. The nameOfFunction should be immediately after the function keyword, as shown in the figure.
2. All the function names must be unique. Function names also should not conflict with reserved words which JavaScript uses itself. For example, you cannot define a function named while. You should not define two functions with the same named display in the program.
3. The code between a pair of curly brackets is called a function body.
4. Parameter-list (parameter1, parameter2,… parameterN) is a set of local variables that receive values passed to the function when the function gets called. That is, function parameters receive argument values when it is called by someone.
We can pass different argument values while calling it. We can use the values of the passed values inside the JavaScript function and we can also do the manipulation on these arguments.
5. A function can return a value, but the return statement is optional.
An example of a very simple function definition is as follows:
<script> function sayHello() { document.write("hello!"); } </script>
In this example, the function name is sayHello. The parameter list is empty that tells the function is not receiving any argument value.
Note: JavaScript is a case sensitive. You must write function keyword in lowercase letters.
Types of Functions in JavaScript
There are two types of functions in JavaScript like any other programming language such as C, C++, and Java.
- Predefined functions
- User-defined functions
In this tutorial, we will concentrate on user-defined functions.
Predefined Functions in JavaScript
There are hundreds of predefined functions built into JavaScript to perform a variety of tasks. Some of the important predefined functions are as follows:
1. alert(): This function displays an alert dialog box on the browser.
2. confirm(): This function displays a confirmation dialog box and asks the user to choose one from two options.
3. prompt(): The prompt() function displays a prompt dialog box on the browser and prompts the user to enter input.
4. write(): The write() function used to write something on the document.
5. Date(): This function used to get the current date and time.
6. select(): The select() function used to select the pointed object.
7. parseInt(numString): This function converts a string into an integer.
8. parseFloat(numString, radix): This function converts a string into floating point number.
9. sqrt(number): This function used to get the square root of any number.
10. pow(number): It used to get the power of an integer.
These are some examples of inbuilt “top level” functions in JavaScript. We will learn more about in-built functions in the further tutorials.
User-defined Functions in JavaScript
Like any other robust programming language, JavaScript also allows to create your own user-defined function. With the help of user-defined function, we can organize JavaScript code into discrete and reusable chunks.
The syntax to define a user-defined function has shown above section.
JavaScript use-defined function does not execute when the web page loads. So it should place in the head section of an HTML document.
This is because the function must define and load into the memory before the function called by JavaScript code or an event handler.
Calling Function in JavaScript
In order to run or execute the set of statements (code) in the function block (i.e. function body), we will have to call the function explicitly.
That is, the code inside the function will execute when we call the function. Calling a function is known as invoking a function in JavaScript.
Without function call, the function created does nothing. That is, the function will not execute the code inside the block of function.
To call a function in a JavaScript program, just write its name, and followed it by a pair of opening and closing parentheses. The general syntax to call a function in JavaScript is as follows:
functionName([arguments]); For example: sayHello();
Calling sayHello() executes the body of the function, which is document.write(“hello!”);, and a text will display on the next line: hello!.
There are some scenarios where we can call a function in JavaScript program. They are:
a) When an event occurs. That is, when a user clicks a button.
b) When the function called (i.e. invoked) from another JavaScript function.
c) Automatically (self called).
Note: Function names in JavaScript are case-sensitive. If you define a function named Display with a capital letter, be sure you use the same name when you call the function, otherwise the function will not work. For example, if we define a function named Display() then call it using Display().
Example Program based on JavaScript Function
1. Let’s create a JavaScript program in which we will define a user-defined function to display a message in the head section of HTML webpage. We will call the function later in a script element in the body section of webpage.
Program code 1:
<html> <head> <title>Functions in JavaScript</title> <script> var msg = "Welcome to Scientech Easy"; // Function declaration. function display() { document.write(msg); // It will print statement in web browser. } </script> </head> <body> <script> display(); // Calling function. </script> </body> </html>
In the preceding program, we have created a function named display() in which we have written a statement to display a message “Welcome to Scientech Easy” by using the document.write();.
To print that statement, we simply need to write the name of that function as shown in the above script code. When we call the function, JavaScript interpreter transfers the control of execution to the function for executing code. The following output will display on the browser.
Output: Welcome to Scientech Easy
We can call this function any number of times throughout our code. It saves a lot of time and redundant coding.
2. Let’s take an example program where we will create a function and will call the function when we will click on the button. It will simply print a statement on the browser’s window.
Program code 2:
<html> <head> <title>Function Definition and Calling</title> <script> var msg = "Welcome to Scientech Easy, Dhanbad"; // Function declaration. function display() { document.write(msg); // It will print statement in web browser. } </script> </head> <body> <p>Please, click on the button to call a function</p> <input type = "button" onclick = "display()" value = "Click me"> </body> </html>
When we execute the above HTML code, the following output will be display on the browser’s window.
Output: Welcome to Scientech Easy, Dhanbad
In this HTML program, we are calling the JavaScript function on click event on the button, which displays a statement that is picked up from the head section of the HTML code where we have defined JavaScript function.
Calling Functions from other Functions in JavaScript
We can call a function from another function. It is useful if for example, a specific function contains too many lines of code and may be difficult to read.
So, we can break too many lines of code into separate smaller functions and then call them from one main function. From it would make easier to read.
Let’s create a JavaScript program in which we will call functions inside one main function.
Program code 3:
<head> <title>Calling functions from other functions.</title> <script> // Function 1. function runFirst() { document.write("function 1", "<br>"); } // Function 2. function runSecond() { document.write("function 2", "<br>"); } // Function 3. function runThird() { document.write("function 3"); } // Calling functions inside from function. function main() { runFirst(); runSecond(); runThird(); } </script> </head> <body> <p>Please, click on the button to call main function</p> <input type = "button" onclick = "main()" value = "Click me"> </body> </html>
Output: function 1 function 2 function 3
In this program, when you will click on button, it will call main() function. The main() function will automatically execute other functions one right after other. It is also a lot easier instead of calling each function independently one by one, assuming that they need to execute all functions at once.
Program code 4:
<html> <head> <title>Calling functions from other functions.</title> <script> // Variable declaration. let x = 20; let y = 30; // Function 1. function addition() { let sum = x + y; document.write("Sum = " +sum, "<br>"); } // Function 2. function subtraction() { let sub = x - y; document.write("Sub = " +sub, "<br>"); } // Function 3. function multiplication() { let multiply = x * y; document.write("Multiply = " + multiply, "<br>"); } // Function 4. function division() { let div = x / y; document.write("Div = " +div); } // Calling functions inside from function. function main() { addition(); subtraction(); multiplication(); division(); } main(); // calling function. </script> </head> <body> </body> </html>
Output: Sum = 50 Sub = -10 Multiply = 600 Div = 0.666666
Self-Invoking Functions
We can also make a function expression “self-invoking or self executing”. We can do it by enclosing entire function within { } parentheses and adding the ( ) parentheses operator at the end of the expression.
It means that function expression will automatically execute one time when the browser first loads the script. The syntax of self-executing function expression looks like this:
(function() { // code to be executed. })();
Self-invoking functions are widely used to execute the code when the script gets loaded by browser. We cannot self-invoke a function declaration.
Let’s take an example program based on the self-invoking function in JavaScript.
Program code 5:
<html> <head> <title>Self-invoking function</title> <script> (function() { document.write("Hello! I invoked myself"); })(); </script> </head> <body> </body> </html>
Output: Hello! I invoked myself
In this tutorial, you learned how to declare a function in JavaScript with example programs. Hope that you will have understood how to call a function in JavaScript.
Thanks for reading!!!
Next ⇒ How to call function in JavaScript⇐ PrevNext ⇒