- Use let (or const) by default: They behave more predictably and reduce subtle bugs due to scoping issues.
- Avoid var in modern JavaScript: There's rarely a good reason to use it anymore unless you're maintaining legacy code.
- Readability & Safety: let makes block scope explicit, which improves code clarity, especially in loops and conditional blocks.
When might var still appear?
- Legacy codebases: You'll often see var in older projects or
tutorials.
- Global variables workarounds: var declared in the global scope
becomes a property of the global object (window in browsers), which
can come in handy in a couple of situations).
Random use case:
<script>
var title = "Glamorous title"
</script>
Use title in other locations. In modern language this can done in other ways, for sure more elegant. Always take in account risky side effects.