Search code examples
javascriptglobal-variables

Should I ever place a function declaration in global object in javascript


Should I ever place a function declaration or a var function expression in the global object? I see this happen a lot in tutorials, but when you would f.e. use function names like 'atob' or 'btoa', they would override functions of the window object. Or should I always use function expressions and place them in const/let?

An example like this would override functions of the global object and cause problems. Blur() and alert() are built-in functions, so the alert will not work.

    function blur(){
    }

    var alert = function(){
      console.log("Bye")
    }

    alert("Hi");``` 

Solution

  • The way I handle this is I always prefix my function names with "jellyBelly":

    function jellyBellyBlur(){
    }
    
    var jellyBellyAlert = function(){
      console.log("Bye")
    }
    
    jellyBellyAlert("Hi");``` 
    

    So, far, I've had no naming conflicts. I'm a professional.