Java Script
JS variables
JS variables can be decleared in 4 ways
1. using let
2. using var
3. using var – not recommended
4. automatically ( Not recommended)
When to Use var, let, or const?
Always declare variables
Always use const if the value should not be changed
Always use const if the type should not be changed (Arrays and Objects)
Only use let if you cannot use const
Never use var if you can use let or const.
// using Let
let x = 4;
let y = 7;
let z = x + y;
[Link]("The value of x+y = " + z);
// declearing variables using let
let carName ;
carName = "Volvo";
[Link](carName);
// Declearing a variable using const
const price1 = 5;
const price2 = 6;
const total = price1 + price2;
[Link]("The total price is " + total);
JavaScript Let
The let keyword was introduced in ES6 (2015)
Variables declared with let have Block Scope
Variables declared with let must be Declared before use
Variables declared with let cannot be Redeclared in the same scope
Variables declared inside a { } block cannot be accessed from outside the
block:
{
let x = 2;
}
// x can NOT be used here
Variables declared with the var always have Global Scope.
Variables declared with the var keyword can NOT have block scope
Cannot be Redeclared
Variables defined with let can not be redeclared.
You can not accidentally redeclare a variable declared with let.
let x = 5;
let x= “John Doe”;
Variables defined with var can be redeclared.
var x = "John Doe";
var x = 0;
Redeclaring Variables
Redeclaring a variable using the var keyword can impose problems.
Redeclaring a variable inside a block will also redeclare the variable
outside the block
Redeclaring a JavaScript variable with var is allowed anywhere in a
program:
Example
var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Redeclaring a variable using the let keyword can solve this problem.
Redeclaring a variable inside a block will not redeclare the variable
outside the block:
Example
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2 // For the output this value will displace because it is in the
block
}
// Here x is 10
With let, redeclaring a variable in the same block is NOT allowed
Redeclaring a variable with let, in another block, IS allowed