How does the program remember things? To catch and hold the values JavaScript provides thing called a variable. Variables are containers for storing data
There are 3 types of variables
1) var
2) let
3) const
Short reflection on history
Brendan Eich invented JavaScript in 1995, and at that time, there was just the variable 'var,' but in 2015, they added 'let' and 'const' to the collection.
Variable 'var' mainly is not used. However, if you want to run your code in older browsers, you must use 'var.'
Declaration of variales
The particular word (var, let, or const) indicates that this sentence will define a variable.
The variable's name follows it, and if we want to immediately give it a value, by an = operator and an expression.
Rules for naming variables
Do
1)Names can contain letters, digits, underscores, and dollar signs.
2)Names must begin with a letter.
3)Names can also begin with '$' and '_.'
Don't Do
1)Words with a special meaning, such as var, are keywords and cannot be used as variable names. JS reserves several words for use. At the bottom are some parts of that list.
2) Names are case sensitive, and the capital letter 'A' is not the same as a lowercase 'a'.
Const
Const is type of variable which CANNOT
1)reassighned
2)redeclared
this will be ERROR, because a is a constant and we want to reasighn it.
But we can change some properties of an object or add new ones.
Note: push adds new elements to an array
program will print[1,2,3,4,5]
This will be an ERROR, because we want to reasighn new vale to the object
Var and Let
We can classify these two variables together, separate from const, because they are similar. We can reassign the object. But they have two differences
1)'var' can be redeclared, and program will consider as valid value the last declaration
but 'let' cannot be declared twice
program will print ERROR as a is already declared
2)'let' allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the 'var' keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
Scope
The scope is the space where the values of our variables are visible. In the above, we discussed the difference between 'var' and 'let.' They work in different amounts of scopes.
If variables let and const are declared in some scope, they are visible in subscopes of that scope. Variable var is visible everywhere with its last declared value.
If the program does not see the variable in a particular scope, it goes up and takes the latest declared value.
Top comments (0)