How to declare a global variable inside a jQuery function

Ciprian on Tuesday, May 17, 2022 in Methods, Events and Scopes

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

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;


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

Leave a Reply

Your email address will not be published. Required fields are marked *