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

JavascriptIf StatementReactjsConstantsLet

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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`

Solution 2 - Javascript

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

Solution 3 - Javascript

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

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

Solution 4 - Javascript

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 https://stackoverflow.com/q/40753492/1048572.

Solution 5 - Javascript

let and const are block level scoped, so you will have to define them outside of the block. var works because it hoists out.

You can defined classes before the if block like @finalfreq

or

let classes = `${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`;

if (withBorder) {
  classes += `${styles.circularBorder}`;
}

Solution 6 - Javascript

ESLint standard likes the operators at the beginning of the line. Long conditionals should also be abstracted out, unless in a computer time loop.

In this particular case the strings are also long, so I would abstract those out too. Problem with Bergi's way is most linters will cripple his style, for conformance reasons.

This way keeps everything normal and easy to read, if you are familiar with ternaries, which you should be.

const styleWithBorder = `${styles.circularBorder} ${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`
const styleWithoutBorder = `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`
const classes = isBorderedElement ? [ styleWithBorder ] : [ styleWithoutBorder ]

Solution 7 - Javascript

Simple, just do this:

const genericStyle = `${styles.dimensions} ${styles.circularPadding} row flex-items-xs-middle flex-items-xs-center`,

classes = withBorder ? `${styles.circularBorder} ${genericStyle}` : genericStyle;

return (
  <div className={classes}>
    {renderedResult}
  </div>
);

This has some clean-up also, the class used twice and only circularBorder is the difference...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohhan SantanaView Question on Stackoverflow
Solution 1 - JavascriptmaiomanView Answer on Stackoverflow
Solution 2 - JavascriptfinalfreqView Answer on Stackoverflow
Solution 3 - Javascriptrap-2-hView Answer on Stackoverflow
Solution 4 - JavascriptBergiView Answer on Stackoverflow
Solution 5 - JavascriptantyangView Answer on Stackoverflow
Solution 6 - JavascriptRay FossView Answer on Stackoverflow
Solution 7 - JavascriptAlirezaView Answer on Stackoverflow