jskatas.org Continuously Learn JavaScript. Your Way.

function API: function.bind()

The bind() method creates a new function with a given scope and optionally parameter(s).

Using fn.bind() creates a new function with scope (and parameters) pre-configured

GIVEN we bind a scope to a function

WHEN we call the bound function with a custom object THEN the scope of this refers to the given object
const fn = function() { return this.newVariable; }; const boundFn = fn.____({myScopeVariable: 'forty-two'}); assert.strictEqual(boundFn(), 'forty-two');
WHEN binding a string to String's toUpperCase THEN calling the resulting function returns the upper case value of the string
const yell = String.prototype.toUpperCase('hello'); assert.strictEqual(yell(), 'HELLO');
WHEN binding Array's slice() method THEN array-like values can dynamically be converted to an array
const arrayLike = {length: 1, 0: 'a'}; const toArray = function (a) { return Array.prototype.bind(a)(); }; assert.deepStrictEqual(toArray(arrayLike), ['a']);

GIVEN we bind parameters to a function

WHEN binding the first parameter of a function THEN the bound function can be called just with the seconds parameter
const add = function(a, b) { return a + b; }; const add5 = add.bind(); assert.strictEqual(add5(10), 15);

Links

The MDN docs about `bind()`.
The ECMAScript Language Specification, 5 Edition, Section 15.3.4.5, when `bind()` was introduced.

Related Katas

function API

Arrow functions

Async Function

Difficulty Level

ADVANCED

First Published

16 October 2023

Stats

4 tests to solve