Hi @jiehengwu0380423002 - welcome to the forum!
Essentially, you would use return
whenever you need to “hand something back” to the code outside of your function.
If I borrow your examples…
function monitorCount(rows, columns) {
return rows * columns;
}
const numOfMonitors = monitorCount(3,4);
console. log(numOfMonitors);//prints 12
Here, what return rows * columns
is doing is returning the value (12
) to your variable numOfMonitors
. From here, you can use that variable elsewhere in your code.
function mCount(rows, columns) {
let area = rows * columns;
}
const a = mCount(3,4);
console. log(a);//prints undefined
Here, you’re getting undefined
because your function doesn’t return anything. As nothing comes back from mCount(3,4)
to be assigned to const a
, the constant remains undefined and JS tells you when you try to print it to the console.
function Count(rows, columns) {
console. log(rows * columns);
}
Count(3,4);//prints 12
Here, you get the output of 12
on the console because that’s what your function does. However, if we were to do
const b = Count(3,4)
console.log(b)
you would once again get undefined
because we don’t return any value from the function.
So, if your function does something useful and you want to use its output elsewhere in your code you need a return
to get that output into a variable. 