0

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?

Edit

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)
1

1 Answer 1

1

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]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.