0

Codeware Challenge

So here what happening I'm trying to make a function that return the number i enter in the function parameter * the number of loop iteration i expect

// 1 * 5 = 5
// 2 * 5 = 10
// 3 * 5 = 15
// 4 * 5 = 20
// 5 * 5 = 25
// 6 * 5 = 30
// 7 * 5 = 35
// 8 * 5 = 40
// 9 * 5 = 45
// 10 * 5 = 50

but i only get // 1 * 5 = 5

i know that return stop the loop from iterating but i can't figure out how to make the loop continue

function multiTable(number) {
  //loop from 1 to 10
  for(let i = 1; i <= 10; i++){

    //create a string with the calculation
    let sum = (`${i} * ${number} = ${number * i}\n`);

    //return the sum
    return sum 

    //this is where the error happen it only return the first iteration (1 * 1 = 1)
    // i expect it to return 1 * 1 = 1, 1 * 2 = 2 all the way up to 10 
  }
}

multiTable(5);
2
  • 2
    the return ends the loop. it ends the entire function. if you return something you end the function. you can only return once. Commented May 31, 2021 at 23:58
  • You’re returning in for loop, place the return statement after the loop and declare the sum before the loop and inside the loop just concat the sum as sum += (${i} * ${number} = ${number * i}\n); Commented Jun 1, 2021 at 0:00

2 Answers 2

2

You will want to pull the return statement out of the for loop. Additionally, you'll want to maintain the sum outside the scope of the for loop as well or you'll overwrite it every time. The following should do both of these things.

function multiTable(number) {
  let sums = "";
  for(let i = 1; i <= 10; i++){
    sums += `${i} * ${number} = ${number * i}\n`;
  }
  return sums;
}

console.log(multiTable(5));

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks and also i would like to know what does really happen when you declare the sum as (let sums = "";) is this only so you can concat the string?
Yes exactly, that's so the strings can be concatenated. Another option would have been to maintain an array of strings and then join them by the line break at the end.
0

This is a nice application for a generator function:

function* multiTable(number) {
  for (let i = 1; i <= 10; i++) {
    yield `${i} * ${number} = ${number * i}`;
  }
}

console.log(Array.from(multiTable(5)).join('\n'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.