Creating a function in Javascript is very similar to others programming. The function keyword is used to create functions in javascript. The function keyword is only used to create a function in JS. You don't need to use any other keyword with a function name. The function keyword defines the expression of a function in javascript programming. We define a name with a function keyword. You can define any name according to functionality. All functions' names should be different.
How to create a function in Javascript
We will use the function keyword to create a function in JS. Let's create a function in JS.
function notificaion()
{
alert('Hello , You have received a message');
}
In the code above -
function - Keyword
notification() - Function name with parenthesis
In this way, you can create a function in JS.
How to call a function in JS and HTML?
Calling a function is very easy. If you want to use the logic of function then you should call a function. Here, we create an HTML button and use the onclick event in JS.
Let's call a function on button click in HTML and JS.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> Calling a function in javascript </title>
<script type="text/javascript">
function notificaion()
{
alert('Hello , You have received a message');
}
</script>
</head>
<body>
<button type="button" onclick="notificaion()">Click Notificaton</button>
</body>
</html>
Output on button click -
Alert message = Hello , You have received a message
When you click on the button, you see an alert message in your browser. This is the process of calling a function in Javascript. You can use more JS events.
Function with arguments in Javascript
Function with arguments refers to a function that contains parameters(arguments) inside the parentheses. Function with arguments may be built-in functions or user-defined functions. In the function with arguments, we pass the arguments(variables) in function and define the value of variables at the end of the function the call.
Let's create a function with arguments-
Here, we will create a addition function which will give you sum of two numbers .
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Creating a function with arguments in JavaScript </title>
<script type="text/javascript">
function sum(a,b)
{
var sum=a+b;
alert('Sum of two numbers '+ sum);
}
</script>
</head>
<body>
<button type="button" onclick="sum(4,8)">Get Result</button>
</body>
</html>
Output-
Function with arguments is used to change the variable value at the execution time in Javascript or another programming. Now, you can understand the process of creating a function in JS, Calling a function in JS, and function with arguments in javascript.