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 context
and all var declarations must be at the top of the function scope
How could I fix this?
Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false. Use switch to specify many alternative blocks of code to be executed.
Constants are block-scoped, much like variables declared using the let keyword.
As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable.
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`
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`; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With