Search code examples
javascriptarraysnode.jsv8

Node.js v8 HOLEY arrays unexpected behavior


After watching Mathias Bynens report about HOLEY and PACKED arrays, I did some experiments and got unexpected behavior. See two cases:

// CASE #1
const array = [0,1,2,3,4,5,undefined]
array.__proto__[6] = 'some value'

console.log(array[6]) // "some value" expected but got undefined

// CASE #2
const array = [0,1,2,3,4,5]
array[10] = 'faraway value'
array.__proto__[6] = 'some value'

console.log(array[6]) // "some value" expected and received

So, what the difference between these cases ? Why does in the first case it return undefined without looking in the prototype chain ?


Solution

  • In case #1, you're explicitly putting undefined into the array. There is no need to go up the prototype chain because the element is present. Compare:

    var case1 = [0, 1, 2, 3, 4, 5, undefined, 7];
    var case2 = [0, 1, 2, 3, 4, 5, , 7];
    case1.hasOwnProperty(6);  // true
    case2.hasOwnProperty(6);  // false
    console.log(case1[6]);  // "undefined", loaded from object
    console.log(case2[6]);  // "undefined", because no element was found (not on the object, and not on the prototype chain)
    case2.__proto__[6] = "proto value";
    console.log(case2[6]);  // "proto_value", loaded from prototype chain