Can anyone explain why this doesn't work

This function is supposed to either count up or count down. And it keeps throwing an error: SyntaxError: Unexpected token ‘else’

function range(start, end) {
  let nums = [];
  if (start > end) {
    for (let i = start; i >= end; i--) {
      nums.push(i);
  }else if (end > start) {
    for (let i = start; i <= end; i++) {
      nums.push(i);
  }
    
}
}
  return nums;
}

console.log(range(5, 2));

Where are you using the step argument in the function?

I haven’t got that far yet…

The function should still work though? It should either count down or count up, correct?

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

1 Like

“Unexpected token” almost always means that you forgot a semicolon or a closing brace, bracket, parenthesis, quote, etc.

In this case you have an else before you close your if.

1 Like

Hi! you have forgotten to close your for loop in the following line.

for (let i = start; i >= end; i--) {
      nums.push(i);
}else if (end > start) {
  ....
}

Hope this helps

you messed up some curly braces.

check this one it is the same but with curly braces in place

function range(start, end) {
let nums = ;
if (start > end) {
for (let i = start; i >= end; i–) {
nums.push(i); }
}else if (end > start) {
for (let i = start; i <= end; i++) {
nums.push(i);
}

}

return nums;

}

console.log(range(5, 2));

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.

Thanks Ariel! I’m pretty green and I really appreciate the info

It took me a long time, I figured it out. I didn’t close one of my loops. To be honest, this post was more of a lesson in learning how to ask for help!”;)

I’m glad I could help. Most of us on the forums try to give nudges so that you can successfully struggle in the right direction and work through it. It can be a bit frustrating, but I think it more effective in the long run.

Happy coding!

1 Like