Question

Okay, experimenting with CommonJS module system in the context of NodeJS.

module.exports = pricingCalculator;

function pricingCalculator (options) {
  var target = {};
  return target;
}

This works. Presumably the variable declaration of pricingCalculator is hoisted to the top of the function scope, so the misordering doesnt quite matter as the function is passed by reference anyway. I get that. What I dont understand is why the following two versions that work:

module.exports = pricingCalculator;

var pricingCalculator = function (options) {
  var target = {};
  return target;
}

Fail.

module.exports = pricingCalculator;

pricingCalculator = function (options) {
  var target = {};
  return target;
}

Fail. Curious to understand deeply what is going on.

Was it helpful?

Solution

In first example function is defined before assignment (java script way).
In second and third examples assignments are executed in sequence.

http://studiokoi.com/blog/article/execution_order_of_functions_and_variables_in_javascript_and_actionscript

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top