Create Global Functions In JavaScript

Normally, a function defined would not be accessible to all places of a page. Say a function is mentioned using “function checkCookie()” on a external file loaded first on a page. This function cannot be called by the JavaScript file loaded last. So you have to make it a ¬†Global function that can be called from anywhere on a page.

The “window” is a Global Object that has a lot of functions.

> typeof window
< "object"

This “window” object is accessible to all JavaScript code of a page, even if it’s an external file. So, if the “window” object is global, then the functions it contain will also be global. So, if we add a new function to the “window” object, it will be a global function. This is what we are going to do to make a Global function.

Here is a normal way that we use to define a function :

function checkCookie(){
 // do whatever you want here

As you already understood, this function wouldn’t be accessible to all JS codes. The error that produce when a function can’t be accessible is :

ReferenceError: checkCookie is not defined

To make the “checkCookie” function global, we are going to add the function to the “window” object :

 // do whatever you want here

Note the semi colon (“;”) at the closing of the function. This semi colon is required when defining a function on a object. As normal you can add parameters to the function.

Another Example :

function makeString(string, position){
 // do whatever you want here

can be made global by :

window.makeString=function(string, position){
 // do whatever you want here

Now, you can call the function directly or call it with window :


makeString("", 5)
window.makeString("", 5)

The output of the different ways to call functions will be the same. You should know that jQuery is also doing this to make “$” & “jQuery” functions global.