r/learnjavascript • u/Distinct-Gene926 • Jul 27 '26
what's one JavaScript mistake every beginner should avoid?
If you could give one piece of advice to someone learning JavaScript today, what would it be?
It could be about:
- Learning fundamentals
- Debugging
- Async code
- DOM manipulation
- Functions
- Projects
Curious to hear what experienced developers wish they'd known earlier.
83
Upvotes
View all comments
Show parent comment
2
u/engelthehyp Jul 27 '26
letandconstare block-scoped, butvaris function-scoped, and this is not really intuitive, e.g. you usevar i = 0;to declare the loop variable for a for loop, and the next time you write a for loop usingiin that function, declaring it withvarwould be a redeclaration because of the function scope.iwould also be accessible anywhere outside of the loop within the same function, which is undesirable when you want to make sure a temporary variable will stay temporary. This would not be the case withlet.In ye olde (pre-ES6) times, there was only
var, so if you wanted to restrict its scope within a function, the solution was to take the section where you declared the variable and wanted it to be accessible in, surround it with an anonymous function, and then execute that function. That was a very common use of the immediately-invoked function expression (IIFE):(function () { ... })();.But now that we have ways to declare variables and constants within block scope, simulating it with this trick is no longer necessary, and not having to worry about the unexpected effects of function scope saves time and mental effort. If you declared something within a block of a function, you probably didn't want it to be accessible to the entire rest of the function, and that's why using
varis discouraged.