Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use a ternary operator and arrow function in this way in JSX?

With babel-preset-react (EDIT: babel version: v6.26.0), the following expression fails with the error "Invalid left-hand side in arrow function parameters" (try on babel repl):

true ? ("test") : x => 42      //FAILS, but only with `babel-preset-react`

Yet it works given a small modification:

true ? "test" : x => 42        //works fine

Both of these scenarios work as expected in seemingly any other configuration.

Is this a bug? Or is there something as a part of JSX parsing that causes this to happen?

like image 660
uber5001 Avatar asked Jan 17 '18 20:01

uber5001


Video Answer


1 Answers

Arrow functions are parsed differently than regular ones see Parsing order

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

let callback;

callback = callback || function() {}; // ok

callback = callback || () => {};      
// SyntaxError: invalid arrow-function arguments

callback = callback || (() => {});    // ok

It must have something to do with associativity of ternary operator (right-to-left) see link

like image 77
stefkin Avatar answered Sep 18 '22 16:09

stefkin