Lodash _.repeat: Multiplying Strings in JavaScript

The _.repeat method in the Lodash JavaScript utility library is used to repeat—or "multiply"—a given string a specified number of times. This guide explains the exact output produced by _.repeat, breaks down its syntax and parameters, and details how the method handles standard inputs as well as edge cases like negative numbers, decimals, and empty values.

How _.repeat Works

In Lodash, the _.repeat method takes a string and concatenates it with itself a defined number of times. It returns a single, contiguous string.

Syntax

_.repeat([string=''], [n=0])

Standard Output

When provided with a valid string and a positive integer n, the method outputs a new string containing n copies of the input string joined end-to-end.

_.repeat('cat', 3);
// Output: 'catcatcat'

_.repeat('*', 5);
// Output: '*****'

Behavior with Edge Cases

Lodash's _.repeat is built to fail safely, avoiding runtime exceptions that might occur with standard JavaScript operations.

Zero and Negative Numbers

If n is 0, or if a negative number is supplied, _.repeat returns an empty string. Unlike native JavaScript's String.prototype.repeat(), which throws a RangeError for negative numbers, Lodash returns an empty string without throwing an error:

_.repeat('hello', 0);
// Output: ''

_.repeat('hello', -2);
// Output: ''

Decimals and Floating-Point Numbers

If n is a floating-point number, Lodash truncates the value to an integer before repeating:

_.repeat('abc', 2.8);
// Output: 'abcabc'

Missing or Non-String Inputs

If the string parameter is omitted, null, or undefined, the method treats it as an empty string:

_.repeat();
// Output: ''

_.repeat(null, 3);
// Output: ''

If a non-string data type is passed as the first argument, Lodash converts it to a string representation prior to repetition:

_.repeat(7, 3);
// Output: '777'

_.repeat(true, 2);
// Output: 'truetrue'