Search code examples
javascriptfunctionhoisting

Why can I use arrow javascript function before its initialization


I checked out Why can I use a function before it's defined in JavaScript?. and It says I can use functions before or after initialization when using Declaration Functions. However for the case of Expression Functions I need to initialize before use.

But check my code please. I used Expression Functions and I can use it even before initialization.

const x = () => {
  console.log('hello x')
  y() // why can I use it here???
}

const y = () => {
  console.log('hello y')
}

// later use somewhere in HTML
x()


Solution

  • Because it is just a definition.

    If you write x() before the definition of y, there would be an error.

    const x = () => {
      console.log('hello x')
      y() // why can I use it here???
    }
    
    x() // error
    
    const y = () => {
      console.log('hello y')
    }