ECMAScript® 2024 Language Specification

Draft ECMA-262 / February 15, 2024

20.2 Function Objects

20.2.1 The Function Constructor

The Function constructor:

  • is %Function%.
  • is the initial value of the "Function" property of the global object.
  • creates and initializes a new function object when called as a function rather than as a constructor. Thus the function call Function(…) is equivalent to the object creation expression new Function(…) with the same arguments.
  • may be used as the value of an extends clause of a class definition. Subclass constructors that intend to inherit the specified Function behaviour must include a super call to the Function constructor to create and initialize a subclass instance with the internal slots necessary for built-in function behaviour. All ECMAScript syntactic forms for defining function objects create instances of Function. There is no syntactic means to create instances of Function subclasses except for the built-in GeneratorFunction, AsyncFunction, and AsyncGeneratorFunction subclasses.

20.2.1.1 Function ( ...parameterArgs, bodyArg )

The last argument (if any) specifies the body (executable code) of a function; any preceding arguments specify formal parameters.

This function performs the following steps when called:

  1. Let C be the active function object.
  2. If bodyArg is not present, set bodyArg to the empty String.
  3. Return ? CreateDynamicFunction(C, NewTarget, normal, parameterArgs, bodyArg).
Note

It is permissible but not necessary to have one argument for each formal parameter to be specified. For example, all three of the following expressions produce the same result:

new Function("a", "b", "c", "return a+b+c")
new Function("a, b, c", "return a+b+c")
new Function("a,b", "c", "return a+b+c")

20.2.1.1.1 CreateDynamicFunction ( constructor, newTarget, kind, parameterArgs, bodyArg )

The abstract operation CreateDynamicFunction takes arguments constructor (a constructor), newTarget (a constructor), kind (normal, generator, async, or async-generator), parameterArgs (a List of ECMAScript language values), and bodyArg (an ECMAScript language value) and returns either a normal completion containing an ECMAScript function object or a throw completion. constructor is the constructor function that is performing this action. newTarget is the constructor that new was initially applied to. parameterArgs and bodyArg reflect the argument values that were passed to constructor. It performs the following steps when called:

  1. If newTarget is undefined, set newTarget to constructor.
  2. If kind is normal, then
    1. Let prefix be "function".
    2. Let exprSym be the grammar symbol FunctionExpression.
    3. Let bodySym be the grammar symbol FunctionBody[~Yield, ~Await].
    4. Let parameterSym be the grammar symbol FormalParameters[~Yield, ~Await].
    5. Let fallbackProto be "%Function.prototype%".
  3. Else if kind is generator, then
    1. Let prefix be "function*".
    2. Let exprSym be the grammar symbol GeneratorExpression.
    3. Let bodySym be the grammar symbol GeneratorBody.
    4. Let parameterSym be the grammar symbol FormalParameters[+Yield, ~Await].
    5. Let fallbackProto be "%GeneratorFunction.prototype%".
  4. Else if kind is async, then
    1. Let prefix be "async function".
    2. Let exprSym be the grammar symbol AsyncFunctionExpression.
    3. Let bodySym be the grammar symbol AsyncFunctionBody.
    4. Let parameterSym be the grammar symbol FormalParameters[~Yield, +Await].
    5. Let fallbackProto be "%AsyncFunction.prototype%".
  5. Else,
    1. Assert: kind is async-generator.
    2. Let prefix be "async function*".
    3. Let exprSym be the grammar symbol AsyncGeneratorExpression.
    4. Let bodySym be the grammar symbol AsyncGeneratorBody.
    5. Let parameterSym be the grammar symbol FormalParameters[+Yield, +Await].
    6. Let fallbackProto be "%AsyncGeneratorFunction.prototype%".
  6. Let argCount be the number of elements in parameterArgs.
  7. Let bodyString be ? ToString(bodyArg).
  8. Let parameterStrings be a new empty List.
  9. For each element arg of parameterArgs, do
    1. Append ? ToString(arg) to parameterStrings.
  10. Let currentRealm be the current Realm Record.
  11. Perform ? HostEnsureCanCompileStrings(currentRealm, parameterStrings, bodyString, false).
  12. Let P be the empty String.
  13. If argCount > 0, then
    1. Set P to parameterStrings[0].
    2. Let k be 1.
    3. Repeat, while k < argCount,
      1. Let nextArgString be parameterStrings[k].
      2. Set P to the string-concatenation of P, "," (a comma), and nextArgString.
      3. Set k to k + 1.
  14. Let bodyParseString be the string-concatenation of 0x000A (LINE FEED), bodyString, and 0x000A (LINE FEED).
  15. Let sourceString be the string-concatenation of prefix, " anonymous(", P, 0x000A (LINE FEED), ") {", bodyParseString, and "}".
  16. Let sourceText be StringToCodePoints(sourceString).
  17. Let parameters be ParseText(StringToCodePoints(P), parameterSym).
  18. If parameters is a List of errors, throw a SyntaxError exception.
  19. Let body be ParseText(StringToCodePoints(bodyParseString), bodySym).
  20. If body is a List of errors, throw a SyntaxError exception.
  21. NOTE: The parameters and body are parsed separately to ensure that each is valid alone. For example, new Function("/*", "*/ ) {") does not evaluate to a function.
  22. NOTE: If this step is reached, sourceText must have the syntax of exprSym (although the reverse implication does not hold). The purpose of the next two steps is to enforce any Early Error rules which apply to exprSym directly.
  23. Let expr be ParseText(sourceText, exprSym).
  24. If expr is a List of errors, throw a SyntaxError exception.
  25. Let proto be ? GetPrototypeFromConstructor(newTarget, fallbackProto).
  26. Let env be currentRealm.[[GlobalEnv]].
  27. Let privateEnv be null.
  28. Let F be OrdinaryFunctionCreate(proto, sourceText, parameters, body, non-lexical-this, env, privateEnv).
  29. Perform SetFunctionName(F, "anonymous").
  30. If kind is generator, then
    1. Let prototype be OrdinaryObjectCreate(%GeneratorFunction.prototype.prototype%).
    2. Perform ! DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }).
  31. Else if kind is async-generator, then
    1. Let prototype be OrdinaryObjectCreate(%AsyncGeneratorFunction.prototype.prototype%).
    2. Perform ! DefinePropertyOrThrow(F, "prototype", PropertyDescriptor { [[Value]]: prototype, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }).
  32. Else if kind is normal, then
    1. Perform MakeConstructor(F).
  33. NOTE: Functions whose kind is async are not constructible and do not have a [[Construct]] internal method or a "prototype" property.
  34. Return F.
