The value to check
Optionalname: string
The name of the native function (its initial name, eg. "Array", "max", "get size" for a getter, or
"" for an anonymous one such as a bound function), when it isn't provided any native function matches
true when the value is a native function (with the name), otherwise false
isNativeFn(Array); // true
isNativeFn(Array, "Array"); // true
isNativeFn(Math.max, "max"); // true
isNativeFn(Math.max, "min"); // false
isNativeFn(function Array() {}); // false, written in JavaScript
isNativeFn(() => {}); // false
isNativeFn(Array.bind(null)); // true, eg. "function () { [native code] }"
isNativeFn("function Array() { [native code] }"); // false, not a function
// Another realm's (eg. an iframe's) Array is also the native Array
isNativeFn(iframe.contentWindow.Array, "Array"); // true
Checks whether the value is a native function, a function which isn't written in JavaScript (eg. a built-in function like
ArrayorMath.max, a function returned by the nativeFunction.prototype.bind()or a callableProxy), and when anameis provided, whether it is the native function with that name.Its source text, from the intrinsic
Function.prototype.toString()(captured when the module is loaded, so one which is replaced later, or a function's owntoString(), isn't used), is matched against theNativeFunctionsyntax which the ECMAScript specification requires for these functions, eg.function Array() { [native code] }(a runtime may add whitespace, eg. new lines), in linear time. The source text of a function written in JavaScript is its code, which can't have this syntax as[native code]isn't valid JavaScript, except where the runtime doesn't return its code: V8 (eg. Chrome and Node) returns a native source text for a function which has more than 65,535 characters between thefunctionkeyword and its parameters (eg.functionfollowed by 65,536 spaces andArray() {}), so (as the source text is all it uses) such a function is also identified as a native function there. So it identifies the runtime's functions (eg. to choose a native implementation), it isn't a security check of a value which may have been created to look like a native function.It returns a
booleanrather than being a type guard, as afalseresult doesn't mean that the value isn't a function (a function written in JavaScript also returnsfalse), use isFunction to narrow the type.