javascriptbeginner10 minutes
Predict the Output of a Basic For Loop with Condition
Analyze the given JavaScript code snippet involving a for loop and conditional statements, then determine the output printed to the console.
Challenge prompt
Consider the following JavaScript code: function printNumbers() { let result = ''; for (let i = 1; i <= 5; i++) { if (i % 2 === 0) { result += i + '-even '; } else { result += i + '-odd '; } } console.log(result.trim()); } What will be printed when printNumbers() is called?
Guidance
- • Pay attention to how the loop iterates from 1 to 5.
- • Understand the condition checking if the number is even or odd.
- • Note how the result string is built during each iteration.
Hints
- • Remember the modulus operator (%) returns the remainder after division.
- • Even numbers have a remainder of 0 when divided by 2.
- • The trim() method removes trailing spaces from the result string.
Starter code
function printNumbers() {
let result = '';
for (let i = 1; i <= 5; i++) {
if (i % 2 === 0) {
result += i + '-even ';
} else {
result += i + '-odd ';
}
}
console.log(result.trim());
}
printNumbers();Expected output
1-odd 2-even 3-odd 4-even 5-odd
Core concepts
for loopconditionalsstring concatenation
Challenge a Friend
Send this duel to someone else and see if they can solve it.