Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question
up vote 1 down vote accepted

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)

share|improve this answer
    
This answer was awesome, thank you. – Alejandro Gomez Jan 29 at 18:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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