Sum All Numbers in a Range - fixing ugly code

I know that my code is ugly. But rather than look at other people’s answers or the solution code, I would like to get my ugly code to work before I try making it faster/shorter. Right now, I am getting the following error message and I don’t know why:

newarr is not defined

Code so far


function sumAll(arr) {

if(arr[1] > arr[0] && arr[0] === 1){
  let newarr = [...Array(arr[1]).keys()].concat(arr[1]);
  console.log(newarr);
}else if (arr[0] > arr[1] && arr[1] === 1) {
  let newarr = [...Array(arr[0]).keys()].concat(arr[0]);
  console.log(newarr);
}else if(arr[1] > arr[0] && arr[0] !== 1){
 let newarr = [...Array(arr[1]).keys()].concat(arr[1]).splice(arr[0]); 
 console.log(newarr);
}else if(arr[0] > arr[1] && arr[1] !== 1){
 let newarr = [...Array(arr[0]).keys()].concat(arr[0]).splice(arr[1]); 
 console.log(newarr);
}

 return newarr.reduce((total, amount) => total + amount); 

}

sumAll([15, 10]);

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range

Thank you.

Ah, I see.

I changed from let to var. I will have to read up more on let, const, and var.

Thank you.

Edit: The post I was responding to was deleted for some reason. But anyways, the fix works.

Don’t use var if you can avoid it. I deleted the last post because it accidentally submitted before I was done.

The issue here is the block-scoping of variables declared with let. Each block is defined by curly braces that define control elements, like:

for (let i=0; i< 10; i++){
  // i is only defined for use inside this block, the one declared by the for loop.
  // use let when you expect to reassign to the variable (the i++)
  if (i%2 === 0) { // only runs when i is even
    const a = i/2;
    // a is only defined for use inside this if statement.
    // use const when you don't expect to reassign to the variable after creation.
    console.log("half of", i,"is:", a);
    // this block has access to the value of i because it is nested inside the block where i was declared.
  }
  //Line below won't work: a is scoped to the prior if block. Uncomment it and try it:
  //console.log(a);
}

Live pen to fork so you can break the code to see these concepts in action

@sabbyiqbal, I have to say, [...Array(arr[1]).keys()] is clever! :+1:
I’m hyped that I found something new, so I’ll spoil a little :slight_smile:

// First of all you can remove all your if...else ugliness by using Math.max / Math.min
[...Array(Math.max(...arr)).keys()]

// Then .map would be a nicer way to handle 0-index
[...Array(Math.max(...arr)).keys()].map(k => k + 1)

// Then you can remove splice and use filter instead
[...Array(Math.max(...arr)).keys()].map(k => k + 1).filter(k => k >= Math.min(...arr))

// Then you know what to do next and you have 'sexy' one-chain solution.