JavaScript Annoyances: for (i in array)

I got bitten by a JavaScript annoyance today that I figured I’d describe here in case other people have the same problem. I’m not going to call it a bug, because technically it isn’t.

I was looping through an array, using the syntax for (i in a) where i is the array index and a is the array. Inside this loop I needed to do some simple arithmetic, just a basic i + 1. What can go wrong? As it turns out, everything.

Since JavaScript is loosely-typed it just happily converts your variables from one datatype to another whenever it needs to. This is handy when you want to concatonate an integer on the end of a string, or do arithmetic on a number stored as a string. Unfortunately the combination of this loose typing and the overloading of the + operator can lead to problems.

The for (x in y) construct is used to iterate over all of the keys in an object, but the keys it returns are all converted to strings. When you try to add 1 and 1 (to get 2), you actually end up concatonating "1" and "1" (getting "11").

The solution is to use the slightly more verbose for (var i = 0; i < a.length; i++) construct, which leaves i an integer throughout. Alternatively you can use the parseInt() function to turn a string into an integer, or do one of the ugly tricks like subtracting zero or multiplying or dividing by one (we’ve seen that adding zero won’t work because of the overloaded +).

Hopefully in taking the time to write this up I won’t fall for this again.

Masters Update

I said on Friday that I’d keep you updated on the possibility of me doing a masters. Well, the descision-making process was a little faster than I had expected. I’m typing this in my new (shared) office, where I’ll be working for the next 18 months or more.

I’ll be working on the same project that I’ve been doing for the summer, only now I’ll be essentially taking over the whole thing instead of just doing the front-end. We haven’t sorted out every detail yet of course, but I have enough to be working on anyway. I’m at an advantage over other new postgrads since I’ve already got a comprehensive todo list and a very good knowledge of the system I’m working with (I should have, I wrote it).

My system in here isn’t set up yet. I was given a computer that was used by a German PhD student who’s just left. It’s set up with FreeBSD in German, and he’s the only person who knows the root password. I figured it would be a good idea to make sure he had everything he needed before I install my own OS on it. He got back to me earlier today, so I’ll do my installing mojo tomorrow. For now I’m working on my laptop (which still works well after all these weeks, despite what the naysayers would have you believe).

There are some new postgrad requirements being introduced this year in the department, one of which is that I have to take at least two taught modules as well as just doing my thesis. There’s a heck of a list to choose from, including all of the fourth-year courses, most (or many) of the taught masters courses, a few computational courses from the mathematical physics department, and some others.

On top of all of this registration, system set-up, choosing courses stuff, I’m hoping to have a working prototype ready to demo to some interested parties in about four weeks. I might need to start coming in before one o’clock.

Roses are Well-Read

An academic career involving theoretical physics and computer science is not very high up the "How to Meet Women" list. In fact, if it’s on that list at all it’s only because of an irresponsible sub-editor having a laugh. In short, there is something terribly wrong when switching to computer science brings you into contact with more members of the fairer sex.

But now I find out, from former classmate and über-physicist Joe, that this year’s Rose of Tralee just graduated from UCD with a first in theoretical physics. She was in the year behind me. Why is finding women so hard? I mean, it’s not rocket science.

Masters

I haven’t had a huge amount to report these last few days. It turns out that last week was the last week of my internship, though I spent the first half of this week waiting to find out if I was needed for another week. No worries though; they took several weeks to start paying me so it’ll be another few until they stop. The project actually progressed a bit farther than I had expected, though we didn’t get it to release standard. I don’t think anyone had any real idea of how big a project it was. I’d like to see it get finished.

I’ve got a meeting today to talk about starting a masters next year. I’m quite keen on it, not least because it comes with quite a substantial tax-free scholarship. I don’t know how much benefit ist is to have a masters in this field when looking for a job, but my reasoning is that I’m far more likely to regret not doing it than I am to regret doing it. I was also offered a job, but I’m much more interested in the masters so I’m going to turn the job down. I’ll let you know how things go.

Logos

I have a hard time taking them seriously, I’m afraid. It’s ugly, it’s got a drop shadow, for crying out loud, and it’s multicolored like a circus tent. The first G looks weird, like someone was trying to draw a G but was using someone else’s memory of what a G looks like, the letters are oddly kerned, and the whole thing looks like it should be painted on the side of an ice cream truck.

So there seem to be some people who aren’t overly-keen on the Google logo. They’re saying this now that Google has several billion dollars tied up in brand recognition, rather than five years ago when no-one would have noticed a change. Oh well. I guess we’re stuck with it.

Anyway, the talk of logos got me thinking about the best simple logos, and you know what I realised? I love the Sony logo. Just look at it. Isn’t that a triumph of simplicity? If I knew anything about the theory of design I’d tell you why that logo is so great. But I don’t. Still, I hope someone got a promotion for designing that thing.

Top 5: Steve Martin Movies

I wanted to ease myself into the Top 5 swing with this list, which itself was actually the inspiration for the series. The Steve Martin Quintillogy is a group that I’ve always considered to be the Steve Martin movies. All of the rest are just movies that he was in. So there wasn’t an awful lot of deliberation in compiling this list, beyond a brief scan of IMDb to make sure I didn’t accidentally leave anything out.

5. "Hi. My name is Bob. I’ll be your robber."

I know I’ll probably get hate mail for putting L.A. Story at the lowly position of number five, but the truth is simply that I haven’t seen this movie in so long it’s a struggle to remember specifically why it’s so good. All I have is a vague feeling of having been entertained by the sometimes-surreal commentary on the shallowness of life in L.A. If I was going to do a proper review and, you know, actually research my choices this would have been the first of the five that I watched.

4. "Wherever liberty is threatened, you will find…"

I watched ¡Three Amigos! for the first time as quite a young child, and I remember specifically learning off the speech and the odd shoulder-slapping, hands-on-hips gyrating routine so that I could imitate the ‘heroes’ of this movie. This one was definitely aimed at kids, and it doesn’t quite make the grade anymore, if only by Martin’s standards. It’s still a quality movie, and worth anyone’s time to watch.

3. "You could de-emphasize your nose if you wore something larger, like… Wyoming."

The most straightforward of the five, in terms of its story, Roxanne still shines with some memorable moments. It starts brilliantly with the "I really admire your shoes" dialogue, but the comedy takes a back seat to the love story as the movie goes on. I’ve heard it said that if the shot is too close for you to be able to see all of Martin then you’re missing something; he does comedy with his entire body. Roxanne contains my favourite example of this style: CD buys a newspaper and starts to read it as he walks away. Then he lets out a yell and runs back to cram the newspaper back into the box he got it from.

2. "Man your drunk tests are hard!"

Absolutely the most surreal of the quintet, The Man with Two Brains was a very strong contender for the top spot. A love story between neurosurgeon Dr Hfuhruhurr and brain-in-a-jar Anne Uumellmahaye, this movie is hilarious as soon as you’ve heard the synopsis. The magnificent poem Oh Pointy Bird made its first appearance in this movie, and was later repeated (in part) in L.A. Story:

Oh pointy bird,
  Pointy pointy,
Anoint my head,
  Anointy-nointy

1. "Ruprecht, do you want the genital cuff?"

Barely better than the runner up, Dirty Rotten Scoundrels scrapes into the number-one position. It has style, it has wit, it has charm, but most importantly it has Ruprecht. It also has some classic scenes of physical comedy, in particular Michael Caine making it difficult for Steve Martin to fake paralysis by repeatedly hitting his legs with a cane. While not as saturated with comedy as The Man with Two Brains, Scoundrels has a more coherent story. Plus it was directed by Yoda.

And now to you: what are your favourites, what did i get wrong, what did I get right?

Top 5: A Rambling Introduction

I’m a very list-y person. Some people have called me listless, and they may also be right; such are the paradoxes of the universe. I’ve inherited this inclination—to sort all of life’s ups, downs and sidewayses into short bulletted columns—from my father, who enumerates his days’ activities in a notepad, with gleeful anticipation. I’ve tried to help him add more value to his lists: by prepending each ‘to do’ with the item "Make List" you give yourself one thing to strike off straight away, giving you a good run up to the rest.

