Scope
There are three types of scope in JavaScript:
- Block scopes
- Local scope
- Global scope
Block scope
A block is {}
, variable declared inside the block cannot be accessed from outside when const
and let
keywords are used. Block is
not applicable for var
keyword.
{
var x = 10;
}
console.log(x);
// expected output: 10
{
let y = 2;
}
console.log(y);
// expected output: y is not defined
// No output expected because let is inside the block, console is outside the block
{
const z = 7;
}
console.log((x = z));
// expected output: z is not defined
Work out
Local and Global scope
For every variable there will be scope. It can be either global
or local
scope. Global variable can be accessed throughout a
code. Local variable is limited to a block of code, it is defined within.
var x = 10;
function testScope() {
var x = 5;
console.log("Local variable :" + x);
}
testScope();
console.log("Global variable :" + x);
JavaScript always searches nearby by values. Inside the function testScope x = 5
is inside the same block, function will take that
value. But outside of the function testScope x = 10
.