Exporting a variable from JavaScript module

By | May 29, 2016

From time to time I do the same error when trying to export some variable from whatever kind of JavaScript module:

Having 13 years of coding experience does not save me from the moment of confusion here :-). If you are also confused, then continue reading.

So, why the result is “Alexander” again? The reason is that s.name and local variable name are totally different variables. The first one is created here as a property of the object, which is being returned from createStudent:

Its value is copied from name variable and this value is reference to the “Alexander” string. So at this point both point at the same object. But then s.setName("Ivan") gives to the name variable (which is closed inside setName and getName) a new value, the reference to the “Ivan” string. The value of s.name does not change, therefore we get “Alexander” again from the console.log(s.name) expression. However, console.log(s.getName()) returnes “Ivan” because it closes name variable inside itself.

So the lesson here is to avoid exporting local variables as module’s properties. One should export functions which close local variables instead. Another interesting option is to use JavaScript’s property feature like this:


Leave a Reply

Your email address will not be published.