JavaScript Glossary - Lesson #19

JavaScript String .repeat() Method

The String repeat() method is a very fun one. You can take any string and repeat over it so that it displays multiple times.

javascript
""hello "".repeat(5);
// output: hello hello hello hello hello
js
// 1. we have a string
const myString = 'hi there. ';

// 2. repeat over it 5 times
const repeatedString = myString.repeat(5);

// 3. output: hi there. hi there. hi there. hi there. hi there.
console.log(repeatedString); // hi there. hi there. hi there. hi there. hi there.

It can also work with emojis!

javascript
""??"".repeat(10);

// output: ?✨??✨??✨??✨??✨??✨??✨??✨??✨??✨?

This can be useful as filler text or for annoying your friends.

javascript
myString.repeat(numberOfTimesToRepeat);

count (integer)

The number of times you want to repeat over the string.

Repeat() does not affect the original string. It creates a new one and returns that.

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)