When working with basic JavaScript concepts like this, it is recommended to use a console instead of directly coding for a web page. By utilizing console.log()
to write programs first and then moving on to manipulate DOM elements, you can bypass the cumbersome methods of using alert()
or document.write()
. I personally found guidance from the book Eloquent JavaScript by following similar practices.
Here are three different loop examples that achieve what you have described. The loops vary in their approach but all serve the purpose similarly:
console.log('\nloop one')
;(function() {
var x = '',
i = 1
while (i <= 20) {
x += i
x += i%5 ? ' ' : '\n'
i++
}
console.log(x)
})()
console.log('\nloop two')
;(function() {
var line = ''
for (var i = 1; i <= 20; i++) {
line += i + ' '
if (i % 5 === 0) {
console.log(line)
line = ''
}
}
})()
console.log('\nloop three')
;(function() {
for (var i = 1, line = ''; i <= 20; line = '') {
for (var j = 0; j < 5; j++)
line += i++ + ' '
console.log(line)
}
})()
node example
, with the above code saved in a file named 'example', will produce the following output:
loop one
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
loop two
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
loop three
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20