0
0
JavascriptHow-ToBeginner · 3 min read

How to Repeat String in JavaScript: Simple Guide

In JavaScript, you can repeat a string using the repeat() method. It takes a number as an argument and returns the string repeated that many times.
📐

Syntax

The repeat() method is called on a string and takes one argument:

  • count: The number of times to repeat the string. It must be a non-negative integer.

The method returns a new string with the original string repeated count times.

javascript
string.repeat(count)
💻

Example

This example shows how to repeat the string "Hello" 3 times using repeat():

javascript
const greeting = "Hello";
const repeated = greeting.repeat(3);
console.log(repeated);
Output
HelloHelloHello
⚠️

Common Pitfalls

Common mistakes when using repeat() include:

  • Passing a negative number or a non-integer as the count, which throws a RangeError.
  • Passing a non-number value, which is converted to a number and may cause unexpected results.
  • Trying to use repeat() on non-string types without converting them first.
javascript
try {
  console.log("Hi".repeat(-1)); // Throws RangeError
} catch(e) {
  console.log(e.message);
}

console.log("Hi".repeat(2.5)); // Repeats 2 times, decimal is truncated

console.log(String(123).repeat(2)); // "123123" - convert number to string first
Output
count must be non-negative HiHi 123123
📊

Quick Reference

Remember these tips when using repeat():

  • Use only non-negative integers as the count.
  • It returns a new string and does not change the original.
  • Works only on strings; convert other types to string first.

Key Takeaways

Use the string method repeat(count) to repeat a string in JavaScript.
The count must be a non-negative integer; decimals are truncated and negatives cause errors.
repeat() returns a new string and does not modify the original string.
Convert non-string values to strings before using repeat().
Common errors include passing negative or non-numeric counts.