Eric Smith
Eric Smith

Reputation: 103

Why can you reference a variable before declaring it in a function property of an object?

Basically, I'm looking for an explanation of why and how this is working

const someObj = {
    test: () => callback()
}

const callback = () => console.log("how?")

someObj.test()

output: how?

and this is not

const someObj = {
    test: callback()
}

const callback = () => console.log("how?")

someObj.test

output: Uncaught ReferenceError: Cannot access 'callback' before initialization

Upvotes: 3

Views: 103

Answers (1)

Adrian Brand
Adrian Brand

Reputation: 21638

In your first example you are assigning a function to the property test. It doesn't try to call callback until you call it. By the time you do call it callback has been defined. Try calling test before you define callback and you will see if also fails.

In your second example you are trying to assign the result of calling callback to the property test, but seeing callback hasn't been defined yet you get the error.

Upvotes: 3

Related Questions