VCF

Unit 4 · Thinking like a programmer

return vs console.log in JavaScript

console.log prints a value for you to read. return hands the value back to the code that called the function, so it can be stored or used. A function without return gives back undefined.

The mix-up

What people often think

“Showing the answer with console.log is the same as giving it back.”

What the tutor says

console.log only shows a value to you. return hands it to the code that called the function, so it can be used.

How it works

If total(20) only logs the answer, const due = total(20) stores undefined, even though the right number appeared in the console.

return console.log(price + 7) does not help: console.log shows the value and then itself returns undefined, which is what gets returned. Return the value: return price + 7.

Side by side

The mix-upJavaScript
function withShipping(price) {
  console.log(price + 7);
}
const due = withShipping(20);  // undefined
Shown, not given back.
What worksJavaScript
function withShipping(price) {
  return price + 7;
}
const due = withShipping(20);  // 27
The caller gets the answer.

Close cousins of this mix-up

The tutor watches for these in the same lesson.

  • “return console.log(...) returns the number.”

    console.log shows the value and then gives back undefined. Return the sum itself: return price + 7.

  • “Setting total to 27 is a fix.”

    That breaks for every other price. Make the function return its answer so any price works.

Practise it with a tutor watching

Functions: machines with inputs and outputs

Define a function, call it with inputs, and return a value the rest of the code can use.

20 minutes See it Build it Break it Say it
Start the lesson

Free, no account needed.