Using String repeat() method to coding in Javascript/JS

This JavaScript tutorial explains how to use the string approach known as repeat() with syntax and examples.

Description

In JavaScript, repeat() is a string method that is used to repeat a string a specified range of times. Because the repeat() technique is a approach of the String object, it have to be invoked via a precise occasion of the String class.

Syntax

In JavaScript, the syntax for the repeat() technique is:

string.repeat([count]);

Parameters or Arguments

count Optional. The quantity of instances to repeat the string. If this parameter is not provided, the repeat() approach will use zero as the default and return an empty string.

Returns

The repeat() approach returns a string that has been repeated a preferred variety of times.

If the depend parameter is no longer furnished or is a value of 0, the repeat() approach will return an empty string. If the rely parameter is a poor value, the repeat() method will return RangeError.

Note

The repeat() technique does now not change the cost of the authentic string.

Example

Let’s take a seem at an example of how to use the repeat() method in JavaScript.

For example:

var totn_string = 'TechOnTheNet';

console.log(totn_string.repeat(0));
console.log(totn_string.repeat(1));
console.log(totn_string.repeat(2));
console.log(totn_string.repeat(3));

In this example, we have declared a variable referred to as totn_string that is assigned the string cost of ‘TechOnTheNet’. We have then invoked the repeat() approach of the totn_string variable to repeat the string a particular variety of times.

We have written the output of the repeat() technique to the internet browser console log, for demonstration purposes, to show what the repeat() approach returns.

The following will be output to the internet browser console log:

<empty string>
TechOnTheNet
TechOnTheNetTechOnTheNet
TechOnTheNetTechOnTheNetTechOnTheNet

As you can see, the repeat() approach returned an empty string when the matter parameter was once 0, Otherwise, it repeated the string ‘TechOnTheNet’ the unique number of times.