/

The repeat() Method in JavaScript

The repeat() Method in JavaScript

The repeat() method in JavaScript, introduced in ES2015, allows you to repeat a specified string a certain number of times. It can be useful in situations where you need to generate repetitive patterns or output repeated text.

Here’s an example of how to use the repeat() method:

1
'Ho'.repeat(3); // 'HoHoHo'

In this example, the string “Ho” is repeated three times, resulting in the output “HoHoHo”.

If you call the repeat() method without any parameters or with a parameter of 0, it will return an empty string:

1
2
'Ho'.repeat(); // ''
'Ho'.repeat(0); // ''

On the other hand, if you pass a negative parameter to the repeat() method, it will throw a RangeError:

1
'Ho'.repeat(-1); // RangeError: Invalid count value

It’s important to note that the parameter passed to the repeat() method must be a non-negative integer. Any non-integer values will be rounded down to the nearest integer.

In conclusion, the repeat() method provides a convenient way to repeat a string in JavaScript. It can be a useful tool in various scenarios, such as generating repeating patterns or creating repetitive text outputs.

tags: [“JavaScript”, “string”, “repeat()”, “ES2015”]