4

in this code snippet, I could not use obj before declaration

 const obj = {
     value : 10,
     x : obj
}

while here I could

 const obj = {
     func : () => console.log(obj.value),
     value : 10,
}
obj.func();

How could the second compiles but the first fail?

actually, I wonder why any of them compiles since I used obj before it was instantiated, as I understand (I may be wrong) first the right side first evaluated, and then assign the result to the variable(obj)

Ali Faris
  • 17,754
  • 10
  • 45
  • 70
  • 10
    The `obj` reference in the second code block will not be evaluated until that `func()` is actually called. At declaration time, no reference is made. – Pointy Dec 21 '20 at 12:13
  • 1
    Have a look at https://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations and https://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Bergi Dec 21 '20 at 12:54

1 Answers1

0

If I'm not mistaken, this is a JS hoisting and scope issue. I believe the problem lies in the fact that obj inside your first code snippet is being called while also being declared, which causes the error. Conversely, the second code snippet keeps a function inside the scope of obj, so when hoisted, the variable const is given a value of an obj with a function that hasn't been called yet, and a value. So when calling the function with obj.func(), it's doing so AFTER the variable is given a full value.

Better explanation if mine made no sense at all.

Alternatively, you could try setting up the variable in stages, i.e:

const obj = {}
obj.value = 10;
obj.x = obj.value
console.log(obj)

Better Explanation

It really depends on what your intent is, but to my knowledge the concept is the same.

Extended reading on JS engine, the runtime, and the call stack.