jskatas.org Continuously Learn JavaScript. Your Way.

String API: string.repeat(count)

Appends count copies of string to each other and returns it.

Donate to NGO Julenka. Support Ukranians in need. Julenka is an NGO which my brother founded in 2011 to support Ukranian families and kids in need.

str.repeat(x) concatenates x copies of str and returns it

the 1st parameter the count

  • if missing, returns an empty string
  • when 1, the string stays the same
  • for 3 the string x becomes xxx
  • for 0 an empty string is returned

the count is not a number

  • such as a string "3", it gets converted to an int
  • a hex looking number as a string "0xA", it gets converted to an int
  • and does not look like a number, it behaves like 0

throws an error for

  • a count of <0
  • a count of +Infinty

accepts everything that can be coerced to a string

  • e.g. a boolean
  • e.g. a number

for my own (string) class

  • calls toString() to make it a string
  • toString() is only called once

Links

The official specification, actually quite good to read for this function.
The part in the spec, which explains the conversion of a string to a number.
The Mozilla Developer Network docs, contains good examples.
Announcement of this kata on twitter.