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

let and const are block level scoped meaning they can only be used within the block they have been defined in ie. { // if defined in here can only be used here }

In this case I would just define above the if/else statement

let classes;

if (withBorder) {
  classes = `${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
} else {
  classes = `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
}

Don't use an if-else-statement but a ternary expression:

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`;

Alternatively, just declare it outside of the if block, which allows you to get rid of the duplication as well:

let classes = `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;
if (withBorder) {
  classes += ` ${styles.circularBorder}`;
  // or if you care about the order,
  // classes = `${styles.circularBorder} ${classes}`;
}

Also have a look at messy classnames construction.


Alternative (not sure it's good nor elegant though):

const classes = (() => {
  if (withBorder) {
    return `${styles.circularBorder}...`;
  } else {
    return `${styles.dimensions}...`;
  }
})();

This is a good example of where a simple ternary assignment could suffice:

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 block scoped, so that's why they don't work in your example.

For DRYer code, you can use the ternary only for the part that depends on it:

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