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

  • This is because when you are calling x , at that time y is already defined. So it is not throwing any error. But if you want to call it before defining then it will throw error. Just like console.log(y) is throwing error before defining it. also take. a look at hoisting

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

    But if it is a function declaration then the function will be hoisted to the top

    function x() {
      console.log('hello x');
      y();
    }
    console.log(y)
    
    function y() {
      console.log('hello y')
    }
    x()

    Note the changes in the error when you defined a function expression with const keyword

    const x = function() {
      console.log('hello x');
      y();
    }
    console.log(y)
    
    const y = function() {
      console.log('hello y')
    }
    x()