1
\$\begingroup\$

I am experimenting with ES6 using BabelJS in a codepen project you can find here. I am confused as to why my code breaks when I decide to use let instead of var in the following function:

function getUnits(country) {
const imperialCountries = ['US', 'BS', 'BZ', 'KY', 'PW'];

if (imperialCountries.indexOf(country) === -1) {
  var units = 'metric';
} else {
  units = 'imperial';
}
console.log(country, units);
return units;
}

Thank you!

\$\endgroup\$
2

2 Answers 2

1
\$\begingroup\$

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)

\$\endgroup\$
0
2
\$\begingroup\$

let and const allows us to declare block scoped variable. In your code

if (imperialCountries.indexOf(country) === -1) {
  var units = 'metric';
} else {
  units = 'imperial';
}

when you replace var with let the variable units becomes a block scoped variable and is recognized only inside the if block. You can make the following change in your code to use let:

let units;
if (imperialCountries.indexOf(country) === -1) {
  units = 'metric';
} else {
  units = 'imperial';
}
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.