Why JavaScript functions always return a value?

前端 未结 4 1863
傲寒
傲寒 2020-11-27 03:41

I\'m taking a course in JavaScript programming, and the instructor said that a typical JavaScript function always returns a value. Even when we don\'t provide any explicit r

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 04:29

    Even when we don't provide any explicit return value, the engines return "undefined". Is that true?

    Not really. As I understand it, a function that returns nothing...returns nothing. That said, if you assign a variable to the result of such a function invocation, then the expression will evaluate to undefined.

    EDIT

    I stand corrected. Here's the relevant portion of the spec:


    13.2.1 [[Call]]

    When the [[Call]] internal method for a Function object F is called with a this value and a list of arguments, the following steps are taken:

    1. Let funcCtx be the result of establishing a new execution context for function code using the value of F's [[FormalParameters]] internal property, the passed arguments List args, and the this value as described in 10.4.3.
    2. Let result be the result of evaluating the FunctionBody that is the value of F's [[Code]] internal property. If F does not have a [[Code]] internal property or if its value is an empty FunctionBody, then result is (normal, undefined, empty).
    3. Exit the execution context funcCtx, restoring the previous execution context.
    4. If result.type is throw then throw result.value.
    5. If result.type is return then return result.value.
    6. Otherwise result.type must be normal. Return undefined.

提交回复
热议问题