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

后端 未结 5 2046
野趣味
野趣味 2021-02-01 07:50

What is the difference between:

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

and

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

I

5条回答
  •  长情又很酷
    2021-02-01 08:08

    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.

提交回复
热议问题