I am starting out with JavaScript and am having problems with the confusing operation of variables. I read that var
was to be discouraged because it allows unexpected changes so let
and const
should replace var
. I have been struggling with a program that produces the wrong results and I have narrowed the problem down to my use of a variable. I have determined that if I use let
, the code fails but it works fine with var
. I get that the problems is due to the scope of the let command but I would like to have some guidance on the best practice of how to make this simple sample work with let
rather than var
.
Here is the code that gets an undefined error:
const yearBorn = 1970;
console.log(yearBorn);
if (yearBorn <= 2020) {
console.log("Less than");
let baseYearCalc = 2021;
console.log(baseYearCalc);
}
console.log(baseYearCalc);
Output is:
1970
Less than
2021
baseYearCalc is not defined
Please let me know how someone who knows what they were doing would solve this problem.
Thanks, Larry
2
Answers
so when you use
var
that variable is hoisted. Essentially it is available outside the scope of your if block.Solution is to define it outside the if block
Question: What should
baseYearCalc
be ifyearBorn
is not less than or equal to2020
? That’s the fundamental problem here, you only declare the variable at all when the condition is true.The trick here is to remember that, generally, declarations using
let
andconst
after an open brace,{
, end with the next closing brace,}
. If you want the variable to exist beyond that, you need to declare them in the outer scope that needs them, even if you give them a value later.For example, in your case, you could do:
This is still flawed:
baseYearCalc
has no value if theif
statement isn’t true. To fix this, you can give it a default value in the originallet
, or assign a different value in anelse
attached to theif
.