Menu

Post image 1
Post image 2
1 / 2
0

JavaScript Modules Explained: Import, Export, and Why Your Code Will Thank You

DEV Community·Janmejai Singh·24 days ago
#NbUVwLu2
Reading 0:00
15s threshold

Stop writing 1,400-line JavaScript files. I've been there. You come back to a project after three weeks. One file. Everything in it. Functions calling other functions. Variables defined on line 847, used on line 12. You scroll up. You scroll down. You question your career choices. That's the problem ES Modules solve. And they do it elegantly. Let's get into it. Why Modules Exist (The Problem First) Before ES Modules were standard, JavaScript files shared a single global scope via <script> tags: <script src= "utils.js" ></script> <script src= "cart.js" ></script> <script src= "app.js" ></script> Enter fullscreen mode Exit fullscreen mode Every variable from every file lived in the same global bucket. The consequences were predictable: // utils.js var discount = 0 ; // cart.js — loaded after utils.js var discount = 0.15 ; // 💥 silently overwrote utils.js's variable // app.js console . log ( discount ); // 0.15 — but was this intentional?…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More