Reputation: 6509
I have a function that uses lodash's template
method to dynamically create files and generate code within them.
Anyway, I encountered a bug that has me scratching my head. Googled around, couldn't find an answer.
Suppose I have the following array,
const myMap = [1, 2, 3, 4, 5, 6, 7];
What am I really accessing when I do the following?
console.log(myMap[1|4]); // 6
console.log(myMap[4|1]); // 6
console.log(myMap[4|1|4|1|1|1|1]); // 6
console.log(myMap[4|1|3|1|1|1|1]); // undefined
console.log(myMap[1&4]); // 1
console.log(myMap[1&5]); // 2
console.log(myMap[5&1]); // 2
console.log(myMap[1&6]); // 1
// combining the is also valid javascript, apparently:
console.log(myMap[5&1&5|2]); // 4
I feel like I'm missing something elementary, what's going on here?
Likewise, I can do this with objects:
const obj = { hello:'world' }
console.log(a['hello' & '']); // undefined
console.log(a['hello' | '']); // undefined
console.log(a['hello' || '']); // 'world' (obviously)
Upvotes: 0
Views: 52
Reputation: 3178
JS is evaluating the expression inside the square brackets, so for myMap[1|4]
it evaluates 1|4
where |
is a bitwise OR, and 1|4 == 5
which is why you're getting 6 === myMap[5]
Upvotes: 1