JS-Variable Identifier
Identifiers are rules for declaring variables. The following are identifiers for declaring JS variables.
- Variable name must start with a letter (a to z or A to Z), underscore (_), or a dollar sign($).
- Variable names can contain letters, digits, underscore, and dollar signs.
- JS variables are case sensitive (for example z and Z are different variable names).
- Reserved words or JS keywords are can not be used as variable names.
We can declare JavaScript variables in three ways.
1) Declaring Variables Using var Keywords
var keywords is a common way of declaring JS variable.
Example1: Correct variable declaration.
var a1=15; var _b=10; var c="DG Teck";
var 1a=15; var 32_b=10; var 111="DG Teck";
In JavaScript the equal sign(=) is an assignment operator, used to assign a value for a variable. It is different from Algebra, If you want to use equal to an operator like algebra in javascript you can use double equal("==") sign.
Many variables in a Single line
To avoid unnecessary repetition, and reduce wastage of space, you can declare many variables and assign values in a single line by separating them with a comma.
var F_name="Minilik", School="hope School", Age=14;
var keyword allows you to redeclare variables again. In this case, you can also reassign values for variables. In the below example the compiler takes the second value ("10") for variable a.
Example3: Redeclaring variables
Example3: Redeclaring variables
<!DOCTYPE html> <html> <body> <h3>Redeclaring variables</h3> <p id="pa"></p> <script> var a=18; var a=10; document.getElementById("pa").innerHTML = "the value of a ="+ a; </script> </body> </html>
Redeclaring variables
when variables are declared with let can not be redeclared in the same block. variables defined with let has block scope.
Example1: variable defined with let can not be redeclared in the same block as follows.
{ let a=18; let a=10; //'a' has already been declared. you can not redeclare here! }
Example2: You can not access variables out of block scope
<!DOCTYPE html> <html> <body> <h3>we can't access variable out of block scope</h3> <p id="pa2"></p> <script> { let b=18; } document.getElementById("pa2").innerHTML = "the value of b ="+b; </script> </body> </html>
we can't access variable out of block scope
As you saw in the above output there is no displayed value of variable b because variable be is defined with let keyword so it can't be accessed out of block scope or {}.3) Declaring Variables Using const Keywords
When you define variables with const, they can't be redeclared, reassigned and it has block scope then it can't be accessed out of block scope.
A JavaScript const variable must be assigned when it is declared.
Example1: Can't be reassigned.
const a=18; a=10;//Error can't be reassigned a=30;//Error can't be reassigned
const a=18; a=15;//not allowed var a=10;////not allowed let a=30;////not allowed
1 Comments
wow, it is amazing tutorial.
ReplyDelete