TransWikia.com

Are parentheses ignored when assigning JSX to a variable

Stack Overflow Asked by Di Zhu on December 22, 2021

I’m learning about the javascript basics. The two lines of code seem equivalent and I’m wondering if the parser simply ignores the parentheses in the second case:

var a = 5 + 5;
var b = (5 + 5);

EDIT:
I realize the context of the question might of help after going through the comments, which are helpful. I was trying to assign some JSX to a variable and noticed that the parentheses seem optional:

var a = 
  <div>
    <SomeComponent />
  </div>;
var b = (
  <div>
    <SomeComponent />
  </div>
);  

In the case of a return statement, I understand that parentheses are needed due to automatic semicolon injection. But in case of a simple assignment do the parentheses still matter?

EDIT 2:
Thanks for the comments and answer that help me narrow down and articulate my question. I think what I really meant to ask is, does JSX parser (e.g. Babel) ignore the parentheses in such a case? Since both will be transpiled into:

var a = React.createElement(
  "div",
  null, 
  React.createElement(
    SomeComponent, 
    null
  )
)

One Answer

They're not ignored, but simple mathematics tells you that:

5 + 5 == (5 + 5)

If you had a different set of values, it would change - e.g.:

var a = (5 * 5) + 5 * 5;
var b = 5 * (5 + 5) * 5;
var c = 5 * 5 + (5 * 5);
var d = (5 * 5 + 5) * 5;
var e = 5 * (5 + 5 * 5);
var f = (5 * 5 + 5 * 5);

console.log(a); // 50
console.log(b); // 250
console.log(c); // 50
console.log(d); // 150
console.log(e); // 150
console.log(f); // 50

It depends on the Order of Operations (aka BODMAS/BIDMAS/BEDMAS etc.)

Answered by Jack Bashford on December 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP