Reputation: 36580
What I get from previous posts and articles is that the exports object is located on the global
object. I came across this code which confused me:
let blue = 'blue'
let red = 'red'
var exports = module.exports = {
red,
blue
};
This code sets module.exports
to a variable called exports
which then gets set to an object which gets exported.
I am confused however by this syntax:
Example1:
var exports = module.exports = {}
How does this work exactly? Because normally in JS you can't assing a variable two times. For instance this gives an error:
Example2:
let foo = 5 = 4;
How does the code in example 1 give no error while the code in example 2 does?
Upvotes: 0
Views: 709
Reputation: 101652
Your interpretation of what the line is doing is incorrect.
This code sets module.exports to a variable called exports which then gets set to an object which gets exported.
What is actually happening is that the value { red, blue }
is being assigned to module.exports
, and then that same value ({ red, blue }
) is being assigned to exports
.
In JavaScript and other languages with similar syntax (C, C++, C#, Java) someAssignableThing = someValue
is treated as an expression, and you can use a = b
as a sub-portion of other expressions and chain as many together as you want.
As an expression someAssignableThing = someValue
equates to "assign someValue
to someAssignableThing
and evaluate to the value someValue
".
So the statement:
a = b = c = d = e = 5;
would assign the value 5
to a
, b
, c
, d
, and e
.
It is a syntax error to have something on the left side of the =
that cannot be assigned a value and that's why you get an error in the second case (you cannot assign a value to 5
).
Upvotes: 1
Reputation: 138235
let foo = 5 = 4;
Cause its parsed from right to left:
let foo = (5 = 4);
And 5
is not a variable, so you cant assign stuff to it. However it works with an identifier:
let bar;
let foo = bar = 5;
Upvotes: 2