Understanding the scope of variables in Javascript



Understanding the scope of variables in Javascript
Scope determines the accessibility of variables from different parts of your code.
JavaScript has two types of scopes: Global scope and Local scope.
Global scope:
When a variable is ''globally scoped'', that variable is available from anywhere in your program. If the variable is declared outside a function or a block outside a function, leads to it being a globally scoped.
Local scope :
When variables are declared within a function or a block, they are locally scoped. It means that they can only be accessed inside the function or the block they were declared in.
Local scope variables are divided into:
- Function scoped variables: a function scoped variable means that the variable defined within a function will not be accessible from outside the function.
- Block scoped variables: a block scoped variable means that the variable defined within a block will not be accessible from outside the block. A block can reside inside a function, and a block scoped variable will not be available outside the block even if the block is inside a function.
There are three different keywords used to declare a variable in JavaScript. These are: var, let and const.
Var is function scoped, let and const are block scoped.
Here are some examples about var and let:
Function example:
Using Var:
function test() {
var a = 4;
console.log(a); //a=4
}
console.log(a); //a is not defined
‘var’ value is not available outside a function because it's function scoped.
Using let:
In case of a function, the braces identify a block.
function test() {
let b = 6;
console.log(b); //b=4
}
console.log(b); //b is not defined
‘let’ value is not available outside a function because it's block scoped.
Code Block example:
Using Var:
{
var a = 8;
console.log(a); //a=8
}
console.log(a); //a=8
‘var’ value is also avaiable outside a block because it's function scoped not block scoped.
Using let:
In case of a function, the braces identify a block.
{
let b = 10;
console.log(b); //b=10
}
console.log(b); //b is not defined
‘let’ value is only avaiable inside a block because it's block scoped.