JavaScript namespaces: a simple example

Suppose that you begin to code and you declare the following function:

javascript
const getRandom = () => {
    
    console.log(Math.random() * 50);
    
}

Later on, when you are going to finish your program, you need a function to print a random string from an array:

javascript
const getRandom = (array) => {
    
    console.log(array[~~(Math.random() * array.length)]);
    
}

If you declare with the same name as the first one, you'll get an error. Namespaces are useful to prevent different functions with the same name to collide.

First namespace

numbers will be the context of the first function:

javascript
let numbers = {
    
    getRandom: () => {
        
        console.log(Math.random() * 50);
        
    }
    
}

Second namespace

names will be the context of the second function:

javascript
let names = {
    
    getRandom: (array) => {
        
        console.log(array[~~(Math.random() * array.length)]);
        
    }
    
}

Now you can declare and launch both functions safely:

javascript
names.getRandom(['Erik', 'Bill', 'Jeff', 'Elon']); // Erik
numbers.getRandom(); // 49.0108007834264

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.