Understanding Arrow Function Behavior with Conditional Operations in JavaScript

71 Views Asked by At

I'm learning arrow functions in JavaScript and attempting to conditionally set the value of show to false based on a certain value. While using the '&&' operator for this purpose, I encountered a syntax issue with the following code:

const obCallback = (something) =>
    something.value === 1
    && show = false;

I know it works when I do this:

const obCallback = (something) => {
    if (something.value === 1) {
        show = false;
    }
};

or this:

const obCallback = (something) => something.value === 1 ? show = false : undefined;

Can anyone of you please explain why the first code snippet doesn't work and the other do? Can we only do function calls but not assignments after "&&" in an arrow function, because the below seems to be working?

const obCallback = (something) =>
    something.value === 1
    && Dance(); //This works

I know this seems like a basic question but I'm seeking a thorough explanation to improve my understanding of using arrow functions in the future.

1

There are 1 best solutions below

0
Barmar On BEST ANSWER

= has lower precedence than === and &&, so your expression is being parsed as

const obCallback = (something) =>
    (something.value === 1
    && show) = false;

which is invalid because you can't assign to an expression. Add parentheses to force the intended grouping

const obCallback = (something) =>
    something.value === 1
    && (show = false);

That said, most programmers think it's poor form to use logical operators in place of control flow. Use an if statement for this.