Code Logo

Borrow Methods with call()

Published at25 Jul 2026
JavaScript Functions Medium 0 views
Like0

Write a JavaScript function that uses Function.call() to borrow an Array method and apply it to a string (which is an array-like object). The function takes a string and returns an array of its individual characters.

Array.prototype methods like map, filter, and reduce are designed to work on arrays, but they can be borrowed by array-like objects using call(). Array-like objects have indexed elements and a length property but are not true arrays. Strings are array-like: each character has an index and the string has a length. By using Array.prototype.map.call(str, fn), we can apply Array.map to the string without converting it to an array first.

This pattern of method borrowing is a powerful JavaScript technique that demonstrates the language's dynamic nature. Functions are first-class citizens, and methods can be detached from their objects and applied to any compatible target using call() or apply(). Understanding this pattern is essential for advanced JavaScript programming.

Time complexity is O(n) where n is the string length, as map visits each character. Space complexity is O(n) for the resulting array. The call() method does not modify the original string.

Edge cases include empty strings (return empty array), single characters, strings with special characters or spaces, and ensuring the correct this context is passed to the borrowed method.

Example Input & Output

Example 1
Input
""
Output
[]
Explanation

Empty string

Example 2
Input
"hello"
Output
["h","e","l","l","o"]
Explanation

Borrow Array.map on string to get chars

Example 3
Input
"12345"
Output
["1","2","3","4","5"]
Explanation

Five digits

Example 4
Input
"abc"
Output
["a","b","c"]
Explanation

Three chars

Example 5
Input
"x"
Output
["x"]
Explanation

Single char

Algorithm Flow

Recommendation Algorithm Flow for Borrow Methods with call()
Recommendation Algorithm Flow for Borrow Methods with call()

Solution Approach

Call a function with a specific this value using call(), apply(), or bind(). call() accepts arguments individually, apply() accepts an array of arguments, and bind() creates a new function with a bound this.

function solution(greet) { return greet.call({ name: 'World' }, 'Hello'); }

call() immediately invokes the function. apply() is similar but takes arguments as an array. bind() returns a new function with permanent this binding that can be called later.

Time O(1), Space O(1).

Best Answers

javascript - Approach 1
function solution(str) {
  return Array.prototype.map.call(str, function(ch) {
    return ch;
  });
}