JavaScript Function:-
JavaScript provides functions similar to most of the scripting and programming languages.
In JavaScript, a function allows you to define a block of code, give it a name and then execute it as many times as you want.
A JavaScript function can be defined using function keyword.
Syntax:
//defining a function
function <function-name>()
{
// code to be executed
};
//calling a function
<function-name>();
Example:-
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript function</h1>
<script>
function ShowMessage() {
alert(“Hello World!”);
}
ShowMessage();
</script>
</body>
</html>
Output:-
Hello World
Function Parameters:-
A function can have one or more parameters, which will be supplied by the calling code and can be used inside a function. JavaScript is a dynamic type scripting language, so a function parameter can have value of any data type.
Example:-
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript function parameters</h1>
<script>
function ShowMessage(firstName, lastName) {
alert(“Hello ” + firstName + ” ” + lastName);
}
ShowMessage(“Steve”, “Jobs”);
ShowMessage(“Bill”, “Gates”);
ShowMessage(100, 200);
</script>
</body>
</html>
Output:-
Hello Steave jobs
Hello Bill Gates
Hello 100 200