Parameters and arguments
- Parameters are the names that appear inside the parentheses when you define the function.
- Arguments are the actual values you pass when you call it.
function multiply(a, b) { // a and b are parameters
return a * b;
}
multiply(3, 4); // 3 and 4 are arguments
Default values
You can give a parameter a default value in case it is not provided:
function greet(name = "friend") {
return "Hello, " + name;
}
console.log(greet()); // "Hello, friend"
console.log(greet("Lucia")); // "Hello, Lucia"
return
The keyword return returns a value and ends the function immediately.
⚠️ Classic trap: forgetting the return. A function without return always
gives back undefined, no matter how many calculations it runs inside. If your
function "returns nothing", check this first: it's the number-one mistake for
beginners.
function isAdult(age) {
if (age >= 18) {
return true; // exits here
}
return false;
}
Anything you write after an executed
returnnever runs.
Examples
Calculating a discounted price: default value and early return
function finalPrice(price, discount = 0) {
if (price <= 0) return 0;
return price - price * discount;
}
console.log(finalPrice(100)); // 100
console.log(finalPrice(100, 0.2)); // 80