Today i saw this code, that was running in node.js environment. (>node.exe test.js)
var param = (typeof module !== "undefined" && module.exports) || {};
(function(exports){
console.log(exports === module.exports);
})(param);
And this log returned true.
Can anybody explain me such behavior?
Thanks in advance.
If module
is not undefined (which it isn't since it is the default object) and module.exports
is a truthy thing (which it is by default), then exports
is assigned to param
and passed to the function.
exports
is then compared to module.exports
, and they are the same because module.exports
is where the object came from in the first place.
(exports
wouldn't be the same as module.exports
if it was running elsewhere (e.g. a browser where you get window
, not module
) since {}
would be assigned to param
instead.)
Update re comments on the question:
Hmm, maybe it's wrong, but i thought that ((typeof module ..) || {}) will return true, but not "exports" object
No. &&
will (working left to right) evaluate as the first falsey thing it tests or (if everything is truthy) the last truthy thing it tests.
typeof module !== "undefined"
is true so it tests module.exports
, which is also true so it returns module.exports
.
(The ||
returns the first truthy or last falsey thing it tests, so it then returns module.exports
)
var d = (a && b) || c
d
evaluates to b
if a
is true. If a
is false, d
evaluates to c
.