The project I’m working on with Jim and Michael has definitely hit its stride and the past week I’ve been working with a fair amount of JavaScript. It had been a couple months since I’d spent more than a few minutes tweaking this or that UX element so it’s been great to really dive in.

Today I had a big gotcha that cost me a few more minutes than I care to admit, but fortunately Michael helped me troubleshoot for a few minutes and caught the gotcha staring us in the face.

I was spiking through these two almost identical functions to see how they worked on the page…. and the first worked just fine:

$(‘#title-suggestions’).on('click', ‘li’, function(event) {
  title = $(this).val();
  updateSearchTerms(title, ‘#title-search’);
});

It grabbed the text of an ‘li’ element in the ‘title-suggestions’ and added it to the already selected search terms.

Then I wanted to do the same thing in the cities suggestion so I wrote this:

$(‘#city-suggestion’).on(‘click’, ‘li’, function(event) {
  location = $(this).val();
  updateSearchTerms(location, ‘#city-search’);
});

However, when I jumped into the browser to make sure it worked I was getting a weird redirect. Then I tried to just add in a simple console.log(location) debug statement and I was still getting the error.

Experienced JS gurus probably already see both of my mistakes. The first and biggest gotcha is that I wasn’t using ‘var’ to declare my variables for either title in the first function or location in the second. The second line of both functions should be:

var term = $(this).val();

This declaration scopes the variable to the function I’m in and is good practice because it keeps the variable from “bubbling up”.

The second gotcha and the actual cause of my error is that the name location is a host variable in JavaScript that contains information about the page that is loaded. You can open up the JavaScript console in your browser of choice and just by typing location you’ll get a whole bunch of information about the page you’re on.

My double whammy was that because I wasn’t declaring ‘location’ as a variable inside the scope of my function it was bubbling up and causing problems. The first function worked just fine, even without a scoped variable, because the title variable didn’t conflict with anything else.

Here’s an older article with a short list of other variable names you probably want to avoid when writing JavaScript.