Nerd For Tech
Published in

Nerd For Tech

Basics of Javascript · String · repeat() (method)

This article is a transcript of my free youtube series about basics of web development. If you prefer watching over reading, feel free to visit my channel “Dev Newbs”.

Hello my fellow newbs. Jacob here, with yet another String method. Today’s method is one of the simple ones. I like these straightforward methods, because you can just use them. No shenanigans, no catches. Of course, unless you are explicitly looking for them, which we of course are. So let’s get to it.

The repeat() method returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

The only parameter needed is an positive integer value specifying how many times we want the given string to be repeated.

What we get as a result is a created string or RangeError in case that repeat count is either negative or it causes the result string to overflow maximum string size.

Let’s see the basic usage in the first example.

"Repeat (0):   '" + "Ab ".repeat(0) + "'"       // empty string
"Repeat (1): '" + "Ab ".repeat(1) + "'" // 'Ab '
"Repeat (2): '" + "Ab ".repeat(2) + "'" // 'Ab Ab '
"Repeat (5.2): '" + "Ab ".repeat(5.2) + "'" // 'Ab Ab Ab Ab Ab '
"true: '" + "Ab ".repeat(true) + "'" // 'Ab '
"empty param: '" + "Ab ".repeat() + "'" // 'Ab '
"false: '" + "Ab ".repeat(false) + "'" // empty string
"null: '" + "Ab ".repeat(null) + "'" // empty string
"undefined: '" + "Ab ".repeat(undefined) + "'" // empty string
"NaN: '" + "Ab ".repeat(NaN) + "'" // empty string

The basic usage example shows the behavior of the method when we provide values that are either integer or can be interpreted as one. Integer values zero, one and two get us exactly what we expect. Float value is more interesting. The part after the decimal point is effectively cut-off and we only work with the whole integer value. So far, the method behaves as we would expect.

If we provide a boolean true, we interpret it as one. False is converted into zero as is any other value or special constant like ‘null’, ‘undefined’ or ‘NaN’. One more case to mention is if we do not provide any value, then default is zero. It is not mentioned in the specification, so it is possible that this is just a way of implementation within Chrome browser. So keep that in mind.

Ok, let’s try some shenanigans with the RangeError.

try { 
console.log("Ab ".repeat(-1));
}
catch(err){
console.log(err);
}
// RangeError: Invalid count value at String.repeat (<anonymous>)try {
console.log("Ab ".repeat(3/0));
}
catch(err){
console.log(err);
}
// RangeError: Invalid count value at String.repeat (<anonymous>)try {
let As = "A".repeat(536870889);
}
catch(err){
console.log(err);
}
// RangeError: Invalid string length at String.repeat (<anonymous>)

RangeError is an error thrown in only a handful of cases. First of them is a negative value. That we have covered in the first block of code. Second case is if we provide a value equal or higher than positive infinity. And guess what you get if you divide positive value by zero? Bingo! So that’s block code number two.

And the third one is if we create a string that is longer than maximal available string length. This number can actually be different in different browsers and can also be limited by available resources of the computer. But I will get back to that later in example number three. For now, just take it as something that just is true. The value in the third block code is exactly one more than maximum string length available, so it throws RangeError.

So back to the maximum length now. You cannot get maximum string length available by simply accessing some constant or a built-in method, which is a shame. Luckily clever people on the internet can help with virtually anything, so here is the code from Stack overflow that I shamelessly copied over. Shout out to author of the code username Jack Griffin. And here is the code that gets us the maximum length of the string variable in our browser.

// stack overflow // question: 13697500 // author: Jack Giffin
for (var startPow2 = 1; startPow2 < 9007199254740992; startPow2 *= 2)
try {" ".repeat(startPow2);} catch(e) {
break;
}
var floor = Math.floor, mask = floor(startPow2 / 2);
while (startPow2 = floor(startPow2 / 2))
try {
" ".repeat(mask + startPow2);
mask += startPow2; // the previous statement succeeded
} catch(e) {}
console.log("The max string length for this browser is " + mask);// The max string length for this browser is 536870888

That’s it for today. We learned that not all String methods are as terrible as the others. This was one of the good ones.

As always thank you for the attention and I will meet you in the next article tomorrow.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jakub Korch

Jakub Korch

19 Followers

Web enthusiast, programmer, husband and a father. Wannabe entrepreneur. You name it.