JavaScript Functions
Functions are the building blocks of JavaScript. They are self-contained blocks of code that can be called and executed to perform a specific task. In this page, we will cover the syntax, example, output, explanation, use, important points, and summary of JavaScript functions.
Syntax
The syntax for creating a JavaScript function is:
function function_name(parameter1, parameter2, parameter3, ...) {
// code to be executed
return result;
}
Here:
function_name
is the name of the function.parameter1
,parameter2
,parameter3
, ... are the optional parameters that the function can accept.// code to be executed
is the code that the function executes.return result
is the value that the function returns.
Example
Here is an example of a simple JavaScript function that takes two parameters and returns their sum:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Function Example</title>
</head>
<body>
<!-- Placeholder for displaying the output -->
<p id="output"></p>
<script>
// Define a function to calculate the sum of two numbers
function calculateSum(a, b) {
return a + b;
}
// Example usage of the function
var num1 = 10;
var num2 = 20;
var result = calculateSum(num1, num2);
// Display the result in the HTML document
document.getElementById("output").innerHTML = "The sum of " + num1 + " and " + num2 + " is: " + result;
</script>
</body>
</html>
Output
Once we define the function, we can call it to execute the code inside it. For example, we can call the sum
function we defined above and pass two values:
The sum of 2 and 3 is: 5
The output of this function call will be 5
, since the function returns the sum of 2
and 3
.