First Thought: A function is a reusable "code machine" or a "recipe."
Imagine you have a task you need to do over and over, like making a sandwich. Instead of re-writing the instructions (get bread, get cheese, etc.) every single time, you write the recipe down once and give it a name, like "Make Turkey Sandwich."
Why do we need them? The DRY Principle: Don't Repeat Yourself. Functions let you write a piece of logic once and reuse it hundreds of times.
// 1. DECLARATION: Writing the recipe
// - `function` is the keyword.
// - `greet` is the name of our function.
// - `(name)` is the parameter, a placeholder for the input.
function greet(name) {
// The code inside the {} is the "body" of the function.
const message = `Hello, ${name}!`;
return message; // 3. RETURN VALUE: Giving back the result.
}
// 2. CALLING: Using the recipe with a specific ingredient ("Alice")
const greetingForAlice = greet("Alice");
console.log(greetingForAlice); // Outputs: "Hello, Alice!"
const greetingForBob = greet("Bob");
console.log(greetingForBob); // Outputs: "Hello, Bob!"
name). It's a placeholder."Alice").return keyword. If a function has no return statement, it automatically returns undefined.There are three main ways to create functions in JavaScript, and their differences are important.