4

This question is about ES6 not about global variables.
When the new ES2015 export or export default were introduced. They were made so that you can import/get the same variables, values or items somewhere else using import. So I have a simple question. Why should we use export and import instead of just making a simple object of a class and getting items through it or just making static or global variables?


I know the fact that it can be used to make your code much cleaner and also to put the code easily into multiple files but let's just assume we have first.js and second.js and we have a variable called names in the first.js that we want to get in the second.js. Now you can either do that with import and export or by making an object in the second.js and accessing our variable by that object. So why is it better to use export and import?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Shariq Musharaf
  • 997
  • 2
  • 10
  • 25
  • You mean "why split up code into multiple files instead of putting all your code in a single, huge file?" Well.... –  Jun 21 '17 at 07:47
  • 3
    How do you get one of those objects defined in one module (read: file) into another module? As you said: global variables. And that's really yucky and prone to naming clashes. So instead you *explicitly `import`* something instead of *implicitly assuming its global presence*. – deceze Jun 21 '17 at 07:47
  • @ChrisG Well you can make multiple files and use objects right? – Shariq Musharaf Jun 21 '17 at 07:47
  • Well, anything you `export` is also an object. Everything in Javascript is an object. – deceze Jun 21 '17 at 07:48
  • @ShariqMusharaf Right, and for a single project you'd be correct, but if you want to create reusable modules, importing only what you need is preferable, see deceze's comment. –  Jun 21 '17 at 07:49
  • I think all of this should be compiled into 1 answer but more simplified lol, I think I'm mixing up a bit with java where you make objects of a class to get the values. – Shariq Musharaf Jun 21 '17 at 07:53
  • 1
    I don't think it's different in Java if you have Java background. Why won't you make everything global in Java so you won't ever need to write all these pesky imports? Wait... that's because this would be total mess, and Java never allowed this, in contrast to JS. – Estus Flask Jun 21 '17 at 08:19
  • 1
    *by making an object in the second and accessing our variable by that object* - what is this supposed to mean?This assumes that this object is global. And in the case of modular environment it's not. – Estus Flask Jun 21 '17 at 08:46
  • @estus Why don't you post all of that down below in the answers lol I'm the one upvoting your comments – Shariq Musharaf Jun 21 '17 at 08:48
  • I don't think that the question can gain a good answer in its current state. When you're asking fundamental JS question in 2017, you can be sure that it was already discussed on SO countless times, and there are answered questions that answer yours too. This isn't specific to ES6 modules but to JS modules in general. All modules implement [Module pattern](https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript) and serve for a good purpose. Encapsulation. The lack of encapsulation is the reason why 'globals are bad'. – Estus Flask Jun 21 '17 at 08:56
  • Possible duplicate of [I've Heard Global Variables Are Bad, What Alternative Solution Should I Use?](https://stackoverflow.com/questions/2613310/ive-heard-global-variables-are-bad-what-alternative-solution-should-i-use) – Estus Flask Jun 21 '17 at 08:56
  • You're welcome. Consider reasking the question in more specific form if you will come up with unsolved parts after the research. – Estus Flask Jun 21 '17 at 09:06

2 Answers2

3

export was introduced to be used alongside import (you need to explicitly declare what you need to later import), as part of the ES2015 module standard.

Before these standard modules were implemented, splitting up Javascript code into multiple files and not have all objects pollute the global object was only possible using sort short of non-standard module definition and/or module loaders like RequireJS. The simplest case was to wrap your code in Immediately Invoked Functions. ES6/2015 just standardize Javascipt modules.

Now you asked why not just have Javascript objects even in many files? The answer to that is namespacing

bluninja1234
  • 73
  • 10
vassiliskrikonis
  • 566
  • 2
  • 10
0

Actually - you make a good point.

namespace stuff is in C++. There are lots of people who think it is cool to have a namespace indicator in front of everything they use. So, instead of saying { cout << my_string << endl; }, their whole program has { std::cout << my_string << std::endl; }. Sometimes you see stuff like { disk::io::byte::bit::atom::neutron::quark::say_hi(2) }. And, the guy who wrote that thinks he's a super developer.

But, as they are purist, it more likely you will see { std::cout << myString << endl; } because camel case is so much more preferential than human readable strings.

Now, in node.js I am always doing something like const ClassFromMod = require('mod-with-class'). In the file, you have to say module.exports = ClassDeclaredInHere. I always do this, because really, is there any other way provided?

Or you can do this const {ClassFromMod} = require('mod-with-class'). Then you have to have, module.exports.ClassFromMod = ClassDeclaredInHere.

So, doing the same thing in the browser is sort of OK. But, now global contexts and local contexts are harder to work with - really. Just a little harder sharing things between modules when you have to. But, not to worry almost all of the time people partitions their modules just right. That's because they are people - in fact the sort of people who are more cautious than those in charge of nuclear reactors - because those people do some web programming. So, no Chernobyl when it comes to partitioning modules. Right?

Now, you can get your hands into a class def. And, the class is itself something of a namespace.

So, then why is there not a global registry of classes? Only that maybe different companies (individual developers) will use the same name for two remotely different classes. But, likely there would be some way around that.

One way might be to assign classes to uses (sort of name spacey). But, it might be more categorical. Like "engine" for something with a car feature, or "engine" for something that runs a script. Programming languages might have something like "talking about cars here". What would that be like?

 start>> talking about cars <
 let bval = engine.rev()
 if ( bval ) {
   <about scripts> engine.run("small program")
 }
 <<stop talking about car

That's an idea. Looking at it, I don' like it. It's sort of like "with" that lots of languages use.

So, with new strictures imposed on the programming environments, you get bugs and scope troubles that add to your long long long day. But, you should get that your question drawn from clear thinking is in some sense being steamrolled by a small group of people who can. And, you can take out the trash for them.

So, what about identifying objects by features and enabling sort of a flat namespace management? Could be driven by AI. Could have been done thirty years ago. But, now is now. But, the future exists for correcting the mistakes of the past.