I'm starting to use ReactJS with Github Copilot, i was trying to build a calculator, and needed that the input field clean after click one operation, and copilot suggested:
Class component:
const { total, next, operation } = this. State;
const current = next || total || 0; // What is this doing?
DOM Printing:
<div className="calcresult">
{current}
</div>
Its working perfectly but i don't know what is the || doing in the variable: current
.
CodePudding user response:
I found out that is a short circuit operator, if the first value is falsie it goes to the second, if the first and the second are falsie it goes to the third, if the first variable is empty, indefine or null it goes to the next.
Geeks for Geeks JS Short Circuiting
CodePudding user response:
const current = next || total || 0; // What is this doing?
Let's break this out
- First it checks if
next
variable if it has true value, a true value can be an integer greater than 0, a non-empty string, a non-empty array. if it is, then thecurrent
value will be equal tonext
- If
next
don't have a true value, then it checks the true value oftotal
- If none of the
next
andtotal
has a true value, the default value will be0