Why does -(-10) = 10?

Hi,

I was working through a code challenge and struggling. When I viewed the solution I noticed the following:

(I’ve simplified the problem below as the full challenge is long.)

let num = -10;

console.log(-num); // Will log positive 10 to the console.)

Why does the above log 10 to console. What is the code actually doing behind the hood. Does it look like this when being worked out:

console.log(--10);

If so, why does --10 = positive 10?

I think this is fairly simple maths and feel silly as I can’t wrap my head around it.

To begin with, you can think of -10 as being equivalent to -1 * 10.

So then you can think of doing -1 * (-1 * 10) as being the same as -(-10).

Multiplication doesn’t care about order when it’s just by itself, so
a * (b * c) = (a * b) * c = a * b * c.

Notice -1 * -1 = 1… and so you can think (-1 * -1) * 10 = ? and you’re left with 1 * 10 = 10

Finally, I think I understand! Thank you :grinning:

Am I on the right lines if I think of it like this and break it down as such:

console.log(-num); // Is the same as…
console.log(-(-num)) // which is the same as…
console.log (-1(-10) // which is the same as…
console.log(-1 * -10) // which equals 10!

Therefore console.log(-num) // Will print 10 to the console.

console.log(-num); // Is the same as…
console.log(-(-10)) //

which is not (-(-num)) — that’s (-(-(-10))) :slight_smile: but other than that yes.

Oops yes, missed that! Thank you again, really helpful :grinning: