Repeating Strings in JavaScript

Introduction

String manipulation is a fundamental part of coding, like duplicating or repeating strings/characters - a task that may seem trivial, but important for certain scenarios, whether it's formatting output to display to a user or saving certain types of data to a file. In this Byte, we'll see what it takes to repeat strings and how to do it in JavaScript.

The Need for Repeating Strings

Imagine you're building a command line tool that needs to generate a dynamically-sized border around an element, like a table. The border would be made up of a string of characters that need to be repeated based on the size of the element. Or, consider a scenario where you need to create a string of a specific length for testing purposes.

String repetition becomes a handy tool in cases like these. It's a simple operation, but knowing how to do it the "right" way can make your code much simpler and more idiomatic.

How to Repeat a String in JavaScript

JavaScript has a couple of ways to repeat a string. The two most common methods are using the built-in repeat() method and using a for loop. Let's explore these methods in more detail.

Using the repeat() Method

Introduced in ES6, the repeat() method is a built-in JavaScript method that simply repeats the string a specified number of times.

Here's how you can use it:

let str = "StackAbuse ";
console.log(str.repeat(3));

This will output:

StackAbuse StackAbuse StackAbuse 

The repeat() method is an incredibly straightforward way to repeat a string. All you need to do is call the method on the string you want to repeat, and pass in the number of repetitions as an argument.

Note: The repeat() method does not change the original string. It returns a new string with the repeated content.

The repeat() method is a great tool when you need to repeat a string a specific number of times. It's easy to use, highly readable, and part of the JavaScript standard - making it a reliable choice for string repetition.

Using a For Loop

While the repeat() method is the most straightforward way to repeat a string in JavaScript, there's another method that doesn't rely on a bespoke method - the good old for loop. This way to do it is a bit more manual, but it would also allow you to customize the repetition a bit more than the repeate() method, like if you needed to conditionally repeat a string or characters.

Here's a simple example:

let text = "Stackabuse ";
let repeatedText = "";

for (let i = 0; i < 5; i++){
    repeatedText += text;
}

console.log(repeatedText); // "Stackabuse Stackabuse Stackabuse Stackabuse Stackabuse "
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

In the above code, we're creating an empty string repeatedText and then appending the text to it five times in the for loop. The result is the string "Stackabuse" repeated five times.

This method can be a little bit more cumbersome than using repeat(), but it's good to know that it exists, especially if you're working in a JS environment that doesn't support repeat().

Comparing the Methods

Now that we've seen two different ways to repeat a string, you might be wondering which one you should use. The answer? It depends. Let's take a look at some of the factors you might want to consider.

Performance

When it comes to performance, the repeat() method is faster than the for loop. This is because the repeat() method is a built-in JavaScript function and is optimized for performance.

However, the difference in performance is negligible unless you're dealing with very large strings or repeating a string a huge number of times.

console.time('repeat');
"Stackabuse ".repeat(1000000);
console.timeEnd('repeat'); // repeat: 0.179ms

console.time('for loop');
let str = "";
for (let i = 0; i < 1000000; i++){
    str += "Stackabuse ";
}
console.timeEnd('for loop'); // for loop: 94.756ms

In the above code, we're timing how long it takes to repeat a string one million times. As you can see, repeat() is significantly faster, coming in at over 500x faster! But remember, unless you're working with similarly large numbers, you're unlikely to notice a difference.

Readability

In terms of readability, the repeat() method wins hands down. It's clear, concise, and tells you exactly what it's doing. The for loop, on the other hand, requires a bit more cognitive load to understand what's happening.

// Clear and concise
let str1 = "Stackabuse".repeat(5);

// Requires a bit more thinking
let str2 = "";
for (let i = 0; i < 5; i++) {
    str2 += "Stackabuse";
}

As Donald Knuth once said, "Programs are meant to be read by humans and only incidentally for computers to execute." So, when in doubt, opt for readability over minor performance gains.

Browser Compatibility

Of course, if you're working with a cross-platform library or frontend code, you really need to consider browser compatibility.

The repeat() method is a modern addition to JavaScript, introduced in ES6. And luckily, it's supported by most modern browsers, including Chrome, Firefox, Safari, and Edge. However, if you're developing for an audience that may be using older browsers—like Internet Explorer—you might run into some compatibility issues as IE doesn't support the repeat() method.

Note: Always check the Can I use website to verify the compatibility of JavaScript methods with different browsers. It'll save you headaches down the road if you accidentally use a method that's not widely supported

On the other hand, using a for loop to repeat strings is a more traditional approach and is supported across all browsers, including older ones like IE, so it's a bit safer.

Conclusion

In this Byte, we've explored how to repeat strings in JavaScript using the repeat() method and a for loop. We also examined the speed of each method, the browser compatibility, and noted that while the repeat() method is a modern addition to the language and is not supported in older browsers, a for loop offers wider compatibility.

Last Updated: September 18th, 2023
Was this helpful?

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms