In this post, I will show you how to use repeat with an example.
repeat method is defined as below:
Here, count is an optional value. It is the number to repeat the string. If we don’t provide this value, it will return an empty string. Else, it will create a new string by appending the same string to the end and return that string.
This method doesn’t change the original string. It creates one new string by repeating the original string count number of times.
For count equal to 0 or if we don’t provide the count value, it will return an empty string.
For a negative count value, it throws one RangeError.
Let’s take a look at the below program:
const givenStr = 'hello'; console.log(givenStr.repeat()) console.log(givenStr.repeat(0)) console.log(givenStr.repeat(1)) console.log(givenStr.repeat(2)) console.log(givenStr.repeat(3))
It will print the below output:
hello hellohello hellohellohello
For the first two, it printed empty strings.