With ES2016, two new ways to define variables were introduced with let and const. Before that you could use var to define variables.
Scope are mainly two type
- Function Scope
- Block Scope
1. Function Scope
function myFunction() {
var firstName = 'Pradeep';
console.log(firstName);
//Output : Pradeep
}
console.log(firstName);
//Output : ReferenceError: firstName is not defined
}
Using var, variables are function-scope because their visibility is limited to function. When you try to use it outside of the function, you’ll get an error.
2. Block Scope
if(true){
var firstName = 'Pradeep';
let test1 = 'Front end devloper';
const test2 = 'and Ui Devloper';
console.log(firstName); // Pradeep;
console.log(test1); // front end devloper;
console.log(test2); // and Ui Devloper;
}
console.log(firstName); // Pradeep;
console.log(test1); //ReferenceError: test1 is not defined;
console.log(test2); //ReferenceError: test2 is not defined
The visibility of firstName isn't limited by the if statement block. And test1 nad test2 are limited in to the block code.
What is var?
- The var statement declares a variable and can also optionally initialize its value.
- var is function scoped when it is declared within function. That means that it is available and can be accessed only within that function
- var are function scope because their visibility is limited to function. When you try to use outside the function you'll get an error.
function myFun(){
var fname="Pradeep";
console.log(fname); //Output : Pradeep
}
console.log(fname); //Output : ReferenceError: fname is not defined
or
var x = 1;
if (x === 1) {
var x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 2
What is let?
- The let allows you to declear variables that are limited in scope to the perticular block scope.
- block scope {} between the code
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 1
What is Const ?
Const are block scoped, much like variables defined using the let statement. the value of const cannot change through reassignment, and it can't be re-declared.
const number = 42;
try {
number = 99;
} catch (err) {
console.log(err);
// expected output: TypeError: invalid assignment to const `number'
// Note - error messages will vary depending on browser
}
Comments
Post a Comment