Search code examples
javascriptecmascript-6scopehoisting

Circular const, let declaration for graph ... how to fix?


OK, brain freeze ... I need help making this work:

const a = {
  val: 'a',
  neighbor: d
}

const b = {
  val: 'b',
  neighbor: a
}

const c = {
  val: 'c',
  neighbor: b
}

const d = {
  val: 'd',
  neighbor: c
}

console.log('d: neighbor - > ', d.neighbor)
console.log('a: neighbor - > ', a.neighbor)

const a has to point to const d but unfortunately const d is defined after const a. In most cases, I can move const a to be defined after const d but in this case const d needs to be defined after const c. What am I missing....? Thank you


Solution

  • You can define neighbor properties as getters. A getter is actually a function which is executed when you're retrieving the value of an object, i.e. at that point all the referred objects are already defined. This way you can also protect the neighbor property against accidental changes.

    const a = {
        val: 'a',
        get neighbor () {return d;}
    };
    const b = {
        val: 'b',
        get neighbor () {return a;}
    };
    const c = {
        val: 'c',
        get neighbor () {return b;}
    };
    const d = {
        val: 'd',
        get neighbor () {return c;}
    };
    
    console.log('d: neighbor - > ' , d.neighbor);
    console.log('a: neighbor - > ' , a.neighbor);