1

I need to print a range of numbers in a range using a function and a for-loop. Again I'm stuck on the return value. I believe my code is sufficient for the task but if you have a better idea I'm all ears.

function printRange(rangeStart, rangeStop) {    
    var text = "";
        for (var i = rangeStart; i < rangeStop; i++) {
            text += i + ',';
        }
    return text;
    var result = text;
}

printRange(20, 47);

The 'result' is ought to print the numbers 20,21,22...,46,47 but of course it doesn't... Any help is appreciated. Regards, Thomas

1
  • 4
    return exits the function, the line below doesn't get reached. Commented Mar 10, 2015 at 21:08

2 Answers 2

2

There are two things you need to fix - your code doesn't print rangeStop, but it does include a trailing comma.

You can fix the former by changing your loop end condition to use <=, and String.prototype.slice can do the latter.

function printRange(rangeStart, rangeStop) {
  var text = "";
  for (var i = rangeStart; i <= rangeStop; i++) {
    text += i + ',';
  }

  return text.slice(0, -1);
}

document.write(printRange(20, 47));

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

Comments

0
function printAllNum(rangeStart, rangeEnd){
  for(let i = rangeStart; i <= rangeEnd; i++) {
  document.write(i + " ")}
}
printAllNum(1,20);

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.