What do you think the following code does?
function fn(msg, time) {
setTimeout(function() {
console.log(msg);
}, time);
}
fn('it works', 1000);
What do you think the following code does?
function fn(num) {
return (num > 3) ? 'TOO BIG' : num;
}
console.log([ 1, 2, 3, 4, 5 ].map(fn));
What do you think the following code does?
function fn(num, range) {
for (var i = 1; i <= range; i += 1) {
console.log((num % i) ? 'not divisible by' : 'divisible by', i);
}
}
fn(200, 10);
As much fun as it is to test our ability to parse and compile code, I can't help but feel we ought to focus more on testing that code does what we expect. Out of interest I considered looking at the above from a unit testing perspective and asked myself how I would test each code block. The first thing that becomes clear is that the code is not testable because it uses console.log and should be changed to output it's values. It becomes a more interesting exercise to change the above code blocks to testable units and write the tests that assert our expectations and see where we failed.