Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript 'in' function showing weird behavior [closed]

Tags:

javascript

I was just testing the in operator in Javascript. When I run something like console.log("cookie" in document), it logs true, but when I do console.log("cookie" in "cookiejar") or assign cookiejar to a variable a and then do console.log("cookie" in a), I get an error statement TypeError: invalid 'in' operand a. Can anyone tell me why is it behaving like this?

like image 840
SexyBeast Avatar asked Apr 25 '26 12:04

SexyBeast


1 Answers

The in operator doesn't do what you think it does. a in b tells you if a given object b has the property named a.

You cannot use in to search for characters in a string. Use indexOf for that.

'cookiejar'.indexOf('cookie')

Note that the in operator is entirely separate from and completely unrelated to the for-in statement.

like image 90
josh3736 Avatar answered Apr 28 '26 02:04

josh3736