Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I've never understood the hate for variable shadowing. Maybe it's because I mostly use Rust, but I've always found it a useful boon for readability. You often want to extract/parse/wrap/package some value within the middle of a function in a manner that changes its type/form but not its semantic purpose. Shadowing the old value's variable name is brilliant: it communicates that there's a step-change in the responsibilities of the function, demarcating layers from one-another and preventing accidental use of the old value.


> I've never understood the hate for variable shadowing. Maybe it's because I mostly use Rust,

That's likely a good chunk of it. My impression is it's more acceptable in languages where you have a very correctness-focused compiler, and `rustc` is that both with types and liveness/ownership. In a language where it's less clear when you copy values or hand out mutable references, or where implicit conversions occur on type mismatches, it's gonna be a different experience.

I think this article is best read as js/ts-specific advice, e.g. the split between null and undefined also isn't something you have to worry about in most other languages, and the semantics of various `?` and `?.` operators can vary a lot.


If you like to actually read the code, then being able to search for a variable name really helps comprehension. Shadowing makes that harder, by introducing multiple distinct objects with the same name.

Now you need something like an IDE to easily follow the lifetime of an object. Introducing a heavyweight dependency like that, as a prerequisite for simply following the code easily, is... a poor choice.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: