JavaScript semantics that catch people out
Equality, array methods that copy or mutate, and closure capture.
10 min read
Three areas account for most of the JavaScript defects that survive review, because the code reads correctly in each case.
Equality. == converts types before comparing. 0 == "0" is true, 0 == [] is true, "0" == [] is false. Use ===, which compares without conversion. The one idiom in which == is preferable is x == null, which matches both null and undefined.
Copying and mutating. map, filter and slice return a new array. sort, reverse and splice modify the array given to them, and sort also returns it, so it resembles the first group while behaving like the second. sort converts to strings by default, which is why [10, 9, 1].sort() returns [1, 10, 9]. Supply a comparator for numeric values.
Closures capture variables, not values. A callback created inside a loop observes the variable as it stands when the callback runs. With let each iteration receives its own binding; with var it does not. The same applies to anything deferred: setTimeout, a promise, an event handler.
Go deeper
Lessons are not assessed. Progress towards the certificate is recorded from the work you submit. See all requirements