Remember, let
variable bindings are local to the scope. In your example you have two scopes inside the getUnits
function:
function getUnits(country) {
// function scope
if (imperialCountries.indexOf(country) === -1) {
// scope 1
} else {
// scope 2
}
}
If you declare a variable using the let
keyword in either of the inner scopes, it will be unbound once that scope finishes.
When you declare variables with the var
keyword they will still be bound outside of the inner scopes of the given function. Effectively, using var
as in your example, is the same as this:
function getUnits(country) {
var units;
if (imperialCountries.indexOf(country) === -1) {
units = 'metric';
} else {
units = 'imperial';
}
}
If you wish to use let
then just replace the var
in the above example with it.
One more thing, since the imperialCountries
variable is a const
, it might be better to keep it outside of the getUnits
function. (Unless you do not wish to pollute the global namespace)