What is the error I am getting : TypeError: "newArr" is read-only ? Why Can't I set newArr variable to new values?

Tell us what’s happening:
Describe your issue in detail here.

**Your code so far**

function sumAll(arr) {
const newArr = [];
if(arr[arr.length-1] < arr[0])
newArr= arr.sort();
else newArr = [...arr];

console.log(arr);
//console.log(newArr);
const count = newArr[newArr.length-1]-newArr[0]+1;
const sum = (2*newArr[0]+(count-1)*1)*count/2;

return sum;
}

console.log(sumAll([5, 10]));
**Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36

Challenge: Sum All Numbers in a Range

Link to the challenge:

HI @Peter-gacc !

You are receiving that error message because you declared a const variable for newArr.

Remember that const is for constant variables that don’t change and can’t be assigned new values.

1 Like

Thanks @jwilkins.oboe!

Do you have any idea why the following function is giving me as a result?

function sumAll(arr) {

let newArr = [];

if(arr[arr.length] < arr[0])

    newArr= arr.push(arr[arr.length].push(arr[0]));

//else newArr = [...arr];

console.log(newArr);

const count = newArr[newArr.length-1]-newArr[0]+1;

const sum = (2*newArr[0]+(count-1)*1)*count/2;

return sum;

}

console.log(sumAll([4, 1]));

Put the values into the function.

The function is not returning [], you are console logging newArr, which is an empty array, which is []

function sumAll(arr) {
  let newArr = [];
  if(arr[arr.length] < arr[0]) {
    newArr= arr.push(arr[arr.length].push(arr[0]));
  }
  const count = newArr[newArr.length-1]-newArr[0]+1;
  const sum = (2*newArr[0]+(count-1)*1)*count/2;
  return sum;
}

arr is [4,1]
newArr is []

arr[arr.length] < arr[0] is
arr[2] < 4 is
undefined < 4 is
false.

So the if block is skipped.

count is
newArr[newArr.length-1]-newArr[0]+1 is
newArr[-1] - undefined - 1 is
undefined - undefined - 1 is
NaN

sum is
(2*newArr[0]+(count-1)*1)*count/2 is
(2 * undefined + (NaN - 1) * 1) * NaN / 2 is
NaN

Return value is NaN

1 Like

Thanks for the detailed explanation!

Surprisingly when changed the if(arr[arr.length] < arr[0]) ------> if(arr[arr.length-1] < arr[0])… It is working for [4,1] but not for [10,5]. Do you see any issue?

Zero based indexing means this doesn’t do what you think that it does

Never mind. I changed the function in line 4 from newArr= arr.sort() -----> to arr.reverse();

And it is working perfectly.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.