简体   繁体   中英

Why inside a function you can use a variable that's declared later

I was writing a Dialog component and this thought came into my mind suddenly.

export const alert = (content: string) => {
  const buttons = [<button onClick={()=>closeModal()}>ok</button>] // quite ok 
  // const buttons = [<button onClick={closeModal}>ok</button>] // raise an error
  const closeModal = modal(content, buttons)
}

The error is: Block-scoped variable 'closeModal' used before its declaration. I am so used to wrap some expression in a function in React and never thought about it.

The situation may be simplified to below:

const caller = () => {
  func() // ok
}
const funcAgain = func // error
func() // error
const func = () => {}

What's this behavior called? Does it have something to do with closure? or variable hoisting?

This has to do with the basics of The variable declaration and scope management and then execution phase. Here variable declarations for blocked scope variables(let, const), are actually hoisted but not initialised. Js engine simply denies any operation on uninitialized variable identifiers.

Also there is famous term for this called as Temporal Dead Zone(TDZ). func is in its TDZ in this case.

Hope this helps.

Good question. onClick on the first sample works because it returns a new Function object. The body of the function does not get evaluated until it is being invoked.

()=>closeModal()

I think you are referring to 'Hoisting'. To hoist a function, you need to declare as below

const caller = () => {
  func() // ok
}
func() 
function func () {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM