JavaScript Modules: A Beginner’s Guide
Preethi Kasireddy
9.6K113

Hi Preethi, thanks for the detailed explanation of modules in JavaScript. I got some of my understandings corrected. Thanks again.

There are a couple of points I wanted to differ with you.

1.
You: In JavaScript, functions are the only way to create new scope
Me: This might be true earlier, but, with ‘let’ variables, we can create variables/objects with block scope. Hence, if we don’t have to accept any parameters, instead of using an IIFE, we can just wrap the module definition in a pair of flower brackets — {}

2. 
You: In this example, we basically make two copies of the module: one when we export it, and one when we require it
Me: I don’t think there are two copies of ``counter`` module. It’s just one copy. In the example that you have taken, the counter member of the object being exported is not a reference type — but value type as it is a primitive. Hence, the statement ``counter.counter`` refers to the copied value of module local variable ``counter``. Whereas the ``increment()`` method is refering to the local variable ``counter`` from it’s closure. Hence, if all members of the exported object are object references (no primitive), we won’t see any difference. I have also tried to search for any documentation on imported object being a copy of exported, but, could not find any references. Please correct me if I’m wrong.

And, on another note, I loved the way that you have presented ‘easy to reason about’. Thanks for that wonderful presentation.

Like what you read? Give Prabhakar Peri a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.