JavaScript Functions
Defining and calling reusable blocks of code, plus anonymous functions.
JavaScript Functions
A function is a reusable block of code that performs a specific task. It eliminates repetition and breaks complex programs into manageable pieces.
function functionName(param1, param2) {
// code to be executed
return value; // optional
}
function multiply(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = multiply(4, 3); // 12
Define once, call many times — with different arguments each time!
Function Invocation
- Function invocation — a direct call using the function name and arguments.
- Method invocation — called as a method on an object, using dot notation.
- Constructor invocation — used with the
newkeyword to create object instances.
Example: Temperature Converter
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
var result = toCelsius(77);
document.write("The temperature is " + result + " Celsius");
// Output: "The temperature is 25 Celsius"
- The return statement sends the computed value back to the caller; execution stops at
return. - Parameters are placeholders in the definition; arguments are the actual values you pass when calling.
Anonymous Functions
An anonymous function has no name. Instead, it is assigned to a variable or passed as an argument to another function.
// Anonymous function assigned to a variable
var multiply = function (a, b) {
return a * b;
};
multiply(4, 3); // 12
// Named function (for comparison)
function multiplyNamed(a, b) {
return a * b;
}
Anonymous functions are commonly used as callbacks — functions passed as arguments to other functions (event handlers, setTimeout, array methods like forEach, map, filter).
Activity — complete the code
Complete the code correctly to mark this lesson as complete automatically.
Complete the function definitions.
multiply(a, b) {a * b;}document.getElementById("demo").innerHTML = multiply(4, 3); // 12// Anonymous function assigned to a variablevar divide = (a, b) {return a / b;};