JavaScript Coding

//constant that stores my current age

const myAge = 22;

// variable that will change set to 2

let earlyYears = 2;

earlyYears *= 10.5;

let laterYears = myAge -= 2;

Why can’t I use the subtraction assignment operator when setting a new variable?

let laterYears = myAge -= 2; gave me an error, yet earlyYears *10.5; didn’t…

Hey @bhb23955, welcome to the forums!

You can only use -= when declaring the variable. When setting the value for the variablel, use just a minus sign.

What is the difference between declaring and setting the value?

I mean declaring in this context:

const example;

That’s a variable decleration. The only time you can use +=, -=, etc etc, is when that variable is being declared.

const example = 0;
example += 1
// completely ok

when you’re setting the value, you can’t use the +=, etc.

const example = 1 += 2
// syntax error

Instead, use:

const example = 1+2

Do you see what I mean?

So, in order to use the +=, -=, etc., you have to already have it set to a value?

1 Like

You are completely correct.

So, when I tried to assign it, laterYears = myAge = myAge -2 is what javascript read, so it wasn’t sure what to set the value to? Is that a correct way of thinking about it?

Oh my goodness. I’m a fool. Look at what type of variable myAge is. It’s constant isn’t it? What’s unique about constant variables?

They can’t be changed.

1 Like

right! And if you’re doing

 laterYears = myAge = myAge -2

you’re setting both myAge and laterYears equal to myAge minus 2. Which will give you a syntax error.

1 Like

Wow that’s really cool…

I love learning JavaScript!

Thanks for helping me

1 Like