DEV Community

Nashe Omirro
Nashe Omirro

Posted on • Updated on

Can you solve this reference problem?

let foo = () => {}
let bar = () => foo
foo = bar
foo === bar() // ???
Enter fullscreen mode Exit fullscreen mode

If you've been using const to declare stuff for too long or have been used to immutability, you might find yourself getting this wrong like I did.

The correct answer is true, bar() does reference the same function, not the previous function that foo was. Now I found that strange and thought it had to do with functions being a little different, since if you turn the above example into objects, the comparison becomes false.

let foo = {}
let bar = { x: foo }
foo = bar
foo === bar.x // false
Enter fullscreen mode Exit fullscreen mode

with objects we can see that bar.x does point to the empty object. This makes sense because instead of storing the reference, we instead use the value that foo points to and assign it to x.

Then that means when using variables inside functions, we use the reference instead of using what the reference points to, now that might be painfully obvious to a lot of you (hopefully not all of you) but if your used to never redeclaring variables, you might have never encountered this interaction, or have forgotten.

With other blocks

But it's not just functions, any re-executable block does this, this loop for example:

let b = 0;
while (b < 10) {
  console.log(b)
  b += 1
}
Enter fullscreen mode Exit fullscreen mode

for the above loop to work properly, b inside console.log() has to be the pointer and not whatever the pointer points to.

Delayed Execution

This also happens with Promises and delayed execution with setTimeout:

let a = 0;
new Promise((res, rej) => {
    let b = 10
    setTimeout(() => {
        b = a;
        res(b)
    }, 300)
}).then(val => console.log(val)) // this will be 40
a = 40
Enter fullscreen mode Exit fullscreen mode

Conclusion

The more I look into it the more I realize that it makes a lot of sense. I don't know why this confused me, maybe because when I first saw this interaction it was with a lot of higher-order tomfoolery, heck I'm not even sure if I'm using terms correctly, but I hope I'm not the only one confused by this interaction.

Top comments (0)