Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different boolean treatment in string template?

Tags:

javascript

const a = 'hi';
const b = 'newTextHI'
const str = `${a.toUpperCase()}${true && `\n${b.toUpperCase()}`}`;
console.log(str);

const c = 'hi';
const d = 'newTextHI'
const str2 = `${c.toUpperCase()}${false && `\n${d.toUpperCase()}`}`;
console.log(str2);

true will be ignore automatically but false will be evaluated as string?

I understand that ternary operator can get what I want, but I don't understand the reason why boolean being treated differently in the above example

like image 934
Isaac Avatar asked Nov 27 '25 02:11

Isaac


1 Answers

In expression1 && expression2,

if expression1 is truthy, it will return expression2 else it will return expression1. (Documentation)

Same logic is repeatedly applied if it's chained. It will check until a falsy value is found. If not found, the last expression is returned. (Short-circuit evaluation)

// no falsy expressions here
// last expression returned: `string`
console.log(true && `string`)

// short-circuit at false, because what's the point of going further?
console.log(false && `string`) 

// true, 100, "string" are all truthy
// 0 is a falsy value. So, this evaluates until 0 and returns it
console.log(true && 100 && `string` && 0 && "doesn't matter")

In your case, you can use the ternary operator instead:

const a = 'hi';
const b = 'newTextHI'
const decider = false;
const str = `${a.toUpperCase()}${decider ? `\n${b.toUpperCase()}` : ``}`;
console.log(str);
like image 55
adiga Avatar answered Nov 29 '25 16:11

adiga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!