by dotancohen · 4y ago · 0 comments
function foo() {
let a = b = 0
a++
return a
}
console.log(typeof a)
console.log(typeof b)
As expected, `a` is defined with `let`, so it is a local variable. But `b` is defined without let, so it is actually globally. I personally do not like declaring multiple variables in a single statement like this, so I've probably not coded any bugs with this behaviour, but I have most certainly worked on code which I now understand to have latent bugs due to this behaviour.Actually, at this point, with the prolifiration of strict mode and linters, I'd say that these old gotchas mostly belong to quizzes and spec discussions, since personally I have not seen new code written this way even in vanilla JS for years by now.
[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Maybe it wasn't 'new' code but it was new enough to use let.
on edit: actually considering the project I would think it was written somewhere within the last 2 years.
let a = 0, b = 0You need to call `foo()` before the first `console.log` to get that behavior.
function foo() {
let a = b = 0
a++
return a
}
foo() // <------ INSERT THIS
console.log(typeof a)
console.log(typeof b)