Search code examples
javascriptfunctionhoisting

function is hoisted. fun1 called fun2. in what order are they declare?


I want to know the order in which the function is declared in javascript.

function ex1() {
  document.write("ex1")
}

function ex2() {
  ex1();
}
ex2();
//result is ex1.
function ex2() {
  ex1();
}

function ex1() {
  document.write("ex1")
}
ex2();
//result is ex1.

I expect an error to occur if change the order. I know js use hoisting. But at the top, I thought it would be declared in order . How was the function called?


Solution

  • JavaScript reads through the file first, specifically looking for the function keyword, and storing those functions and their scopes, then after that it calls the code. All functions declared with the function keyword, no matter where, as long as they're in an accessible scope from their caller, are available anywhere in the file.

    In your specific example, you're defining both of the functions at the top of the file before you call either one of them - so your code will work regardless.