Suppose that you begin to code and you declare the following function:
javascriptconst 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:
javascriptconst 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.
numbers
will be the context of the first function:
javascriptlet numbers = { getRandom: () => { console.log(Math.random() * 50); } }
names
will be the context of the second function:
javascriptlet names = { getRandom: (array) => { console.log(array[~~(Math.random() * array.length)]); } }
Now you can declare and launch both functions safely:
javascriptnames.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.