Note

CreateDynamicFunction defines a "prototype" property on any function it creates whose kind is not async to provide for the possibility that the function will be used as a constructor.

20.2.2 Properties of the Function Constructor

The Function constructor:

  • is itself a built-in function object.
  • has a [[Prototype]] internal slot whose value is %Function.prototype%.
  • has a "length" property whose value is 1𝔽.
  • has the following properties:

20.2.2.1 Function.prototype

The value of Function.prototype is the Function prototype object.

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

20.2.3 Properties of the Function Prototype Object

The Function prototype object:

  • is %Function.prototype%.
  • is itself a built-in function object.
  • accepts any arguments and returns undefined when invoked.
  • does not have a [[Construct]] internal method; it cannot be used as a constructor with the new operator.
  • has a [[Prototype]] internal slot whose value is %Object.prototype%.
  • does not have a "prototype" property.
  • has a "length" property whose value is +0𝔽.
  • has a "name" property whose value is the empty String.
Note

The Function prototype object is specified to be a function object to ensure compatibility with ECMAScript code that was created prior to the ECMAScript 2015 specification.

20.2.3.1 Function.prototype.apply ( thisArg, argArray )

This method performs the following steps when called:

  1. Let func be the this value.
  2. If IsCallable(func) is false, throw a TypeError exception.
  3. If argArray is either undefined or null, then
    1. Perform PrepareForTailCall().
    2. Return ? Call(func, thisArg).
  4. Let argList be ? CreateListFromArrayLike(argArray).
  5. Perform PrepareForTailCall().
  6. Return ? Call(func, thisArg, argList).
Note 1

The thisArg value is passed without modification as the this value. This is a change from Edition 3, where an undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value. Even though the thisArg is passed without modification, non-strict functions still perform these transformations upon entry to the function.

Note 2

If func is either an arrow function or a bound function exotic object, then the thisArg will be ignored by the function [[Call]] in step 6.

20.2.3.2 Function.prototype.bind ( thisArg, ...args )

This method performs the following steps when called:

  1. Let Target be the this value.
  2. If IsCallable(Target) is false, throw a TypeError exception.
  3. Let F be ? BoundFunctionCreate(Target, thisArg, args).
  4. Let L be 0.
  5. Let targetHasLength be ? HasOwnProperty(Target, "length").
  6. If targetHasLength is true, then
    1. Let targetLen be ? Get(Target, "length").
    2. If targetLen is a Number, then
      1. If targetLen is +∞𝔽, then
        1. Set L to +∞.
      2. Else if targetLen is -∞𝔽, then
        1. Set L to 0.
      3. Else,
        1. Let targetLenAsInt be ! ToIntegerOrInfinity(targetLen).
        2. Assert: targetLenAsInt is finite.
        3. Let argCount be the number of elements in args.
        4. Set L to max(targetLenAsInt - argCount, 0).
  7. Perform SetFunctionLength(F, L).
  8. Let targetName be ? Get(Target, "name").
  9. If targetName is not a String, set targetName to the empty String.
  10. Perform SetFunctionName(F, targetName, "bound").
  11. Return F.
