In this function why is “ho” printed first instead of “hello”

function init() {
    console.log("hello " + validate());
}
function validate() {
    console.log("ho ");
    return 'hi'
}
init()

The output of this code is:

ho
hello hi

I can’t make sense of the order. What am I missing?

Answer

I’ll try to show the ‘order of operations’

  1. Call init()
  2. init() will console.log, but needs the result of validate() to do so
  3. validate() is called
  4. validate() outputs ho using console.log
  5. validate() returns hi to init
  6. init() will now console.log the complete string
ho             <-- Result of validate() being called to get value in init
hello hi       <-- Result of init()` console.log