Function Fundamentals
JavaScript functions operate similarly to methods in languages like Java, serving as reusable blocks of code designed to perform specific tasks. However, the syntax is more concise. Unlike Java, JavaScript function definitions do not require access modifiers, explicit return type declarations, or exception lists. The core definition relies on the function keyword, a name, and a parameter list.
Three Methods for Defining Functions
There are three primary ways to declare a function in JavaScript, ranging from standard declarations to dynamic constructor instantiation.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Function Syntax Examples</title>
<script>
// Method 1: Standard Function Declaration
// This is the most common and hoisted syntax.
function displayMessage() {
console.log("Standard declaration executed.");
}
// Method 2: Function Expression
// The function is anonymous and assigned to a variable.
const computeValue = function() {
console.log("Function expression executed.");
};
// Method 3: Function Constructor
// This approach is rarely used but allows for dynamic creation.
const dynamicAction = new Function('console.log("Constructor function executed.");');
// Invoking the functions
displayMessage();
computeValue();
dynamicAction();
</script>
</head>
<body>
</body>
</html>
Parameters and Return Values
JavaScript offers significant flexibility regarding function arguments. The language does not enforce strict matching between the number of parameters defined and the arguments provided during invocation. If fewer arguments are passed than expected, the missing parameters default to undefined. Conversely, extra arguments are simply ignored by the named parameters.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Parameters and Callbacks</title>
<script>
// Demonstrating argument flexibility
function logParams(x, y, z) {
console.log("X:", x);
console.log("Y:", y); // Will be undefined if not passed
console.log("Z:", z);
}
// Passing fewer arguments is valid
logParams(10, 20);
// Return values usage
function calculateArea(width, height) {
return width * height;
}
let area = calculateArea(5, 10);
console.log("Calculated Area:", area);
// Passing functions as arguments (Higher-Order Functions)
function addValues(m, n) {
return m + n;
}
function executeOperation(operationCallback, a, b) {
return operationCallback(a, b);
}
// Passing 'addValues' as an argument
let sum = executeOperation(addValues, 15, 25);
console.log("Result of operation:", sum);
</script>
</head>
<body>
</body>
</html>