In javaScript and LWC we can declare variable in below way:-
The type of declaration depends on the scope. The scope is the fundamental concept in all programming languages that defines the visibility/accbilty of a variable.
Type of declaration
var a = 48;
const b = 'Hello Shaik';
let c = true;
1) Var
The var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
Ex:
function testVar() {
var x = 1;
if (true) {
var x = 2; // same variable
console.log(x); // 2
}
console.log(x); // 2
}
2) let
let allows you to declare variables that are limited in scope to the block, statement, or expression in which they are used.
if you run the below the code it will throw an error
if (true) {
let name = 'Hi Test User';
}
alert(name); //generates an error
In this above case, the name variable is accessible only in the scope of the if statement because it was declared as let.
Ex:
function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
3) const
const variables have the same scope as variables declared using let. The difference is that const variables are immutable - they are not allowed to be reassigned.
Ex:
const a = 'Hello Test User';
a = 'Bye';
console.log(a);
Thanks for reading this boag
The type of declaration depends on the scope. The scope is the fundamental concept in all programming languages that defines the visibility/accbilty of a variable.
Type of declaration
var a = 48;
const b = 'Hello Shaik';
let c = true;
1) Var
The var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
Ex:
function testVar() {
var x = 1;
if (true) {
var x = 2; // same variable
console.log(x); // 2
}
console.log(x); // 2
}
2) let
let allows you to declare variables that are limited in scope to the block, statement, or expression in which they are used.
if you run the below the code it will throw an error
if (true) {
let name = 'Hi Test User';
}
alert(name); //generates an error
In this above case, the name variable is accessible only in the scope of the if statement because it was declared as let.
Ex:
function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}
3) const
const variables have the same scope as variables declared using let. The difference is that const variables are immutable - they are not allowed to be reassigned.
Ex:
const a = 'Hello Test User';
a = 'Bye';
console.log(a);
Thanks for reading this boag
No comments:
Post a Comment