Conditional setState

I came across this line of code this.setState({ errors: errors || {} }); watching a video, I understand it’s purpose but I don’t know why you can use the OR logical operator like that to set the state.

To give you some context, let’s say I have a submit method like this one:

handleSubmit = e => {

    const errors = this.validate();

    this.setState({ errors: errors || {} });
    if (errors) return;

    // Call server

This method submits a form, the validate() method returns an object if there is any error or null if there is none. My approach probably would’ve been something like this:

let errors;
this.validate ? errors = this.validate : errors = {}
this.setState({ errors })

But the first example accomplished the same as the code above by just doing this this.setState({ errors: errors || {} }), why does it work?, I see only a condition.

I can only guess that if errors resolves to null or undefined then it will use the ||

or more likely

if errors resolves to any falsy value then it will use the || which makes it functionally the same to your ternary statement

This is because JavaScript coerces values to booleans when using logical operators, then returns the first truthy (or last value if all values are falsy)

Falsy values: false, null, undefined, 0, NaN, empty string

In your case, since “errors” is falsy, the empty object is used. If you had errors, it would be an object, which is truthy, so it would be returned.

Also, some advice for this code: in this particular case, it’s worth the refactor to make “errors” an array of errors — if there are no errors, the size should be 0. It’s a bit weird to return “null” when everything is valid :thinking:
Returning an empty array (if there are no errors), or an array of errors (if there are errors), makes semantic sense.

I played in the console a bit after reading your comment and this is I what I got:

{a: 1} || {}
// output: {a: 1}
null || {}
// output: {}
{b: 2} && {}
// output: {}
null && {b: 2}
// output: null
null && 0
// output: null
null || 0
// output: 0

So, as you mentioned, Javascript convert both operands into booleans. I also had to read the logical operators description on MDN for these expressions to make sense to me.

This was a bit confusing, but things are clear now, thank you.

edit: in case anyone is interested, this was the article I read, specifically the description chart.