Variables are containers for storing data values. Variable is assigned with datatype. It is a name of memory location.
variable types:
1.let - used when the value may change.
let a = 10;
a = 20;
console.log(a);
output : 20 //let allow to reassign value
2.const - used when the value should not be reassigned.
let name = "Priya";
let age = 25;
const city = " Chennai";
console.log(name);
console.log(age);
console.log(city);
output: Priya
25
Chennai
3.var - to declare a variable.
Scope of variables
Local variable : Variable that declare inside the method. You can only assign the variable within that method and other methods cannot be assigned.
function add()
{
let a = 20; //local variable
console.log(a);
}
add();
Global variable : Variable that declared inside the class but outside the body of the method. we can access this variable anywhere in the program.
let a = 10 ; // global variable
function add()
{
let a = 20;
console.log(a);
}
add();
Block variable : Variable declared with let or const inside the bracket{ } can be accessed only within the block.
if (true)
{
let a = 20;
console.log(a);
}
console.log(a); //error
output : 20
Top comments (0)