Do I have to return something in javascript functi

2020-07-02 08:47发布

In JavaScript functions, do I need to return something (true or false) ? So far, all the functions I wrote without returning anything work just fine. I'm just curious.

3条回答
做个烂人
2楼-- · 2020-07-02 09:11

No; Javascript functions are not required to return a value.

If you call a function that doesn't return a value, you'll get undefined as the return value.

查看更多
淡お忘
3楼-- · 2020-07-02 09:15

no you dont. I believe if you do

var result = iAmADefinedFunctionThatDoesntReturnAnything();

result will be undefined.

Edit, this screenshot should be illuminating (forgive the mistake when i fail to invoke f):

enter image description here

查看更多
放我归山
4楼-- · 2020-07-02 09:23

No you don't

BUT if you find yourself doing something like this

 function myFun(){
   if (1 == 2){
    return true ;
   }
 }

Now you should know you are doing something wrong in your code because it doesn't make sense that only part of the function return a value

查看更多
登录 后发表回答