1.7 - Return
Review
Computers take input, process it, and give output.
Code is run line-by-line, in the order you write it.
We can "chunk" code into smaller sub-programs called functions.
Functions can receive parameters in order to process given data.
The Return Statement (slides are here) (interactive video of the lesson is here!)
It's extremely convenient to pass arguments as parameters to a function:
let x = Math.pow(3, 6);
console.log("3^6 is", x);
Q. How is Math.pow() giving an answer back?
Functions are not just a one-way process. They can return a value back for further processing. Let's recreate the Math.pow() function using the newly created double-star shortcut.
function pow(base, exponent) {
// The math is simple enough
let answer = base**exponent;
console.log(answer);
}
But that prints the answer to the console. Boring!
We want the answer back so we can use it.
That's where the statement return comes in.
function pow(base, exponent) {
let answer = base**exponent;
// Give the answer back to the caller
return answer;
}
Example: Using our new function
let example = pow(2, 3);
console.log(example); // Prints 8
console.log(pow(5, 4)); // Prints 625
console.log(pow(pow(2, 3), 2)); // Prints 64
Your Task
Return statements are easy to practice. Let's create lots of functions in the Replit project for the lesson.