Why does indexOf not break?

  • A+

I made a typo in TypeScript which was picked up during code review.

I used someArray.indexOf[someObject] instead of someArray.indexOf(someObject);

I would expect an error from the IDE/Compiler. Instead, no errors were raised and the result was simply undefined.

Can anyone explain this?


Quite easy.

someArray.indexOf you know that this is a function, which is also an object and can have properties.

By doing someArray.indexOf[someObject], you are trying to reach the property with the key valued to the value of someObject.

Of course, it is not defined on the indexOf function, so it returns undefined.

Quick example that illustrates the syntax and the fact that a function can have properties ;) :

const array = []; array.indexOf['anyValue'] = 'test'; console.log(array.indexOf.anyValue);


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: