Search code examples
javascriptprototype

Javascript New Array Functionality


I came across the below code in one website and I am unable to understand the line commented as "DOUBT". How is the function returning the repeated text by using "new Array(n + 1).join(this)" ?

if (!String.prototype.repeat) { 
  String.prototype.repeat = function(n) {
    return new Array(n + 1).join(this);    /* DOUBT */
  };
}
alert( "La".repeat(3) );

Output: LaLaLa

Solution

  • When you join an array of length n by an argument str, you'll create a new string by inserting n - 1 items of str, such that one is between each array item. Eg:

    const arr = ['foo', 'bar', 'baz'];
    arr.join(' ')
    // results in
    // foo bar baz
    

    The new Array(n + 1) creates an array which has length n + 1 but has no elements. These non-existent elements, when converted into a string by .join, result in the empty string.

    The this inside String.prototype.repeat is the string the function is being called on. For example:

    'foo'.repeat(
    

    results in String.prototype.repeat being called with a this of 'foo'.

    So:

    new Array(n + 1).join(this)
    

    results in a new string containing n repetitions of this.

    Another way of looking at it, if 'x'.repeat(2) is called, the following array is constructed:

    // [<empty>, <empty>, <empty>]
    // insert 'x' between each element of the array:
    // '' + 'x' + '' + 'x' + ''
    // result: 'xx'