March 16, 2021 • 3 min read
Take a moment to look at this snippet and try to figure out what it does.
Don’t scroll to the solution yet!
Really try to figure out the result, It’s not as easy as it seems…
const myArr = [1, 2];
console.log(`Original: ${myArr}`)
[(myArr[0], myArr[1])] = [myArr[1], myArr[0]];
console.log(`Swapped: ${myArr}`);
What will be logged in line 4?
.
.
.
.
Don’t scroll anymore until you know the solution!
.
.
.
.
.
.
OK, ready?
.
.
.
.
Now, I bet you thought the result was:
'Swapped: 2,1'
WRONG.
This code throws an error. You can try it yourself on your browser’s console:
Uncaught TypeError: Cannot set property '2' of undefined
But, why?
This error happened to one of my students and I was puzzled for a while until I discovered the culprit. The code is missing semicolons. Usually, this is not a problem, since JavaScript’s Automatic Semicolon Insertion takes good care of it.
However, in this case, the code is run as:
const myArr = [1, 2];
console.log(`Original: ${myArr}`)[(myArr[0], myArr[1])] = [myArr[1], myArr[0]];
console.log(`Swapped: ${myArr}`);
How can we avoid this kind of headache?
Use static code analysis tools.
Even if it’s a small script that I’m working on, I always install, at least, eslint. Because:
So even if it takes a couple of minutes to set up static code analysis tools, it is always a big win. Moreover, the more times you set them up, the faster you can get it done the next time.