Return Values
Prerequisites: Functions
return sends a value back out of a function to whatever called it —
a function without a return gives back undefined.
function add(a, b) {
return a + b;
}
const result = add(2, 3);
console.log(result);
Expected output
5
Common mistakes
- Calling
console.log()inside a function instead ofreturning the value — that only displays the result, it doesn't hand it back for the caller to store or use further.
Practice
Write a function square(n) that returns n * n, then log
square(6).
Show solution
function square(n) {
return n * n;
}
console.log(square(6));