Mathematical operator error

I’m on the https://www.codecademy.com/paths/web-development/tracks/getting-started-with-javascript/modules/learn-javascript-control-flow/projects/race-day course.

let raceNumber = Math.floor(Math.random() * 1000);

const early = true;
let runnersAge = 20;

if (early == true && runnersAge == 20 ) {
console.log (‘correct’);
} else {
console.log(‘not correct’);
}

^ this works.

let raceNumber = Math.floor(Math.random() * 1000);

const early = true;
let runnersAge = 20;

if (early == true && runnersAge += 18) {
console.log (‘correct’);
} else {
console.log(‘not correct’);
}

^ this does not work, any ideas why? (mathematical operator += 18 // ==20 works I don’t see why this doesn’t.

I’ve put in the correct and not correct just for checking purposes, btw.

1 Like

+= -= /= *= operators are for adding, subtracting, dividing, multiplying the variable with a number.
So sixVar += 2 is the same as sixVar = sixVar + 2 this sets sixVar variable to the older itself and adding 2 to the older one, because if we would do simply this: sixVar + 2 we wouldn’t change the sixVar variable.

So with this information we can’t set a variable in an if statement

Hope this helps :grinning:

Thanks lolfail! I watched the walkthrough youtube video (forgot it was there at the time of posting) and figured out I can’t use the += operator like I was trying. Sorted now!

1 Like