Variables Types (Var, Let, Const)
Variables Types (Var, Let, Const)
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript : local
variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
Correct JavaScript variables
var x = 10;
var _value="sonoo";
Incorrect JavaScript variables
var 123=30;
var *aa=320;
Example of JavaScript variable
Let’s see a simple example of JavaScript variable.
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Output of the above example
30
Output:
Hello, I'm JS Rao!
JavaScript global variable
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or
declared with window object is known as global variable. For example:
<html>
<body>
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a(); //calling JavaScript function
b();
</script>
</body>
</html>
Output:
200 200
Note
The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.
When to Use var, let, or const?
3. Always use const if the type should not be changed (Arrays and Objects)
What is Good?
let and const have block scope.
let and const can not be redeclared.
let and const must be declared before use.
let and const does not bind to this.
let and const are not hoisted.
What is Not Good?
var does not have to be declared.
var is hoisted.
var binds to this.