Use if else to declare a `let` or `const` to use after the if/else?

Johhan Santana picture Johhan Santana · Nov 29, 2016 · Viewed 48.7k times · Source

I'm not sure why but it seems that I can't call the let or const variables if I declare them in an if/else statement.

if (withBorder) {
  const classes = `${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
} else {
  const classes = `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
}
return (
  <div className={classes}>
    {renderedResult}
  </div>
);

If I use this code it says that classes is not defined.

But if I change the const to var classes is defined but I get a warning about classes used outside of binding contextand all var declarations must be at the top of the function scope

How could I fix this?

Answer

maioman picture maioman · Nov 29, 2016

You should use ternary assignment:

const classes = withBorder ?
 `${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center` : 
 `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`

As specified in other comments/answers let and const are blocked scope so that's why they don't work in your example.

For a DRYer code you can also nest the ternary inside string literal:

 const classes = `${withBorder ? styles.dimensions: ''} ${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`