A JavaScript function is a block of code designed to perform a particular task. It is executed when "something" invokes it (calls it).
A function is defined with the function keyword, followed by a
name, followed by parentheses ().
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
The code inside a function is not executed until it is invoked. A function can be invoked when:
When JavaScript reaches a return statement, the function will stop executing.
If the function was called from a statement, JavaScript will "return" to execute the code
after the invoking statement.
let x = myFunction(4, 3); // Function is called, return value will be stored in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
The () operator invokes the function. Accessing a function without
() will return the function definition instead of the function result.
function toCelsius(f) {
return (5/9) * (f-32);
}
let value = toCelsius(77); // Invokes the function
let definition = toCelsius; // Returns the function object
return statement sends a value back to the caller
() operatorreturn statement. Without it, a function always evaluates to undefined — the code inside still runs, but the caller never gets a usable result back.
return a, b; only returns b — the comma operator discards everything before the last value. Return an object or array instead if you need multiple values.
A second example — since a function can only return one value, wrap several related results in an object:
function minutesToHM(totalMinutes) {
let hours = Math.floor(totalMinutes / 60);
let minutes = totalMinutes % 60;
return { hours: hours, minutes: minutes };
}
let result = minutesToHM(135);
console.log(result.hours + "h " + result.minutes + "m"); // "2h 15m"
Q: Can a function return more than one value?
A: Not directly, but you can return an object or array containing several values, as shown above, and unpack them at the call site.
Q: What happens if I call a function without all its parameters?
A: Any missing parameters simply become undefined inside the function — JavaScript doesn't throw an error for missing arguments.
Q: Do I need parentheses to just reference a function without calling it?
A: No — myFunction (no parentheses) refers to the function itself; myFunction() calls it. See the MDN functions guide for more on this distinction.