Wondering if someone can explain the difference between calling a function & using the return keyword/statement. Feels like they do the same thing. Like if I am calculating the area of a rectangle I choose width*height in the body as long as the parameter was given, then I call the function and i have the answer. Seems like return does the same thing but with an extra step and hence it seems pointless, I know it’s not pointless and there is more to it and I can’t see it. SO, wondering if someone can please explain if anyone has time, if you can explain using an example that would be even better
A function is a repeatable block of code that is only executed when called. If you want the function to send a value back to the line of code that called the function (the caller), you need to return
the value. Depending on the language you’re using a function that doesn’t explicitly return a value will implicitly return a value that equates to nothing. JavaScript, for example, implicitly returns undefined
. Python returns None
.
Something that seems to trip up new coders is the misconception that printing a value to the console is the same as returning the value. It is not.
Here’s an example in JavaScript.
const area = function(width, height) {
return width * height
}
const area2 = function(width, height) {
const area = width * height //notice there is no return statement
}
const double = function(num) {
return num * 2;
}
//Let's call the double function using the value returned by the area function
const doubleArea = double(area(10, 12));
//Now we'll do the same using the area2 function
const doubleArea2 = double(area2(10, 12));
//Now let's see what we have
//What would you expect to be printed?
console.log(doubleArea);
console.log(doubleArea2);
Output:
240
NaNWhy did we get
NaN
(Not a Number)?
Thank you, it makes more sense now
This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.