Do my functions have to be defined in jQuery's .ready() method?


#1

Question

Do my functions have to be defined in jQuery’s .ready() method?

Answer

No, they don’t. When using jQuery we can define the functions we want to use after our document is loaded, inside of jQuery’s .ready() method. This way of defining functions ensures that our functions are scoped to the .ready() method and will not be available for access from outside of .ready(). If we define our functions outside of .ready() said functions will be available for use both inside and outside of .ready().

Defining a function inside .ready():

$(document).ready(() => {
  function sayHello (){ //defines sayHello inside the .ready() method
    console.log('hello');
  }
});

sayHello(); //this will error as sayHello is not available outside of the .ready() method

Defining a function outside of .ready():

function sayHello () { //defines sayHello outside of the .ready() method
  console.log('hello');
}

$(document).ready(() => {
  sayHello(); //sayHello is available inside .ready()
});