Functions let you write code once and use it many times. Parameters are the inputs; return sends a result back to the code that called the function.
function greet(name) {
return "Hello, " + name + "!";
}
const message = greet("Sophea");
console.log(message);How return works
returnends the function immediately.- The returned value replaces the function call, so
greet("Sophea")becomes"Hello, Sophea!". - A function without
returngives backundefined.
Code examples
function addTax(price, rate) {
const tax = price * rate;
return price + tax;
}
const total = addTax(100, 0.1);
console.log(total);Expected output
110
price is 100 and rate is 0.1, so tax is 10 and the function returns 110.
Common mistakes
Common mistake: Forgetting return
Without return the function gives back undefined, so total would be undefined instead of 110.
Check your understanding
3 quick questions about this lesson.