HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link name="favicon" type="image/x-icon" href="https://skillzam.com/uploads/system/e353194f3b7cd1b75d69c3ab88041985.png" rel="shortcut icon" />
<title>Function declaration & invoking</title>
</head>
<body>
<!--
Function : A block of code designed to perform a particular task.
Functions increases the reusability of the code.
Function Declaration : Function is defined with the function keyword, followed by a name, followed by parentheses ().
function addTwoNumbers (num1, num2) {
// Block of code
}
Function Invocation : code inside the function will execute when "something" invokes (calls) the function.
() Operator Invokes the function.
Function Return : When JavaScript reaches a return statement, the function will stop executing.
The return value is "returned" back to the "caller".
Function defined as the property of an object, is called a method to the object.
Function designed to create new objects, is called an object constructor.
-->
<h1>Demo: JavaScript Functions</h1>
<div>
<h2>Function declaration & invoking</h2>
<p id="para1"></p>
</div>
<div>
<h2>Function with "return" statement</h2>
<p id="para2"></p>
</div>
<!-- JavaScript code Starts here -->
<script>
/************************************************/
// Function declaration & invoking with no return statement
// Example : Addition of two numbers
//
function addNum () { // function declaration with no parameters
let num1 = 12; // Local Variable
let num2 = 24; // Local Variable
let sum = num1 +num2; // Local Variable sum = 12 + 24 = 36
document.getElementById('para1').innerHTML =
"Addition of two numbers = " + sum;
}
addNum(); // function invoking with no arguments
/************************************************/
// Function declaration & invoking with return statement
// Example : Sum of two numbers
//
function sumNum () { // function declaration with no parameters
let num1 = 10;
let num2 = 20;
let sum = num1 +num2;
return (sum); // function returns sum
}
let result = sumNum(); // function invoking with no arguments
document.getElementById('para2').innerHTML =
"Sum of two numbers = " + result;
</script>
<!-- JavaScript code Ends here -->
</body>
</html>