-2

A project I am working on has some initialization code (not in any function) and some code in a jQuery $(document).ready() event. Which code executes first? Why? I'd also like to know why it might have been written that way? Thanks. For example:

'use strict';
let inputs = [];
function func(){};
function func2(){};
$(document).ready(function(){
  const a = 1;
  func2();
})

2 Answers2

1

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ).ready() method will run once the page DOM is ready to execute JavaScript code.

In this code fun2() will call first after the document is loaded.

Raihan Uddin
  • 116
  • 1
  • 9
1

The code will execute from the top down: 'use strict'; executes first, followed by let inputs = [];, etc.

Note that executing your function definitions function func(){}; and function func2(){}; don't actually call the functions at that point.

Once the document has loaded, it calls the anonymous function passed to $(document).ready() which executes const a = 1; and finally calls func2();.

kmoser
  • 8,780
  • 3
  • 24
  • 40