WebDev 101 / Stuck on sumAll JS exercise


#1

Hey all,

I’ve been working through the sumAll exercise in JS Fundamentals 4. After cracking and looking at the solution, I think I understand everything except for one part.

Here’s the solution:

const sumAll = function(min, max) {
if (min < 0 || max < 0) return “ERROR”;
if (typeof min !== “number” || typeof max !== “number”) return “ERROR”;
if (min > max) {
const temp = min;
min = max;
max = temp;
}
let sum = 0;
for (let i = min; i < max + 1; i++) {
sum += i;
}
return sum;
};

Here’s the part I’m struggling to understand:

if (min > max) {
const temp = min;
min = max;
max = temp;
}

I know that somehow this code sorts min & max in ascending order in the event that the min value is greater than the max value, but I don’t understand how. it just seems like circular assignment - temp = min = max = temp = min = max etc.

Any help or resources I can check out to make sense of this would be greatly appreciated! :slight_smile:


#2

lets say
min is 7
max is 4

  1. temp = min ★here temp is assigned a value of 7 (min)
  2. min = max ★ here min is assigned a value of 4 (max)
  3. max = temp ★ here max is assigned a value of 7 (temp)

hence the final situation is
min is 4
max is 7


#3

Great! Thank you so much!