Creative Name Looping
After taking some time off to focus on other projects, I'm back to the JS challenges! This time with a simple but brain-stimulating challenge: looping names and creating more creative outputs.
The goal of this challenge was to print a name multiple times based on user input, while exploring loops, validation, and some creative enhancements.
1. Syifa Fauziyah Arizal
2. Syifa Fauziyah Arizal
3. Syifa Fauziyah ArizalUnderstanding N
Here, n represents how many times the user wants their name to be printed.
First Attempt
const input = prompt("How many times do you want to print your name? ");
for (let i = 1; i <= input; i++) {
console.log(i + ". " + "Syifa Fauziyah Arizal");
}This version works, but it still lacks validation.
Input Validation
const input = Number(prompt("How many times do you want to print your name? "));
if (!isNaN(input) && input > 0) {
for (let i = 1; i <= input; i++) {
console.log(`${i}. Syifa Fauziyah Arizal`);
}
} else {
console.log("Please enter a valid number 😅");
}Using !isNaN() ensures the input is a valid number, while input > 0 prevents unnecessary looping.
Bonus Challenge
To make the output more fun, I added emojis and motivational quotes that rotate automatically using arrays.
- Syifa 🔥 — Keep going!
- Syifa 💡 — You're learning!
- Syifa 🌱 — Progress every day!
Using Arrays and Modulus
const emojis = ["🔥", "💡", "🌱", "🚀"];
const motivation = [
"Keep going!",
"You can do it!",
"Believe in yourself!"
];The modulus operator (%) allows array items to repeat safely when the loop count exceeds the array length.
Final Solution
const input = Number(prompt("How many times do you want to print your name? "));
const emojis = ["🔥", "💡", "🌱", "🚀", "🎯", "💪", "🧠", "✨", "🔧", "🎉"];
const motivation = [
"Keep going!",
"You can do it!",
"Believe in yourself!",
"Stay positive!",
"Never give up!",
"Dream big!",
"Stay focused!",
"Work hard!",
"Embrace challenges!",
"Success is yours!",
];
let result = "";
if (!isNaN(input) && input > 0) {
for (let i = 0; i < input; i++) {
const emoji = emojis[i % emojis.length];
const quote = motivation[i % motivation.length];
result += `${i + 1}. Syifa `${emoji} - `${quote}
`;
}
console.log(result);
} else {
console.log("Please enter a valid number 😅");
}