Monday, May 20, 2024
-6
rated 0 times [  0] [ 6]  / answers: 1 / hits: 95015  / 8 Years ago, tue, november 29, 2016, 12:00:00

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?


More From » if-statement

 Answers
15

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`

[#59876] Monday, November 28, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luna

Total Points: 698
Total Questions: 114
Total Answers: 93

Location: Israel
Member since Wed, Apr 14, 2021
3 Years ago
luna questions
;