A JavaScript function is a reusable block of code that can accept inputs (arguments), perform some operation or task, and return a value.
Example of function:
1 2 3 |
function add(a, b) { return a + b; } |
In this above example, add
is the name of the function, a
and b
are the arguments passed to the function and the function returns the sum of a
and b
when it’s called.
Code example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div1"></p> <script type="text/javascript"> function add(a, b) { // add function return a + b; } document.getElementById("div1").innerHTML = add(1, 2); </script> </body> </html> |
Output: 3
The add function get invoke and sum up to 3 inside function, return value and replace content of paragraph div to 3
JavaScript function in seperate JS file:
you can also. write javascript function in a separate file and import in html file . lets create a index.js file as below:
index.js file
1 2 3 4 |
function add(a, b) { // add function return a + b; } document.getElementById("div1").innerHTML = add(1, 2); |
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div1"></p> <script type="text/javascript" src="index.js"> </script> </body> </html> |
Output: 3
In above example , the script tag attribute src will import the index.js file