In this chapter, we represent the old scripts. It’s not about writing new codes.
Let’s start at the very beginning.
As you have already learned, there are three main ways for variable declaration:
The var originates from ancient times and is different from the other 2. In general, it is not used in modern scripts.
var may seem similar to let, as it can declare a variable.
There are notable differences.
First and foremost, the variables that var has declared are either global or function-wide. You can see them through blocks:
The code blocks are ignored by var. Hence there is a global variable answer.
If you apply let answer instead of the var answer, it can be possible to see the variable only inside the if.
The same is for loops:
In case the code block is inside a function, the var transforms into a function-level variable, like this:
The var declarations are processed at the start of the function. So, it would be best if you define the var variables at the start of the function.
It is visualized in the example below:
It is possible to hoist declarations, but not the assignments.
It is demonstrated in the example below:
The line var siteMessage = "Welcome to W3Docs" consists of two actions:
- Declare variable var
- Assign variable =.
The declaration is processed at the beginning of the function execution. On the contrary, the assignment works at the place it comes out. The code works as follows:
As initially existed only var having no block-level visibility, the developers created a way of emulating it. The invention was named “immediately-invoked function expressions” (IIFE). Of course, you shouldn't use it at present but can find it in older scripts. It looks like this:
In the example above, a Function Expression is made immediately. Hence, the code invokes at once having its private variables.
After learning what var is, you may have a better perception of old scripts in general.
There exist two significant differences of var compared with let and const:
- There are not any block scopes for the var variables. They have minimum visibility at the function level.
- The declarations of var are processed at the beginning of the function.