DEV Community

Cover image for JavaScript Namespace Equivalent is the FileName
John Peters
John Peters

Posted on

JavaScript Namespace Equivalent is the FileName

We've been discussing the power of Javascript modules which aggregate functions, all of similar concerns, and put into a file; which is a descriptive name of what they do. For example:

FileName : array.ts
function findIndex(array,predicate)...
function addToTop(array,row)...
function moveToBottom(array,row)...

Enter fullscreen mode Exit fullscreen mode

Each function in our module or container being array.ts, is strictly related to array work. Now assume other modules' functions wanting to apply the reusable array functions. The Architect also requires all function names that reuse the functions to be the same name.

FileName: AddressComponent.ts
// Same name as in our reusable function
function addToTop(row){
  // we want the reusable function here
  addToTop(this.addresses, row)
}
FileName: PeopleComponent.ts
// Same name as in our reusable function
function addToTop(row){
  // we want the reusable function here
  addToTop(this.People, row)
}
FileName: Delivery.ts
// Same name as in our reusable function
function addToTop(row){
  // we want the reusable function here
  addToTop...
}
Enter fullscreen mode Exit fullscreen mode

Anytime we type in addtoTop, intellisense shows more than one function. How do we discern which one we want? The answer is via the import statement we use.

import {addToTop} from 'array.ts';
import {addToTop} from 'AdddressComponent.ts';
import {addToTop} from 'PeopleComponent.ts';
import {addToTop} from 'Delivery.ts';
Enter fullscreen mode Exit fullscreen mode

But the IDE will flag each subsequent import as an error. This is the equivalent of a 'namespace collision' in .NET. The compiler cannot know which one to use when it's referenced!

We help the IDE and ourselves simply by changing the name in the import.

import {addToTop} from 'array.ts';
import {addToTop as AddrAddToTop} from 'AdddressComponent.ts';
import {addToTop as PeopleAddToTop} from 'PeopleComponent.ts';
import {addToTo as DeliveryAddToTop} from 'Delivery.ts';
Enter fullscreen mode Exit fullscreen mode

The namespace is the fileName and the variable name allows us to determine which one. Variable names go a long way in describing what is really happening, but in the case of any remaining ambiguity, code comments are invaluable.

\** @description This is a code comment 
* @param Here is doc on the first parameter
* @returns Tells the users what is returned
*\
Enter fullscreen mode Exit fullscreen mode

While code comments appear slightly messy, they more than make up for it, when new developers are trying to learn the API.

JWP 2020 NameSpace JavaScript Modules

Top comments (0)