Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit array property versus a variable in JavaScript

Trying to refactor a simple function:

// arr - array of objects with functions
function eventNotify(arr, event) {
    for (var i = 0; i < arr.length; i++) {
        var a = arr[i];
        if (typeof a[event] === 'function') {
            a[event]();
        }
    }
}

into this one:

function eventNotify(arr, event) {
    for (var i = 0; i < arr.length; i++) {
        var a = arr[i][event];
        if (typeof a === 'function') {
            a();
        }
    }
}

I'm stuck trying to comprehend how such change manages to break all my tests.

How is it possible that the second implementation is functionally different from the first one?

I even tried to split the use of indexes, thinking that maybe it is treated as a 3D array:

var a = arr[i];
a = a[event];

But no, this makes no difference.

Please somebody point out what on earth am I changing in the logic of the algorithm there! I'm wracking my brain over this one now.


I'm testing it under Node.js 10.9

like image 447
vitaly-t Avatar asked Aug 26 '18 12:08

vitaly-t


1 Answers

Thanks @Pointy

My mistake was in not being able to see that syntax a[event]() obscures the fact that it passes in this context set to object a, while simple a() does not, hence the result discrepancy.

like image 165
vitaly-t Avatar answered Oct 06 '22 20:10

vitaly-t