
Not pictured: A oil drum-sized barrel of balsamic vinegar labeled “React”, “Vue”, or “Angular”, and a forgotten can of anchovies labeled “jQuery”.
Thanks to Cameron Barrett for the find!
If…
…you’re in luck! There are a couple of good books on JavaScript whose contents are available to read online, free of charge!
The first of these books is Eloquent JavaScript, Third Edition, written by Marijn Haverbeke and published by No Starch Press. It’s not just an introduction to JavaScript, but an introduction to programming in general. It’s beginner-friendly, which is one of the reasons why it’s the main book for the first part of the JavaScript/React course that I’m teaching.
You can Eloquent JavaScript, Third Edition online here.
The second book is JavaScript for Impatient Programmers, ECMAScript 2020 edition, written by Dr. Alex Rauschmeyer. Its coverage of JavaScript is more complete, but it’s a little less beginner-friendly, which is why it’s the backup book for my course. I’m going to incorporate some of its content into the course, and point students to the online edition if they’d like some additional reading material.
You can read JavaScript for Impatient Programmers, ECMAScript 2020 edition online here.
In the previous article in this series, I put out a call for alternate implementations of the “watcher”-based FizzBuzz solution. Frank Quednau answered the call with this elegant bit of JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
const wordWatcher = (interval, word) => { let count = 0; return () => { count++; if (count === interval) { count = 0; return word; } return ""; } } const fizzWatcher = wordWatcher(3, "Fizz"); const buzzWatcher = wordWatcher(5, "Buzz"); for (number of Array(100).keys()) { const potentialFizzBuzz = `${fizzWatcher()}${buzzWatcher()}`; console.log(potentialFizzBuzz ? potentialFizzBuzz : number + 1); }; |
Let’s take a closer look at the code for the watcher, which is assigned a word and keeps track of when to say it:
1 2 3 4 5 6 7 8 9 10 11 |
const wordWatcher = (interval, word) => { let count = 0; return () => { count++; if (count === interval) { count = 0; return word; } return ""; } } |
wordWatcher
has two parameters:
interval
: The x in “Every xth number”word
: The word to be outputcount
, andword
(if it’s time to say the word) or an empty string.If you find yourself writing a lot of similar code with only minor differences — or worse, cutting and pasting code, followed by typing in those minor differences — you may be looking at an opportunity to use a function like this.
If you prefer to have your functions marked with the keyword function
, you can change out the arrow notation and the code will still work:
1 2 3 4 5 6 7 8 9 10 11 |
function wordWatcher(interval, word) { let count = 0; return function() { count++; if (count === interval) { count = 0; return word; } return ""; } } |
With wordWatcher
defined, creating watchers for Fizz and Buzz is easy:
1 2 |
const fizzWatcher = wordWatcher(3, "Fizz"); const buzzWatcher = wordWatcher(5, "Buzz"); |
And here’s the loop that provides the output:
1 2 3 4 |
for (number of Array(100).keys()) { const potentialFizzBuzz = `${fizzWatcher()}${buzzWatcher()}`; console.log(potentialFizzBuzz ? potentialFizzBuzz : number + 1); }; |
potentialFizzBuzz
will contain that string. The calls to fizzWatcher()
and buzzWatcher()
will also increment their internal counters.potentialFizzBuzz
contains anything, its contents will be printed to the console; otherwise, the current number — which has 1 added to it because array indexes start at 0 and the FizzBuzz game starts at 1 — is printed instead.You should check out the rest of Frank’s Gist, Fizzbuzzes in many colours, which looks at FizzBuzz solutions written in several languages.
In ordinary everyday use, elegant means “pleasingly graceful and stylish in appearance or manner.” The term has been adapted by people in problem-solving fields — science, mathematics, and yes, programming — to mean “pleasingly ingenious and simple”.
And that’s what elegant code is: pleasingly ingenious and simple. This FizzBuzz implementation is elegant because it solves the problem in just over a dozen lines, is simple and concise, and even provides some new insight into programming (the use of custom-generated functions to avoid repetition).
Here’s a good list of qualities of elegant code, courtesy of Christopher Diggins article, What is the Definition of Elegant Code?:
Check out the following articles — sooner or later, you’ll be interviewed by a programmer who’ll want to know if you’ve given some thought to some of programming’s more philosophical questions, and “What does it mean for code to be elegant?” is one of them:
FizzBuzzBazz! (or: Making FizzBuzz harder).
In the previous article, I wrote about a challenge that’s often given to programmers at a tech interview: Write a program that determines if two words are anagrams. I posted a solution in Python; check it out here. In this article, we’ll refactor the Python code and write a JavaScript implementation.
Looking at the code for anagram()
, it’s quite clear that it isn’t DRY (Don’t Repeat Yourself), but manifestly the opposite: WET (Write Everything Twice)!
Under the time constraints of a technical interview, you might not always have the time or cognitive bandwidth to keep your code DRY, but if you should try to do so if possible. You may find that it helps convey your algorithmic thinking more effectively to the interviewer, and that’s what you want. After all, your goal throughout the process is to prove that you can actually program.
The repeated code is the part that takes a string, sorts its characters into alphabetical order, and removes the leading space if it exists. Let’s turn that code into its own method:
1 2 3 4 5 6 |
def sortLetters(word): # Returns the given word with its letters sorted # into alphabetical order and with any # leading space removed. word_lowercase = word.lower() return ''.join(sorted(word_lowercase)).lstrip() |
With this method defined, we can use it in anagram()
. In fact, we can nest it within anagram()
. Here’s the revision:
1 2 3 4 5 6 7 8 9 10 11 12 |
def anagram(first_word, second_word): # Returns True if the given words are made of the exact same characters, # ignoring capitalization and spaces. def sortLetters(word): # Returns the given word with its letters sorted # into alphabetical order and with any # leading space removed. word_lowercase = word.lower() return ''.join(sorted(word_lowercase)).lstrip() return sortLetters(first_word) == sortLetters(second_word) |
Creating the sortLetters()
method doesn’t just DRY up the code, but helps the method better convey what it does. Now, what anagram()
does is very clearly conveyed by its return statement: it tells you if the first word with its letters sorted is the same as the second word with its letters sorted.
I confirmed that this refactored code works by running the tests, which show just how useful having tests is.
anagram()
in JavaScriptHere’s anagram()
in JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function anagram(firstWord, secondWord) { function sortLetters(word) { return word .toLowerCase() .split('') .sort() .join('') .trim() } return sortLetters(firstWord) === sortLetters(secondWord) } |
Note that the JavaScript version of sortLetters()
is structured slightly differently from the Python version. That’s because JavaScript’s sort()
is an array method rather than a general function like Python’s sorted()
.
In the JavaScript version of sortLetters(), I use method chaining to spell out what happens to the given word step by step:
I could’ve written sortLetters()
this way…
1 2 3 |
function sortLetters(word) { return word.toLowerCase().split('').sort().join('').trim() } |
…but I find that “put each method in the chain on its own line” approach more clearly conveys what I’m trying to do:
1 2 3 4 5 6 7 8 |
function sortLetters(word) { return word .toLowerCase() .split('') .sort() .join('') .trim() } |
Next: The Swift version!
The Urban Dictionary definition of "wat" is "the only proper response to something that makes absolutely no sense". The concept of wat is covered a little more completely on its page in Know Your Meme.
"Wat" is also the title of a funny demo of Ruby and JavaScript oddities presented by Gary Bernhardt at CodeMash 2012, a rather unlikely tech conference — it takes place in Sandusky, Ohio, in Ohio’s largest indoor waterpark. (If you just said "wat" right now, you’ve used the word correctly.)
In the video, you see this classic wat bit about undefined variables and assignment in Ruby:
You’ll also marvel at the way JavaScript treats (array + array) vs. (array + object) vs. (object + array) vs. (object + object):
Watch the video, and wait for that final slide, which is pure, hilarious wat!
Are you a web developer and want to sharpen your jQuery skills? Would you like to attend a conference featuring some of the brightest lights in jQuery programming? Are you too short on time and travel expenses to hit such a conference?
For a mere US$150 and no travel at all, you can attend the jQuery Online Conference. It’s a live, over-the-‘net conference taking place on Monday, July 12th starting at 12:00 noon EDT / 9:00 a.m. Pacific and featuring these four sessions:
Your conference attendance fee not only lets you watch the live event and ask questions of the presenters, it also lets you watch the recordings of the events any time afterwards. So if you can’t catch the live event (perhaps you’re busy at work, or it’s 3:00 a.m. in your time zone), you can still watch the presentations. This also lets you watch the live event to get the general idea, and then watch it again for note-taking or hands-on workshopping.
By now, you’ve probably seen my article covering the new, faster, even more standards-compliant Platform Preview 3 of Internet Explorer 9. From hardware acceleration to a speed-boosted JavaScript engine with support for new ECMAScript 5 language features to support for SVG,
<audio>
, <video>
and <canvas>
tags, IE9 is shaping up to be a great browser for an open web.
Before there were Microsoft blogs (such as Canadian Developer Connection), there was Channel 9, Microsoft’s community site run by Microsoft employees. Like Microsoft blogs, Channel 9 gives you unfiltered access to the people building stuff at The Empire, all outside the control of the marketing and PR departments. Channel 9 features a lot of videos – there are times when they post several videos in a day – featuring developer news and training, training kits and courses, discussion forums and wikis for various Microsoft tools and technologies. If you’re a .NET developer or just curious about what’s going on the in the .NET world, you should check out Channel 9 and see what’s happening.
Channel 9 posted a number of videos covering the new features in the third Platform Preview of Internet Explorer 9. I’ve gathered them all into this blog article – enjoy!
Can’t see the video? You can download and install Silverlight or download the video in MP4, MP3, WMA, WMV, WMV (High) or Zune formats.
This video shows some of the sample apps living on the IE Test Drive site in action. It covers the following demos:
Can’t see the video? You can download and install Silverlight or download the video in MP4, MP3, WMA, WMV, WMV (High) or Zune formats.
Here’s a closer look at the FishIE Tank demo and how it makes use of <canvas>
to draw up to thousands of animated, moving, scaling fish sprites.
Can’t see the video? You can download and install Silverlight or download the video in MP4, MP3, WMA, WMV, WMV (High) or Zune formats.
Another <canvas>
demo: Amazon Shelf. This one ties into Amazon’s data to create a virtual bookshelf that lets you browse Amazon’s catalogue of books.
Can’t see the video? You can download and install Silverlight or download the video in MP4, MP3, WMA, WMV, WMV (High) or Zune formats.
The IE9 team showed a preview of support for the <video>
tag, and with Platform Preview 3, you can try it out for yourself. In this video, you see how it’s used to build the IMDb Video Panorama demo.
Can’t see the video? You can download and install Silverlight or download the video in MP4, MP3, WMA, WMV, WMV (High) or Zune formats.
There are lots of boring ways to show of ECMAScript 5’s new array methods in action, but why not show them off with a fun game? In addition to the new JavaScript goodies, the ECMAScript 5 Game demo also shows off:
<video>
and <audio>
<window.getComputedStyle()>