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
moduleis not undefined (which it isn’t since it is the default object) andmodule.exportsis a truthy thing (which it is by default), thenexportsis assigned toparamand passed to the function.exportsis then compared tomodule.exports, and they are the same becausemodule.exportsis where the object came from in the first place.(
exportswouldn’t be the same asmodule.exportsif it was running elsewhere (e.g. a browser where you getwindow, notmodule) since{}would be assigned toparaminstead.)Update re comments on the question:
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 testsmodule.exports, which is also true so it returnsmodule.exports.(The
||returns the first truthy or last falsey thing it tests, so it then returnsmodule.exports)