Question about return statement

Do we use return statement for only variables or we can return with function too?
Lets say we use

function myLocalScope(a, b) {
  'use strict';
  return a + b;
}
myLocalScope(10, 20);

In this case i used only return a + b; would it work?

And would it work if i used return myLocalScope instead? Come someone give me some tips of return statements? I know only to return a function with variable declared in its statement.

Hi there,

You can return almost everything you want. You can return a value (the variable you used to return up until now) or you can perfectly use an expression, the way you did in the example.

In your snippet, though, you cannot return myLocalScope() because it’d mean an infinite loop (the function would be calling and executing itself forever), unless you place another return inside an if statement, for example. But you could even return another self-invoked function, defined inside the function’s return, to do something extra:

function myLocalScope( a , b ) {
  'use strict';
  a += b;
  return ( function( a , b ) {
    return a *= b;
  } )( a , b );
}
console.log( myLocalScope( 10 , 20 ) );

In the previous snippet, you add b to a and store the result in a. Then you return a self-invoked function (called an IIFE - Immediately Invoked Function Expression) taking a and b, multiply its previous values, and return the result. In the last line, I used console.log( ) to print the output of the function to the browser’s console.

Hope it helps. Don’t worry about the last example; you will see it clearly in the future as your experience grows.

Happy coding!

1 Like

Ok so in your example, it will first of all calculate a += b and then a *= b? And why did you use ( a , b ); after return? Is it necessery to use it after you wrote function inside of return? Im talking about return ( function(a , b) { return a += b; }) ( a , b );

Yes. The myLocalScope() will execute first, therefore the a *= b; is going to be executed first also; then the inner function gets executed. I finished the inner function with that ( a , b ) because you have to pass the arguments to the function to be executed.

Again, don’t worry right now about my snippet. I just wanted to show you how flexible a function can get. You will learn about it in time. Step by step :slight_smile: