Skip to content
Advertisement

In JavaScript, what is the main benefit of creating an object in one file, export and use it in other file

I’m learning JavaScript and using AWS SDK from JavaScript.

Reading an IAM example from the documentation, i saw the following pattern:

  • Create a file name iamClient.js where you instantiate an object and export it.
  • Create another file where you import the client created above to use it.

What is the main benefit of doing this instead of just create and use the object in the same file ?

I know this is a small example and maybe there is no issue doing everything in the same file, but i’m more curious if this is just for organization/best practice if something bigger is created based on this sample or if there is some sort of technical reason. 🙂

Advertisement

Answer

Well, that’s how you’d create a configuration singleton for instance in another language.

  • Creation of such object might be expensive in time sometimes so you create it once and then just reuse it 🙂
  • During testing, if you provide a mock for your iamClient module you’re set for all unit-tests (assuming you’re using Jest or similar)
  • It also helps you to not repeat yourself as it’s a codesmell
Advertisement