Code Logo

String Repeat with Prototype

Published at25 Jul 2026
JavaScript String Handling Medium 0 views
Like0

Write a JavaScript function that extends the String prototype by adding a custom repeat method. The method should accept a number n and return a new string consisting of the original string repeated n times concatenated together.

JavaScript's prototype system allows adding methods to built-in objects like String, Array, and Number. When you add a method to String.prototype, every string instance automatically gains access to that method. This is a powerful feature of JavaScript's prototypal inheritance model that differs from class-based languages.

To implement string repetition, create an empty result array, then loop n times pushing the string into the array, and finally join the array into a single string. Using an array and join is the most efficient approach because string concatenation with + creates many intermediate strings, while the array method collects all parts and joins them once.

Time complexity is O(n * m) where n is the repeat count and m is the original string length. Space complexity is O(n * m) for the result string. The array-based approach is significantly faster than repeated string concatenation for large n values.

Edge cases include n = 0 (return empty string), n = 1 (return the string itself), negative n values (return empty string), and very large n values where the result would exceed available memory. The method should not modify the original string.

Example Input & Output

Example 1
Input
"ha",2
Output
"haha"
Explanation

Repeat ha 2 times

Example 2
Input
"x",5
Output
"xxxxx"
Explanation

Repeat x 5 times

Example 3
Input
"test",1
Output
"test"
Explanation

Repeat once returns same string

Example 4
Input
"ok",0
Output
""
Explanation

Repeat 0 returns empty string

Example 5
Input
"abc",3
Output
"abcabcabc"
Explanation

Repeat abc 3 times

Algorithm Flow

Recommendation Algorithm Flow for String Repeat with Prototype
Recommendation Algorithm Flow for String Repeat with Prototype

Solution Approach

Extend a built-in prototype with a custom method using prototype. Adding methods to prototypes can make code more expressive but should be done cautiously to avoid conflicts.

String.prototype.repeat = function(n) { return Array(n + 1).join(this); };

Modifying built-in prototypes can cause conflicts with libraries and future language features. Consider using utility functions or composition instead of prototype extension.

Time O(n), Space O(n).

Best Answers

javascript - Approach 1
function solution(str, n) {
  var result = [];
  for (var i = 0; i < n; i++) {
    result.push(str);
  }
  return result.join('');
}