Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use return, and what happens to returned data?

What is the difference between:

function bla1(x){console.log(x)}

and

function bla(x){return console.log(x)}

In which cases should I use return?

also, when a value is returned from a function, what happens to it? is it stored somewhere?

like image 499
ilyo Avatar asked Aug 25 '11 08:08

ilyo


People also ask

Why do we use returns?

A return statement, rather than output information, makes a specific value available for use in a program at the place where the function was called. For example, the function in the code that follows computes the length of a hypotenuse and return s it. Then, it is up to the programmer what to do with that value.

When should we use return in JavaScript?

There are two times you'll want to return in a function: When you literally want to return a value. When you just want the function to stop running.

What happens when you return in an JavaScript?

The return statement ends function execution and specifies a value to be returned to the function caller.

Does a return statement end a method?

Yes, it will end the method once a value is returned.


2 Answers

What is the difference

The first function returns undefined (as it does not return anything explicitly), the second one returns whatever console.log returns.

In which cases should I use return?

When the function is generating some value and you want to pass it back to the caller. Take Math.pow for example. It takes two arguments, the base and the exponent and returns the base raised to the exponent.

When a value is returned from a function, what happens to it? is it stored somewhere?

If you want to store the return value, then you have to assign it to a variable

var value = someFunction();

This stores the return value of someFunction in value. If you call the function without assigning the return value, then the value is just silently dropped:

someFunction();

These are programming basics and are not only relevant to JavaScript. You should find a book which introduces these basics and in particular for JavaScript, I recommend to read the MDN JavaScript Guide. Maybe the Wikipedia article about Functions is helpful as well.

like image 167
Felix Kling Avatar answered Oct 16 '22 11:10

Felix Kling


Return in a function is a way to pass back data from the function.

Example:

function test(){
   var test = 1+1;
   return test;
}

var feedback = test(); //feedback would now contain the value 2 if outputted.

We could also send a variable into the function and then return it back out.

Example 2:

 function test(i){
    i= i+1;
    return i;
 }

 var feedback = test(1); //feedback would also output the value 2.
like image 30
jamietelin Avatar answered Oct 16 '22 10:10

jamietelin