I was seeing the code of "withHandler.js" in npm module recompose and I came across the following code snippet
var factory = (0, _react.createFactory)(BaseComponent);
I am seeing this similar styled code snippet at many places in react libraries.
May please someone help understand, how to read this code snippet.
N.B. _react is react it was defined as _react= require('react')
Asked
Active
Viewed 42 times
0

frogatto
- 28,539
- 11
- 83
- 129

Akshay Vijay Jain
- 13,461
- 8
- 60
- 73
-
1You are seeing the application of the [comma operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator). – Jorj Feb 03 '19 at 12:23
-
Thank you so much Jorj, I couldn't guess, it might be coming from babel – Akshay Vijay Jain Feb 03 '19 at 12:34
1 Answers
3
First learn how comma operator works in JavaScript. It evaluates the operands from left to right and returns the last one. So, (0, a.b)()
evaluates to (a.b)()
and then a.b()
.
Q: So, what's the point of (0, a.b)()
? Why not a.b()
?
A: When you write a.b()
, this
inside b
refers to the a
not to the global object. However in (0, a.b)()
you're calling b
while this
refers to the global object.
So, calling (0, _react.createFactory)(BaseComponent)
ensures that this
inside createFactory
function refers to the global object.

frogatto
- 28,539
- 11
- 83
- 129