bob0306 bob0306 - 4 years ago 77
Javascript Question

the multiplication of a code between two numbers incorrectly outputting number

function showMultiples(num, numMultiples){
for(i=1; i<=numMultiples; i++){
var multiple = num + " x " + i + " = " + num * i;

}

return multiple;
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2,8));


For this code, what the function should do is, by looking at num and numMultiples variable, it should give you the list of multiplication that is possible with the two numbers. Therefore the console should print out
2x1=2 2x2=4 2x3=6 2x4=8 2x5=10 2x6=12 2x7=14 2x8=16

However, this code prints out 2x8 = 16 any guess to why?

Answer Source

You're assigning the value to multiple then returning it in the end, when your loop has finished, meaning multiple will be 2x8. If you do a console.log(multiple) right under var multiple = num + " x " + i + " = " + num * i; you will see it print out correctly.

EDIT:

function showMultiples(num, numMultiples){
var result = [];
for(i=1; i<=numMultiples; i++){
    result.push(num + " x " + i + " = " + num * i);
}

return result.join(' ');
} 

Add results to an array and when the function completes, join the values inside the array and return the results.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download