Return Values
Why printing is not enough
A function that prints its answer has already decided what happens to that answer. Whoever calls it gets a message on the screen and nothing else. They cannot add to it, compare it, or feed it into the next step.We usually want a function to return its answer instead. Returning hands the value back to whoever called the function, and the caller decides what to do with it.
The call expression IS the returned value
This matches the function notation from algebra exactly. If p(x) = 5x, then the expression p(4) is already the number 20, not an instruction to multiply something later. In the same way, once the function has returned, the expression farePrice(6) is already a number, and it can go anywhere a number can go.A returned value has to go somewhere
A returned value should be stored in a variable, printed, or used in another calculation. If the caller does none of those three, the value is computed and then thrown away.A function that prints gives back undefined
A function that never runs a return statement still hands something back: the value undefined. So if a function only prints its answer, and you try to store the result of calling it, what you store is undefined.return ends the function immediately
The moment a return runs, the function is over. Any code written after it in the same block never runs at all.The same idea explains a function whose if is not taken: the return inside the if never happens, the function runs off the end, and the caller gets undefined.
In the program below,
countWheels returns the number of wheels on some bikes and cars. The program stores one returned value, uses it in a calculation, and leaves the value of the last call unused. Run it, then change it and run it again:• Wrap
countWheels(3, 12) at the bottom in console.log( ).• Press Reset, then make
countWheels print its answer instead of handing it back: rewrite its body as console.log(bikes * 2 + cars * 4);.• Press Reset, then add
console.log("Counted"); inside countWheels, below the statement already there.function countWheels(bikes, cars) {
return bikes * 2 + cars * 4;
}
let wheels = countWheels(8, 9);
console.log("Wheels in the lot:", wheels);
console.log("Wheels in two lots:", wheels * 2);
countWheels(3, 12);
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.
One number type
JavaScript has only one number type. Dividing does not automatically produce a decimal the way it does in some other languages, and a whole result prints with no trailing point-zero. A decimal shows up only when the answer has a fractional part.| Code | What JavaScript prints |
|---|---|
console.log(30 / 5) | 6 |
console.log(9 / 2) | 4.5 |
console.log(1 / 8) | 0.125 |