chefcurry7
chefcurry7

Reputation: 5241

How to use ''let" instead of "var"

Let's say I have this code:

  if (input.length >= 3) {
     var filtered_school = _.filter(schools, function (school) {
         return _.startsWith(school.label, input);
    });
  }
this.setState({ options: filtered_school })

I can't use 'let' as it can't be seen outside the scope so I can't assign filtered_school to options.

But I hear that there is no reason to use var in ES6.

How can I use let in this situation?

Upvotes: 2

Views: 185

Answers (4)

Leon
Leon

Reputation: 12481

let is block scoped, so if let is somewhere inside {}, or in a logical block, it will only be accessible there. To make it accessibly outside of your example place it outside the if statement.

 let filtered_school;
 if (input.length >= 3) {
     filtered_school = _.filter(schools, function (school) {
         return _.startsWith(school.label, input);
    });
 }

Upvotes: 1

Thalaivar
Thalaivar

Reputation: 23632

let creates block level scope in ES6, you can declare it outside and assign it in your filter.

let filtered_school;
 if (input.length >= 3) {
    filtered_school = _.filter(schools, function (school) {
         return _.startsWith(school.label, input);
    });
  }
this.setState({ options: filtered_school })

Upvotes: 1

Quentin
Quentin

Reputation: 943564

You declare the variable in the scope you want to use it in. i.e. outside of the if block.

let filtered_school;
if (input.length >= 3) {
  filtered_school = _.filter(schools, function(school) {
    return _.startsWith(school.label, input);
  });
}
this.setState({
  options: filtered_school
})

Upvotes: 4

nem035
nem035

Reputation: 35491

Just put it outside the if:

let filtered_school;
if (input.length >= 3) {
  filtered_school = // ...
});

let is block-scoped, meaning if you define it within the if block, it won't exist outside of it so you have to extract it out in this situation.

Upvotes: 4

Related Questions