How to declare a global variable inside a jQuery function

on in Methods, Events and Scopes
Last modified on

A JavaScript global variable is a variable with global scope, meaning that it is visible and accessible throughout the program, unless shadowed. This article deals with a problem I used to bang my head about the other day.

jQuery (or JavaScript) global variables

I needed to declare a global variable inside a JavaScript function, and then read it inside another function. If the first function isn’t called/initiated, the second function doesn’t know the value of the global variable.

For example, this function sets the sort order of a column of a table, nothing really interesting:

function clickMe(sortOrder) {
    sortOrderNew = sortOrder;
}

When the function is executed, a global JavaScript variable is set. Notice there is no var or let or const in the declaration.

This line:

let sortOrderNew = sortOrder;

Would set a local variable inside the said function.

Now, a second function needs this global variable. If it is set, it will automatically pick it up, if not, it will set a local variable with a fallback value:

function chipPaginate(page) {
    if (typeof sortOrderNew === 'undefined') {
        let sortOrder = 3;
    }

    if (typeof sortOrderNew !== 'undefined') {
        let sortOrder = sortOrderNew;
    }

    console.log(sortOrder);
}

Notice I’m doing some checks to see if sortOrderNew is defined. If not, it will assign it the value of 3 (it makes sense inside my function). Again, notice I’m using var in front of my variables, to set them locally.

Global variables conclusion

if (typeof myVariable === 'undefined') checks if myVariable is defined or not.

let myVariable = 5;

Omitting var (or let or const) will make myVariable global (i.e., readable among functions and available to other code).

Related posts