Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 217
Shubham Avatar asked Dec 11 '25 20:12

Shubham


1 Answers

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'
like image 61
CertainPerformance Avatar answered Dec 13 '25 10:12

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!