On this page are examples of real or potential gotchas. You’ll find the answers in Gotcha answers, but you’ll learn better if you try to answer the questions yourself first.
A gotcha is a trap for the unwary. Here there should be fairly obvious, but in the wild they’ll be disguised and will sneak up on you. You’re focussing on the main thing and then you write a gotcha.
Equality
if (a == b) { ... }
Addition
x = (a + b) + c y = a + (b + c) x == y // True or False? When?
Trailing comma
x = [ 'first value', 'second value', 'third value', ]
Missing comma
x = [ [1, 2, 3], [4, 5, 6] [7, 8, 9] ]
Missing new
var Point = function(x, y){ this.x = x; this.y = y; } pt = Point(2, 4)
Bind is transient
fn = obj.method; // General form of the gotcha. x = [0, 1, 2, 3, 4, 5]; // Example of gotcha. a = x.slice(1, 3); // What happens behind the scenes? tmp = x.slice; // What happens here? b = tmp(1, 3); // What happens here?
Missing var
var average = function(a, b){ total = a + b; return total / 2; }
Missing closure
// Add handlers: click on item to show item number. var make_and_add_handlers(items){ for(var i=0; i < items.length; i++){ items[i].onclick = function(){ alert("This is item " + i); }; } }
Missing that
// Return fn that does something (and logs the instance). proto.fn_factory = function(...){ var fn = function(...){ ... log("Name = " + this.name); ... } return fn; } // Example of desired output. js> instance.name Charles js> fn = instance.fn_factory(...) js> fn(...) // Logging to go to console. Name = Charles