In order to avoid conflicts of interests it is always a good idea to keep variable names unique.
Avoiding name duplication is easy to do in a simple demo script but in real life it is not so easy. Actually it is virtually impossible because code comes from different sources, the ones we write ourselves and the ones provided by applications we link to.
What we can do to prevent such conflict of interest is to isolate our own code into a closed circuit. This type of implementation if called encapsulation.
There are many ways of applying encapsulation. One such way is to include our code inside of a function. Another way is to write it as an object.
- A function has its own scope which protects its declared assets from being mistaken by global items with the same name.
- As for items inside of objects, they require proper addressing whenever we want to use them. That in itself prevents us from calling the wrong global item by mistake.
I show a few simple encapsulation examples on my latest post at jsplain.com.