var
is scoped to the function.
let
and const
are scoped to the block
That means that y
is scoped to the if
. Had you used var
, this would not have occurred.
You will probably want to use let
instead of const
-- and then you can declare the variable outside the if
, but assign to it inside the if
.
You can't keep it a const
, sadly, because you're changing its value later (just two lines later, but that doesn't matter).
Here is what that looks like:
let taxableIncome = 80000;
let y;
if(taxableIncome >37000 && taxableIncome <80001) {
y = taxableIncome - 37000;
}
console.log(y);
console.log(taxableIncome);
In the above I also remove a semicolon just after the if
's condition, but before it's opening {
.
I might note this: it might not be sensible to try and get the value of a variable if you don't even know if it's been set. It all depends on the taxableIncome
, and so I would add any code that relies on the variable y
having a value to be inside the if
as well -- and that will solve your problem too!