I’m starting this category on my blog to detail some of the many fun things that I learn at work. I was inspired to share these things by the WAT Lightening Talk I saw awhile back.
Today’s lesson: Javascript doesn’t do well when you combine array with the plus operator. Awhile back I was working on a bug that required me to iterate over an array of users on a particular question. Well, we have two arrays – one for people who are replying and one for people who aren’t. So, I did something like this.
var allUsers = usersViewing + usersReplying $.each(allUsers, function(i, user) { user.resetStatus(); })
I was kindly provided with the following error message in the Javascript console. This isn’t the exact error, but the gist of it was:
Object [ has no method ‘resetStatus’
After some digging I found a fun law of Javascript and the + operator with arrays.
[“this is a string”] + [] = “this is a string”
WAT.
Sure enough, Array.concat() saved the day, but still – who thought that behavior would be an excellent idea?