Functions are the beating heart of JavaScript. They are reusable blocks of code built to perform a specific task. We can define them once and run them as many times as we need.
A Simple Analogy: Think of a coffee machine.
- Inputs (Parameters): You give it water and coffee grounds.
- The Process (Function Body): You press a button, and the machine does its work.
- The Output (Return Value): It gives you a cup of coffee.
A function is exactly like this reusable machine.
Before looking at the different types, let's break down the parts of a classic function:
// (2)Function Name (3)Parameter
// | |
function greet(name) {
// (4)Function Body: The work to be done
const message = `Hello, ${name}!`;
return message; // (5)The return value
}
// (1)Keyword
function Keyword: The word that tells JavaScript we are defining a function.greet).name).{ ... } that makes up the function's logic.return Statement: The value that the function sends back after it's done. (This is optional).In modern JavaScript, there are 3 primary ways we define functions:
This is the classic, most fundamental way to define a function.
Syntax:
function calculateSum(a, b) {
return a + b;
}
// Calling the function
let result = calculateSum(5, 10); // result is 15
With this method, we define a function (usually an anonymous one) and assign it to a variable.
Syntax: