Programming Puzzle 3: Closures Quiz

by Mike Gleicher on October 22, 2015

in Assignments,News

Due: October 27th

This is a very short puzzle. Think of it as a Quiz. Since we don’t have class on Tuesday, October 27th, do the puzzle in that time slot. It shouldn’t take 45 minutes – but if you don’t get it in 30 minutes, post the first part and see what other people come up with.

Note: the puzzle isn’t just to solve the problem – it’s to understand why the example solution works the way that it does.

The problem:

Write a program that takes all of the buttons on a web page, and changes them so that when they are clicked, an alert pops up that says the number of the button. (so the first button says “1”, the second says “2”, etc.)

The example solution:

Here is a solution that doesn’t solve the problem. Before clicking on the buttons and seeing what it does do, figure it out by reading the code (all 8 lines of it!): http://jsbin.com/pewatov/edit?html,js,output

Part 1: Why does it do what it does?

Part 2: Create a solution that does the right thing. (note: do it with a loop over the list of buttons, don’t hard code it).

Post your answers to the discussion on Canvas. Even if you don’t get part 2, post  solution to part 1.

I am really curious what people come up with. My first solution isn’t as nice as I would have hoped.

By the way, the title of the assignment is a big hint.

Disclaimer: this quiz is inspired by the example on “interviewcake”. Thank you to Michael who pointed me at that.

Print Friendly, PDF & Email

Previous post:

Next post: