Need help with YDKJS Example

Hi
I need help with understanding one example from YDKJS Scope&Closures.
Here is the code:

var MyModules = (function Manager() {
    var modules = {};

    function define(name, deps, impl) {
      for (var i=0; i<deps.length; i++) {
        deps[i] = modules[deps[i]];
      }
      modules[name] = impl.apply( impl, deps );
      var a = 1;
    }

    function get(name) {
      return modules[name];
    }

    return {
    define: define,
    get: get
    };
})();

MyModules.define( "bar", [], function(){
  function hello(who) {
    return "Let me introduce: " + who;
  }
  return {
  hello: hello
  };
} );

MyModules.define( "foo", ["bar"], function(bar){
  var hungry = "hippo";
  function awesome() {
    console.log( bar.hello( hungry ).toUpperCase() );
  }
  return {
  awesome: awesome
  };
} );


var bar = MyModules.get( "bar" );
var foo = MyModules.get( "foo" );
console.log( bar.hello( "hippo" ) ); // Let me introduce: hippo
foo.awesome(); // LET ME INTRODUCE: HIPPO

Here is link to the book itself: https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md#modern-modules

I do not understand the most part if it, but to start:
why do we need array deps and this loop:

  for (var i=0; i<deps.length; i++) {
    deps[i] = modules[deps[i]];
  }
1 Like

I know the book says to spend a lot of time understanding that snippet of code, but that’s a really difficult-to-understand sample of code. I wouldn’t spend time trying to understand that as long as you get what modules are. I like this article if you want to learn more about modules: https://medium.freecodecamp.com/javascript-modules-a-beginner-s-guide-783f7d7a5fcc#.jbyymk74y

3 Likes