Note 1

Function objects created using Function.prototype.bind are exotic objects. They also do not have a "prototype" property.

Note 2

If Target is either an arrow function or a bound function exotic object, then the thisArg passed to this method will not be used by subsequent calls to F.

20.2.3.3 Function.prototype.call ( thisArg, ...args )

This method performs the following steps when called:

  1. Let func be the this value.
  2. If IsCallable(func) is false, throw a TypeError exception.
  3. Perform PrepareForTailCall().
  4. Return ? Call(func, thisArg, args).
Note 1

The thisArg value is passed without modification as the this value. This is a change from Edition 3, where an undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value. Even though the thisArg is passed without modification, non-strict functions still perform these transformations upon entry to the function.

Note 2

If func is either an arrow function or a bound function exotic object, then the thisArg will be ignored by the function [[Call]] in step 4.

20.2.3.4 Function.prototype.constructor

The initial value of Function.prototype.constructor is %Function%.

20.2.3.5 Function.prototype.toString ( )

This method performs the following steps when called:

  1. Let func be the this value.
  2. If func is an Object, func has a [[SourceText]] internal slot, func.[[SourceText]] is a sequence of Unicode code points, and HostHasSourceTextAvailable(func) is true, then
    1. Return CodePointsToString(func.[[SourceText]]).
  3. If func is a built-in function object, return an implementation-defined String source code representation of func. The representation must have the syntax of a NativeFunction. Additionally, if func has an [[InitialName]] internal slot and func.[[InitialName]] is a String, the portion of the returned String that would be matched by NativeFunctionAccessoropt PropertyName must be the value of func.[[InitialName]].
  4. If func is an Object and IsCallable(func) is true, return an implementation-defined String source code representation of func. The representation must have the syntax of a NativeFunction.
  5. Throw a TypeError exception.
NativeFunction : function NativeFunctionAccessoropt PropertyName[~Yield, ~Await]opt ( FormalParameters[~Yield, ~Await] ) { [ native code ] } NativeFunctionAccessor : get set

20.2.3.6 Function.prototype [ @@hasInstance ] ( V )

This method performs the following steps when called:

  1. Let F be the this value.
  2. Return ? OrdinaryHasInstance(F, V).

This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

Note

This is the default implementation of @@hasInstance that most functions inherit. @@hasInstance is called by the instanceof operator to determine whether a value is an instance of a specific constructor. An expression such as

v instanceof F

evaluates as

F[@@hasInstance](v)

A constructor function can control which objects are recognized as its instances by instanceof by exposing a different @@hasInstance method on the function.

This property is non-writable and non-configurable to prevent tampering that could be used to globally expose the target function of a bound function.

The value of the "name" property of this method is "[Symbol.hasInstance]".

20.2.4 Function Instances

Every Function instance is an ECMAScript function object and has the internal slots listed in Table 30. Function objects created using the Function.prototype.bind method (20.2.3.2) have the internal slots listed in Table 31.

Function instances have the following properties:

20.2.4.1 length

The value of the "length" property is an integral Number that indicates the typical number of arguments expected by the function. However, the language permits the function to be invoked with some other number of arguments. The behaviour of a function when invoked on a number of arguments other than the number specified by its "length" property depends on the function. This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

20.2.4.2 name

The value of the "name" property is a String that is descriptive of the function. The name has no semantic significance but is typically a variable or property name that is used to refer to the function at its point of definition in ECMAScript source text. This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

Anonymous functions objects that do not have a contextual name associated with them by this specification use the empty String as the value of the "name" property.

20.2.4.3 prototype

Function instances that can be used as a constructor have a "prototype" property. Whenever such a Function instance is created another ordinary object is also created and is the initial value of the function's "prototype" property. Unless otherwise specified, the value of the "prototype" property is used to initialize the [[Prototype]] internal slot of the object created when that function is invoked as a constructor.

This property has the attributes { [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: false }.

Note

Function objects created using Function.prototype.bind, or by evaluating a MethodDefinition (that is not a GeneratorMethod or AsyncGeneratorMethod) or an ArrowFunction do not have a "prototype" property.

20.2.5 HostHasSourceTextAvailable ( func )

The host-defined abstract operation HostHasSourceTextAvailable takes argument func (a function object) and returns a Boolean. It allows host environments to prevent the source text from being provided for func.

An implementation of HostHasSourceTextAvailable must conform to the following requirements:

  • It must be deterministic with respect to its parameters. Each time it is called with a specific func as its argument, it must return the same result.

The default implementation of HostHasSourceTextAvailable is to return true.