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.
=has lower precedence than===and&&, so your expression is being parsed aswhich is invalid because you can't assign to an expression. Add parentheses to force the intended grouping
That said, most programmers think it's poor form to use logical operators in place of control flow. Use an
ifstatement for this.