Functions are the "Verbs" of programming. They allow you to bundle a set of instructions, give it a name, and reuse it whenever you want.
The Input-Output Machine
Think of a function like a Toaster.
1. Input (Parameters): You put bread in.
2. Logic (Body): The coils heat up and toast the bread.
3. Output (Return): It pops the toast out.
You don't need to know how the wiring inside works to use it. You just press the button.
1. Defining a Function
Writing the function doesn't run it. It just "teaches" the computer how to do the task.
// 1. DEFINITION (Teaching)
function makeSandwich(filling) {
// 'filling' is a variable that only exists here
return "Here is your " + filling + " sandwich!";
}
// 2. CALLING (Using)
const lunch = makeSandwich("Turkey");
console.log(lunch);
const dinner = makeSandwich("PB & J");
console.log(dinner);The "Return" Confusion
Beginners often confuse console.log with return.
- console.log: Like printing a photo. You can see it, but you can't use it in code.
- return: Like giving you the photo file. You can save it, edit it, or send it to someone else.
function addWithLog(a, b) {
console.log(a + b); // Just prints
}
function addWithReturn(a, b) {
return a + b; // Gives value back
}
const result1 = addWithLog(2, 2);
console.log("Result 1 is:", result1); // Undefined!
const result2 = addWithReturn(2, 2);
console.log("Result 2 is:", result2); // 4 (It worked!)Support JS Mastery Path by checking out our sponsors.
Modern Arrow Functions
In modern JavaScript (ES6), we prefer a cleaner syntax. It behaves mostly the same but looks sharper.
// Old Way
function oldSum(a, b) {
return a + b;
}
// Modern Way
// If it's one line, you don't even need 'return' or curly braces!
const newSum = (a, b) => a + b;
console.log(newSum(10, 50));Default Parameters
What if someone calls your function but forgets the ingredients? You can set defaults.
const greet = (name = "Stranger") => {
console.log("Hello, " + name);
};
greet("Alice"); // Hello, Alice
greet(); // Hello, Stranger (Uses backup)