user9623401
user9623401

Reputation:

Why we don't need to add semicolon to the end of jsx?

I'm new to React and JSX, just a question on JSX syntax, we know we can do like:

export default function App() {
  return <h1>Hello World</h1>
}

but don't we need to add semicolon to the end of jsx ? As:

export default function App() {
  return <h1>Hello World</h1>;
}

Upvotes: 2

Views: 1539

Answers (2)

jsejcksn
jsejcksn

Reputation: 33721

JSX doesn't affect anything in this scenario compared to normal JS syntax.

export default function App() {
  return <h1>Hello World</h1>;
//^^^^^^                     ^
//       ^^^^^^^^^^^^^^^^^^^^
//  1             2          3
//keyword    expression   end of statement
}

When writing code using JSX syntax, each JSX expression is simply an expression, like any other expression. More specifically, each JSX expression is evaluated by the transpiler and converted into a function invocation expression — you can read more at the article JSX In Depth on the React website.

Whether you return a JSX value or a number value or a string value makes no difference in regard to the need for a semicolon.

const myValue = "hello world";

export default function () {
  return myValue;
//^^^^^^        ^
//       ^^^^^^^
//  1       2   3
//keyword   ^  end of statement
//      expression
}

Regarding semicolon usage: I won't get into the reasons why semicolons should be used — that has already been covered on this site.

Upvotes: 2

Sulthan
Sulthan

Reputation: 130102

In javascript semicolons are optional in most situations because they are inserted automatically.

There are not many situations when you actually have to use them and there is an ongoing discussion between developers whether to write semicolons explicitly or not.

See http://www.bradoncode.com/blog/2015/08/26/javascript-semi-colon-insertion/ for more details.

Upvotes: 0

Related Questions