Return function in Javascript and how it works?

2019-08-03 09:43发布

I'm trying to optimize and existing piece of WebGl JavaScript code, and the bottleneck of the code is at an if statement with return at the end however, the return statement doesn't seem to return anything.

function render() {
  if (object.loading) return; // there is no value after return
  // Loading is a boolean indicating if information is still being parsed from a file or not  
}

This is the first time I'm seeing code that has a return statement without a succeeding variable specified to be returned after it.

Without the return the program fails so its definitely important it is there.

Does JavaScript have a special situation in which return can be used without specifying what is being returned after it?

3条回答
不美不萌又怎样
2楼-- · 2019-08-03 10:28

It is used in this case like a get out clause, simple breaking out of the execution of the function prematurely because a required condition has not been met. Is that the entire function or is there more after the comment?

查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-03 10:32

If you use return with no value after it, it returns the value undefined. This is used to stop a function without returning a value. A function will also return undefined if it ends without a return statement.

http://jsfiddle.net/Q9UJg/1/

查看更多
The star\"
4楼-- · 2019-08-03 10:32

There is nothing wrong with not returning a value. In your example it just means that the function finishes executing on that line: code after the return is not executed if that conditional is true.

查看更多
登录 后发表回答