chefcurry7 chefcurry7 - 2 months ago 9
Javascript Question

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

Lets 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

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

How can I use let in this situation?


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.