JavaScript Function Properties and Methods: length, name, call, apply, bind, toString and new Function
The built-in properties and methods every JavaScript function has: length, name and prototype; call and apply for choosing this; bind for fixing this and partially applying arguments (and its gotchas); toString; and the Function constructor, why it ignores local scope, and why to avoid it.
kvi5hnuCode Sprout team member7 min readOn this page
Functions are objects, and every function inherits a set of properties and methods from Function.prototype. You've met some of them already. This article covers them all, with the most attention on call, apply and bind, a favorite interview topic ("what's the difference between call, apply and bind?", "implement bind").
length, name and prototype
function fullName(first, last, middle = "") {
return [first, middle, last].filter(Boolean).join(" ");
}
console.log(fullName.length, fullName.name, typeof fullName.prototype);
console.log((() => {}).prototype);
2 fullName object
undefined
lengthis the number of declared parameters before the first default or rest parameter (article 65), here 2.nameis the function's name, inferred from the variable or property for anonymous functions (article 63). Debuggers and stack traces use it.prototypeexists on regular functions and classes, and becomes the prototype of objects created withnew(article 64, part 9). Arrow functions and methods don't have one.
length and name are read-only: assigning to them fails silently in sloppy mode and throws a TypeError in strict mode. (They're configurable, so Object.defineProperty can still change them, which some libraries do to make wrapper functions look like the originals.)
call and apply: choose this, call now
call and apply invoke a function immediately with an explicit this (article 64). They differ only in how you pass the arguments:

function introduce(greeting, punctuation) {
return `${greeting}, I'm ${this.name}${punctuation}`;
}
const ana = { name: "Ana" };
console.log(introduce.call(ana, "Hi", "!")); // arguments listed
console.log(introduce.apply(ana, ["Hello", "."])); // arguments in an array
Hi, I'm Ana!
Hello, I'm Ana.
A memory aid: apply takes an array, call takes commas.
fn.call(obj, x) behaves as if obj had fn as a method and you called obj.fn(x), without actually adding a property to obj.
Uses of call and apply
Borrowing methods from another type (article 62):
const record = { 0: "x", 1: "y", length: 2 };
console.log(Array.prototype.map.call(record, (s) => s.toUpperCase()));
console.log(Object.prototype.hasOwnProperty.call({ id: 1 }, "id"));
[ 'X', 'Y' ]
true
The second line is the classic safe way to call hasOwnProperty on an object that might not inherit it (or might override it); Object.hasOwn(obj, key) is the modern replacement.
Passing an array as arguments: Math.max.apply(null, numbers) was the pre-2015 idiom; today Math.max(...numbers) does the same.
Wrapping methods without losing this: a wrapper that forwards both this and the arguments is exactly what apply is for:
function trace(obj, methodName) {
const original = obj[methodName];
obj[methodName] = function (...args) {
const result = original.apply(this, args); // same this, same arguments
console.log(`${methodName}(${args.join(", ")}) -> ${result}`);
return result;
};
}
const calculator = {
base: 10,
plus(n) {
return this.base + n;
},
};
trace(calculator, "plus");
calculator.plus(5);
plus(5) -> 15
The wrapper must be a regular function (not an arrow) so that it receives this from the call calculator.plus(5). Logging, timing, caching and permission checks all use this pattern.
bind: fix this for later
bind doesn't call the function. It returns a new function that, whenever it's called, calls the original with a fixed this:
"use strict";
const player = {
name: "Ana",
announce() {
return `${this.name}'s turn`;
},
};
const unbound = player.announce;
const bound = player.announce.bind(player);
try {
unbound();
} catch (err) {
console.log(err.name); // this is undefined
}
console.log(bound());
console.log(bound.name);
TypeError
Ana's turn
bound announce
That's the standard fix for passing methods as callbacks: button.addEventListener("click", this.handleClick.bind(this)), setTimeout(timer.tick.bind(timer), 1000).
bind can't be overridden
Once bound, this stays fixed: calling the bound function as a method, with call/apply, or binding it again doesn't change it.
function getLabel() {
return this.label;
}
const boundToA = getLabel.bind({ label: "A" });
const holder = { label: "B", boundToA };
console.log(boundToA.call({ label: "C" }), holder.boundToA(), boundToA.bind({ label: "D" })());
A A A
The one exception is new: calling a bound function with new ignores the bound this and creates a new object as usual. Arrow functions ignore the this passed to bind, call and apply entirely, since they never had their own.
Each bind creates a new function
const widget = { onClick() {} };
console.log(widget.onClick.bind(widget) === widget.onClick.bind(widget));
false
This matters for removing event listeners: removeEventListener("click", this.onClick.bind(this)) removes nothing, because it's a different function from the one you added. Store the bound function once (this.boundClick = this.onClick.bind(this)) and use that reference for both adding and removing. In React, binding in render creates a new function every render, which can defeat memoization.
Partial application with bind
Arguments passed to bind after this are fixed in advance and placed before any arguments given later:
const multiply = (a, b) => a * b;
const double = multiply.bind(null, 2); // a is always 2
console.log(double(21), double.length);
function logAt(level, message) {
return `[${level}] ${message}`;
}
const warn = logAt.bind(null, "WARN");
console.log(warn("disk almost full"));
42 1
[WARN] disk almost full
This is partial application: creating a more specific function by fixing some arguments. The bound function's length reflects the remaining parameters. Pass null as this when the function doesn't use this. An arrow function does the same job and is often clearer: const double = (b) => multiply(2, b);. Article 69 explores partial application further.
Implementing bind (interview exercise)
A simplified version shows that bind is just a closure around apply:
function simpleBind(fn, thisArg, ...preset) {
return function (...later) {
return fn.apply(thisArg, [...preset, ...later]);
};
}
function describe(prefix, suffix) {
return `${prefix}${this.item}${suffix}`;
}
const describeLamp = simpleBind(describe, { item: "lamp" }, "<");
console.log(describeLamp(">"));
<lamp>
The real bind also handles new, sets name and length, and creates an exotic "bound function" object, but the core idea is exactly this.
toString
A function's toString() returns its source text, exactly as written, including comments (standardized in ES2019). Built-in functions show [native code]:
function area(r) { return Math.PI * r ** 2; /* circle */ }
console.log(area.toString());
console.log(Math.max.toString());
function area(r) { return Math.PI * r ** 2; /* circle */ }
function max() { [native code] }
It's occasionally used for debugging and by tools; don't build application logic on it, since minifiers rewrite source code.
The Function constructor
Functions can be created at runtime from strings with new Function (or just Function): every argument except the last is a parameter name, and the last is the body:
const multiplyFn = new Function("x", "y", "return x * y;");
console.log(multiplyFn(3, 4), multiplyFn.name, multiplyFn.length);
12 anonymous 2
Important differences from normal functions:
- It ignores local scope. The function is created as if at the top level of a script; it can see global variables but not the variables around the call that created it:
globalThis.setting = "global value";
function build() {
const setting = "local value";
return new Function("return setting");
}
console.log(build()());
global value
- Its body is always sloppy mode, even inside a module or strict code, unless the body itself starts with
"use strict". (This course occasionally uses that to demonstrate sloppy-mode behavior.) - It's parsed every time the constructor runs, which is slow in loops.
- It's
evalin disguise. Building functions from strings that contain user input is a code-injection vulnerability, and pages with a strict Content Security Policy block it entirely (nounsafe-eval).
You'll rarely need it. Legitimate uses are tools that generate code: template engines, some schema validators, and sandboxes. In application code, closures and higher-order functions do the same job safely.
Common questions
What's the difference between call, apply and bind?
call and apply call the function immediately with a given this: call takes the arguments separately, apply as an array. bind doesn't call the function; it returns a new function with this (and optionally some arguments) fixed for all future calls.
Why does bind not work on my arrow function?
Arrow functions don't have their own this; they always use the this of the code that created them, so bind, call and apply can't change it. Partial application of arguments with bind still works.
Should I use bind or arrow functions for callbacks?
Both work. Arrow wrappers (() => this.save()) are more common in modern code and let you pass extra arguments easily. bind is handy when you need a reusable bound reference, for example to remove an event listener later.
Is Function.prototype itself a function?
Yes, oddly: typeof Function.prototype is "function", and calling it returns undefined. Every function inherits from it, which is where call, apply, bind and toString come from.
Summary
lengthcounts declared parameters before defaults and rest;nameholds the function's (possibly inferred) name; regular functions have aprototype, arrows don't.call(thisArg, a, b)andapply(thisArg, [a, b])call a function now with a chosenthis; use them to borrow methods and to forwardthisand arguments in wrappers.bind(thisArg, ...preset)returns a new function withthispermanently fixed and optional preset arguments; it can't be re-bound, and eachbindcall creates a new function.- Arrow functions ignore the
thisgiven tocall,applyandbind. toStringreturns a function's source text.new Function(...)compiles code from strings in the global scope, in sloppy mode; avoid it, especially with user input.
Practice Questions
What does this print?
function f() {
return this.v;
}
const g = f.bind({ v: 1 });
console.log(g.call({ v: 2 }), f.call({ v: 3 }));
Answer
1 3. The bound function ignores the this given to call; the original f uses it.
What's the length of this bound function, and what does calling it with (2, 3) pass to the original?
((a, b, c) => 0).bind(null, 1)
Answer
Its length is 2, and the original receives (1, 2, 3): preset arguments come first.
Rewrite Math.min.apply(null, readings) in modern syntax.
Answer
Math.min(...readings).
Why does this listener never get removed?
el.addEventListener("click", this.onClick.bind(this));
el.removeEventListener("click", this.onClick.bind(this));
Answer
Each bind call returns a different function object, so the function passed to removeEventListener isn't the one that was added. Bind once, store the result, and use the stored reference in both calls.
Previous: JavaScript Closures Explained: Lexical Scope, Private State, Loops and Memory

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.