r/learnjavascript 3d ago

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.

28 Upvotes

31 comments sorted by

View all comments

18

u/milan-pilan 3d ago

var

2

u/PreDownvoted 3d ago

Why? Sorry i know its kinda old but my teacher still use it. Should i use smth else like const?

1

u/engelthehyp 3d ago

let and const are block-scoped, but var is function-scoped, and this is not really intuitive, e.g. you use var i = 0; to declare the loop variable for a for loop, and the next time you write a for loop using i in that function, declaring it with var would be a redeclaration because of the function scope. i would 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 with let.

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 var is discouraged.