Re:JavaScript quiz that may confuse you
by dotancohen on Tuesday May 03, 2022 @01:51AM
(#31245095)
This one was a real surprise, the rest were "sharp eyes" or "understand how to use your tools".
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.
[ Parent
| on HN ]
That's why we introduced the strict mode ("use strict" pragma)[1]. Among other things, it prevents from accidentally declaring a global variable this way, throwing a ReferenceError.
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...
Re:JavaScript quiz that may confuse you
by bryanrasmussen on Tuesday May 03, 2022 @06:17AM
(#31246593)
I'm pretty sure I've seen something similar to let a = b = 0 in the last couple months, without strict mode and it evidently hadn't been linted away.
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.
You might be thinking of:
let a = 0, b = 0
Re:JavaScript quiz that may confuse you
by bryanrasmussen on Wednesday May 04, 2022 @02:11AM
(#31257251)
I should apologize, my normal way of writing made it seem like I wasn't sure about having seen it but I was sure, I often use phrases that imply inexact information (for example: I guess) when what I mean oh yeah, I am sure about this thing.
Re:JavaScript quiz that may confuse you
by bryanrasmussen on Tuesday May 03, 2022 @07:15AM
(#31246931)
no It was definitely a = b = somethingelse structure, because I hate that structure.
Re:JavaScript quiz that may confuse you
by squirtle24 on Tuesday May 03, 2022 @02:10AM
(#31245235)
I didn't notice this quirk about global vars either, and indeed if you copypaste into jsfiddle both console.logs are actually undefined.
TIL if you use strict mode, undefined vars do not become global.
The question have error.
You 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)