React.js provides JSX as an XHTML-like syntax for constructing a tree of components and elements. JSX compiles to Javascript, and instead of providing loops or conditionals in JSX proper, you use Javascript directly:
<ul>
{list.map((item) =>
<li>{item}</li>
)}
</ul>
What I haven't been able to explain yet is, why is this considered good if analogous constructs are considered bad in JSP?
Something like this in JSP
<ul>
<% for (item in list) { %>
<li>${item}</li>
<% } %>
</ul>
is considered a readability problem to be solved with tags like <c:forEach>
. The reasoning behind JSTL tags also seem like they could apply to JSX:
- it's a little easier to read when you aren't toggling between XHTML-like syntax (angle brackets, nesting) and Java/Javascript (curlies, commas, parens)
- when you have the full language and platform available for use inside the rendering function, there's less to discourage you from putting logic in that doesn't belong there.
The only reasons I can think of why JSX is different is:
in Java, you had an incentive to do the wrong thing - JSP would be hot-reloaded, so it was tempting to put code in JSPs to avoid a rebuild/restart cycle. Maintainability was sacrificed for immediate productivity. Banishing scriptlets and limiting to a fixed set of template constructs was effectively a way of enforcing maintainability. No such distortion exists in the JS world.
JSP and Java syntax is clunky with the extra
<% ... %>
to distinguish Java code from element generation, and with Java's native syntax lacking aforeach
concept or first-class functions (until recently). The syntax penalty of using native Javascript for loops and conditionals in JSX is non-zero (in my opinion) but not as bad as JSP, and arguably not bad enough to warrant introducing JSX-specific elements for loops and conditionals.
Is there something else I'm missing?