skip to Main Content

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()

2

Answers


  1. 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')
    }
    Login or Signup to reply.
  2. 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()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search