Suggestion: Use semicolons in the material to preempt foreseeable problems in future codebases
jhamberg opened this issue · comments
Problem: Examples in the material rely on automatic semicolon insertion, a convention that can lead to unexpected behavior.
Solution: Use semicolons in the material.
Scenario:
I recently ran into an issue in the wild when using latest Node.js (v21.7.1) and an .mjs file:
const arr = [1, 2, 3]
arr.push(4)
// Swap the first two elements
[arr[0], arr[1]] = [arr[1], arr[0]]
Cannot create property '2' on number '4'
The last line is a valid and commonly recommended way to swap elements in an array without temporary variables or bitwise XOR.
The issue arises from a missing semicolon on line 2, resulting in the code being evaluated as:
arr.push(4)[arr[0], arr[1]] = [arr[1], arr[0]] // ... 4[2] = [2, 1]
There are numerous other problematic scenarios resulting from the omission of semicolon, such as:
const g = 3.14
let everything = 42
/1e-2/g
console.log(everything | 0) // Prints 1337
Prior to running to the array swap issue, I had regarded these errors mostly as theoretical examples, similar to above, with minimal potential to actually manifest in practical production scenarios.
For many people, this course serves as the sole introductory experience to JavaScript. To avoid foreseeable issues in future codebases, I suggest advocating for the less error-prone approach of including semicolons from the get-go. This way, individuals can make their own informed and conscious decision to omit them as they wish, rather than doing so out of habit.
Further motivation: Google Style Guide, Airbnb Style Guide.