Why cannot we use 'let' like this? -Scope Problem

Hi everyone,

Why do we cause error here? why cannot we use multiple ‘let’ s ? Thank you

const getTrainingDays = event => {

  if (event === 'Marathon') {
   let  days = 50;
  } else if (event === 'Triathlon') {
   let  days = 100;
  } else if (event === 'Pentathlon') {
   let days = 200;
  }

  return days;
};

let is block-scoped, so only exist within the (else) if block/clause.

so you can do:

const getTrainingDays = event => {
  let days;
  if (event === 'Marathon') {
     days = 50;
  }

or you can choice not to use an intermediate variable and use return right away.

1 Like