What is the difference between using let and var in JavaScript?

When should I use let over var? Why? Let us find out!

In modern JavaScript, we have 3 ways to declare variables and assign values to them:

  • const
  • let
  • var

When using variables in JavaScript, I always useconst. It ensures that the value cannot be reassigned, so it is safer to use.

But when I need to redeclare the variable later, I always uselet.

I haven't used itvarFor many years, for me, it only exists for backward compatibility purposes. When I see it in use, I am always surprised.

why?

First,letAlreadyWise range.

More or less the same scope is used in all popular programming languages, namely block scope, indicating variables declared with the following commandletThe block with the closest range.

varOn the contrary, it is a bit weird because it has function scope, which means usingvarRange is the closest function.

This has practical significance. For example, inifOr used asforLoop iterator. useletMake it local in these 2 blocks. usevarHowever, the variable is allowed to be available outside the block, which may cause errors.

Always use the least powerful tool to ensure maximum control over it.While owning rights, they are also given great responsibilities.

Another reason to likeletYesHoisting. likeconst,letVariables will not be suspended, but will be initialized during evaluation.

varInstead, the variables are hoisted to the top of the function, so they can be used even in each linebeforeTheir statement. Very strange, right?

The third reason: when you declareletWith the variable of the same name that already exists, you will receive an error message (inStrict mode).

Finally, there is one big difference: if you declare avarAny variable outside the function, it is assigned toGlobal object, meaning iswindowIn the browser.letCan't work in this way; the variable is available, but it is not attached to the global object, so it cannot be accessed from outside the file.

Download mine for freeJavaScript beginner's manual


More js tutorials: