What is variable ?
Variable is like a container or box which used for store data(info,value etc).
History -
In past before ES-6(ECMA Script 6) there are only one way of definig variable like var x=8.5
but now after ES-6 there are 3 way of defining variable i.e var, let and const.
Explain -
Var
- The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.
- Default value is undefined.
- Var first declare then used otherwise it show undefine error.
- If you use var outside of a function, it belongs to the global scope.
- If you use var inside of a function, it belongs to that function.
- If you use var inside of a block, i.e. a for loop, the variable is still available outside of that block.
function foo() {
var x = 1;
function bar() {
var y = 2;
console.log(x); // 1 (function `bar` closes over `x`)
console.log(y); // 2 (`y` is in scope)
}
bar();
console.log(x); // 1 (`x` is in scope)
console.log(y); // ReferenceError, `y` is scoped to `bar`
}
foo();
let
-
let
Declaration declares a block-scoped local variable, optionally initializing it to a value. - If you use let inside of a block, i.e. a for loop, the variable is only available inside of that loop.
function var() {
var x = 1;
{
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function let() {
let x = 1;
{
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
const
-
const
is a variable that once it has been created, its value can never change. - It does not define a constant value. It defines a constant reference to a value.
- Because of this you can NOT:
- Reassign a constant value
- Reassign a constant array
- Reassign a constant object
But you CAN:
- Change the elements of constant array
- Change the properties of constant object
// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;
// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;
// MY_FAV is 7
console.log("my favorite number is: " + MY_FAV);
// trying to redeclare a constant throws an error
// Uncaught SyntaxError: Identifier 'MY_FAV' has already been declared
const MY_FAV = 20;
// the name MY_FAV is reserved for constant above, so this will fail too
var MY_FAV = 20;
// this throws an error too
let MY_FAV = 20;
Thank You.
Top comments (2)
Hey, that was a nice read, you got my follow, keep writing 😉
Thank you Naubit