Search code examples
javascriptlodash

Lodash: _.has() returns false for last element in _.range()


Had a bug caused by this and while the fix is easy, (switch to r.includes()) I don't know why this occurred.

import _ from 'lodash';

console.log("TEST");
var r = _.range(1, 10 + 1);
console.log("_.range(1, 11):    " + r);
console.log("Array.isArray(r):  " + Array.isArray(r));
console.log("_.has(r, 2):       " + _.has(r, 2));
console.log("_.has(r, 20):      " + _.has(r, 20));
console.log("_.has(r, 10):      " + _.has(r, 10)); // ???
console.log("x.includes(10):    " + r.includes(10));

Results in

TEST 
_.range(1, 11):    1,2,3,4,5,6,7,8,9,10 
Array.isArray(r):  true 
_.has(r, 2):       true 
_.has(r, 20):      false 
_.has(r, 10):      false 
x.includes(10):    true 

Why does _.has(r, 10) result in false? Is it a bug or am I just not understanding something?


Solution

  • While the values in the array are set by lodash as 1-10 (by your _.range(1, 10 + 1)), the keys of the underlying JS array remain 0 based.

    You are effectively creating: [1,2,3,4,5,6,7,8,9,10]

    _.has checks wether a path exists and in this case is looking for r[10], but in the array above the last valid index is r[9] (since it's 0 based) So it returns false.

    (Similarly, if you do _.has(r, 0) you will see true)