Table of Contents
show
Example 28
Write a for loop that counts down from 10 to 1
for (var i = 10; i >= 1; i--) {
console.log(i);
}
Output
Example 29
Write a JavaScript to print multiplication table for a number prompted from user
const prompt = require("prompt-sync")();
var n = parseInt(prompt("Enter a number : "));
for (let i = 1; i <= 10; i++) {
console.log(`${i} x ${n} = ${i * n}`);
}
Output
Example 30
Write a JavaScript to reverse a given string
var original = "car";
var reversed = "";
console.log(`Original String: ${original}`);
for (var i = original.length - 1; i >= 0; i--) {
reversed += original[i];
}
console.log(`Reversed String: ${reversed}`);
Output
Example 31
Write a ‘for’ loop that prints numbers from 1 to 20, replacing multiples of 3 with Java and multiples of 5 with Script
for (var i = 1; i <= 20; i++) {
if (i % 3 === 0) {
console.log("Java");
} else if (i % 5 === 0) {
console.log("Script");
} else {
console.log(i);
}
}
Output
Example 33
Write a for loop to print triangle pattern of stars
for (var i = 1; i <= 5; i++) {
var line = "";
for (var j = 0; j < i; j++) {
line = line + "*";
}
console.log(line);
}
Output
Views: 49