Prevent Duplicate Javascript Variables

So I’m working with WordPress and just spend an hour tracking down an issue between two plugins. They both use the same javascript variable ‘d’ but for different objects, so I had to change one of them to ‘e’, but those changes will be lost if the plugin ever updates.

There’s thousands of plugins for WordPress, it’s no surprise that programmers are using the same variables. Is there a way to prevent your own variables from being accidentally overwritten?

Related posts

Leave a Reply

2 comments

  1. You can wrap your code with a function expression:

    (function(){
        var e = 1;
    }())
    

    In the code above, nothing outside the function can touch your variables and your variables don’t destroy other global variables of the same name.

    Just remember that since your variables are not visible outside the function, all of your code that refers to them must also be inside it.