The reason I bring this up is that I want to introduce what I think may become a new… thing here on Soylent Red: my top fives. I’ve taken the rebelious step of naming them ‘Top 5’s in order to save myself three keystrokes. These are the fast paced times we live in. We do things like replace numbers with digits, and end sentences with prepositions. And start sentences with conjunctions.

Sorry, what I meant to say, before I started channelling Lynn Truss, was that I hope to start posting my Top 5 lists of such things as songs, movie directors, blogs and such like. I figured five items is a reasonable length for these lists, given that I want to be able to go into at least a little detail about why I chose these five foos to be my top five foos.

There are two founding principles in this series. The first is that these lists are based solely on my opinions, and opinions I’ve appropriated from people that sound like they know what they’re talking about. I make no claim that I’m going to evaluate every movie before I name my Top 5. If Taxi Driver doesn’t make the list that’s because I haven’t seen it yet. The upshot of this is that if you don’t agree with my choices, don’t come whining to me about it. The second founding principle is that the lists are not final. Okay, I’m not about to go editing the posts to change the lists, but I’m willing to have people make suggestions, point out omissions, etc. The upshot of this is that if you don’t agree with my choices, do come whining to me about it. I realise that these two principles are not entirely consistent, so I leave the descision about whether or not to argue with me to you. Just bear these two principles in mind when you do.

I have a sufficiently long, er, list of topics that I hope to cover, beginning with the list that inspired this whole venture, my Top 5 Steve Martin Movies. Expect to see that post soon.

Michael Bay is the Devil

From this month’s Empire, an anecdote by Michael Bay (aka the Devil) concerning one Scarlett Johansson:

Bay gets a call from his AD, "She needs you."

"I’m like, ‘here we go,’" he continues. "I’m ready to do Ewan and her love scene. I’m like, ‘Oh my God, she’s not gonna come out.’" So, he ventures over to her trailer, and knocks tentatively on the door: "Scarlett?"

"Yes?"

"Can I come in?"

Hearing no reply, Bay opens the door and slips inside to be confronted with what appears to be his worst fears. To put it mildly, she’s in a right tizzy, her name has become more of a description than a monicker — all that is missing is a pair of comedy Chuck Jones spurts of steam blasting out of her ears like a pressure cooker going off and the picture is complete.

"I’m not fuckin’ wearing this bra," she yells at him, "this cheap-ass black bra, okay? I’m going naked."

"I’m like, ‘Scarlett you can’t go naked. It’s a PG-13.’"

The Devil, I tell you.

Non-Polluting JavaScript

All scripts on a web-page excecute in a single context, one after another in the order in which they appear in the page’s HTML (or in which thy are included from external files). This means that the variables and functions defined in a script are accessible by the scripts that run after it. If you’re writing scripts that are intended to be self contained, so that they can be dropped into any page without interfering with the other scripts on that page, you may want to consider making your script what I call a ‘non-polluting’ script. That is, a script that doesn’t alter or define any global variables or define any functions. A script that leaves no traces behind it, beyond its intended effect.

Such a script is made possible by the concept of anonymous functions. When you call a function in JavaScript you generally do it by typing its name followed by the list of parameters enclosed in parentheses, eg.:

myFunc(arg1, arg2);

In fact, you can call an anonymous function by replacing that function name in the code with the function definition, eg.:

(function()
{
    // function code goes here
})();

This has the effect of defining an anonymous function (notice that it’s never given a name) and then excecuting it. If you enclose your entire script withing such an anonymous function it will excecute as normal but none of the variables you define will be defined outside of the anonymous function.

There is one important change you may have to make to your script to be able to put it inside an anonymous function like this. That is that you must ensure that all of your variables are defined explicitly using the var keyword. Otherwise they will be created in the global scope instead of the function scope.

And that’s it. That’s all you have to do to make sure that your script is entirely self-contained and non-polluting.

Invitation to Anthony Gatto

I am officially inviting Anthony Gatto to fly to Ireland to hang out with me for a day or two. You can teach my friends some cool tricks, and show off a bit. I’ll buy lunch, but you’ll have to pay for your own flights. You can stay in the spare room.

(For the confused: [1], [2], [3])