0

The following throws and error "module is not defined" in a browser. Why and how can I avoid the error given that I cannot be sure ahead of time that module will be defined?

;(function() {
    var version = '0.0.1';

    /**
     * This file needs to work in
     * both NodeJS and browsers.
     */
    if (module) {
        module.exports = version;
    } else {
        define(function() {
            return version;
        });
    }
}());
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 1
    see also [JavaScript check if variable exists (is defined/initialized) - Which method is better?](http://stackoverflow.com/q/5113374/1048572) – Bergi Mar 19 '15 at 18:45

1 Answers1

2

Add in this check to see if module has been defined

if(typeof module !== "undefined") {
    // do stuff
}

In your example, you get an exception because module has not been declared or assigned by the time it gets to your condition. So when you try to check if it's null or not by doing if(module), the variable has never been assigned so it throws and exception. Your code would work if right before the condition you did var module = null. Even though you set it to null it has been assigned, so it's not undefined.

Using typeof allows the identifier to never have been declared before, and because of that you can avoid the exception you're experiencing.

sbonkosky
  • 2,537
  • 1
  • 22
  • 31
  • Why does that work, and my example does not? – Ben Aston Mar 19 '15 at 18:20
  • @BenAston I edited my answer to try and explain the difference. – sbonkosky Mar 19 '15 at 18:24
  • But I am not checking for null. I am checking for truthiness. `module` is `undefined` and hence should coerce to `false` surely. I am not in strict mode, so no error should be thrown, no? – Ben Aston Mar 19 '15 at 18:34
  • `var foo; if (foo) {...` is different of `if (foo) {...` in the last case you will get the error because there is no `foo` var, or, in your case, the `module` var – Victor Mar 19 '15 at 18:43