How many type of variable in JS and what kind of use?

0 votes
32 views
Ravi Vishwakarma asked 13 days ago in Web Application by Ravi Vishwakarma

How many type of variable in JS and what kind of use?

1 Answer

1 votes
Ethan Karla answered 12 days ago by Ethan Karla
There are 3 ways to declare a JavaScript variable:
1. Using var
2. Using let
3. Using const
Using var
 Variables are containers for storing data (values).In this example, x, y, and z, are variables, declared with the var keyword.
var x = 5;

var y = 6;
var z = x + y;
console.log('The value of z is: ' + z);
Using let
 Variables defined with let cannot be re-declared. Variables defined with let must be declared before use. Variables defined with let have Block Scope.
let x = 'MindStick pvt ltd';

let x = 0;
// SyntaxError: 'x' has already been declared
var x = 2; // Allowed
let x = 3; // Not allowed
{
let x = 2; // Allowed
let x = 3 // Not allowed
}
{
let x = 2; // Allowed
var x = 3 // Not allowed
}
Using const
 Variables defined with const cannot be re-declared. Variables defined with const cannot be re-assigned. Variables defined with const have block scope. Like fixed value.
const PI = 3.141592653589793;

PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error