What does this type of notation mean?
render() {
const {isAuth, error} = this.state;
document.getElementById("root").innerHTML = `
<div style="color: ${error && "red"}">
${isAuth ? "Welcome back!" : error}
</div>
`;
}
I do not understand why is it written like this. And what does it mean in a style property?
CodePudding user response:
This is an example of short-circuit evaluation.
result = '' && 'foo'; // result is assigned "" (empty string)
result = 2 && 0; // result is assigned 0
result = 'foo' && 4; // result is assigned 4
''
is falsy, so an empty string is returned.2
is truthy, so 0 is returned.'foo'
is truthy, so 4 is returned
Essentially, if error
is true, then this:
`<div style="color: ${error && "red"}">`
will become this
`<div style="color:red">`
And if error is false
, then the code will become
`<div style="color:false">`
Additionally, if error were to be ""
, then the code will become
`<div style="color:">`
And if error were to be "foo"
or another truthy value, then the code will become
`<div style="color:red">`
CodePudding user response:
I am guessing a little bit here, because depending on the framework those could maybe mean something different. But i am assuming that it is vanilla JS we are talking about (or a framework that uses vanilla js conditions)
Here is a small example:
const apple = true;
const ananas = false;
console.log('1', apple && 'it is an apple'); // returns "1 it is an apple"
console.log('2', ananas && 'it is an ananas'); // returns "false"
This notation is calle "short circuit evaluation".
From MDN: The logical AND expression is a short-circuit operator. As each operand is converted to a boolean, if the result of one conversion is found to be false, the AND operator stops and returns the original value of that falsy operand; it does not evaluate any of the remaining operands.
So writing conditionOne && doSomething
is kind of the same as writing if (conditionOne) { doSomething }
You can read about it on MDN (short-circuit evaluation)