Print a string N number of times in JavaScript

Looping statements are used to execute a sequence of statements repeatedly for N times or infinitely, rather than hardcoding those statements N times in a sequence. Therefore, Looping statements facilitate the reusability of a code snippet. In JavaScript, a string can be printed N times using any looping statement provided by JavaScript. For example, consider the code snippet below which uses a for loop,

let n = 10
let string = "JavaScript"
for (let i = 0; i < n; i++)
    console.log(string)

Similarly, other loop constructs like while, do...while can also be used. If the above example is run in a Node environment, it can be seen that the string is printed 10 times.

codespeedy:$ node stringntimes.js
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript
JavaScript

Whereas, in the browser console, though the string is printed 10 times, the console shows it only once. But, It shows the number of times it printed the string.

Leave a Reply

Your email address will not be published.