Variable Scope in javascript
Scope determines the accessibility (visibility) of variables.
JavaScript has 3 types of scope:
- Block scope
- Function scope
- Global scope
1. Block Scope :
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords:
letandconst.These two keywords provide Block Scope in JavaScript.
---------------------------------------------------------------------------------------------
Variables declared inside a { } block cannot be accessed from outside the block:
Example:
{
let x = 2;
}
// x can NOT be used here----------------------------------------------------------------------------------------------
Variables declared with the
varkeyword can NOT have block scope.Variables declared inside a { } block can be accessed from outside the block.
Example:
{
var x = 2;
}
// x CAN be used herenote that :
curly braces block { } like : if , switch , for .....
______________________________________________________________
2. Function Scope (Local Scope) :
Variables declared within a JavaScript function, become LOCAL to the function.
JavaScript has function scope: Each function creates a new scope.
Variables defined inside a function are not accessible (visible) from outside the function.
Variables declared with
var,letandconstare quite similar when declared inside a function.They all have Function Scope:
Example:
// code here can NOT use localVariable
function myFunction() {
let localVariable= "Hend";
// code here CAN use localVariable}
// code here can NOT use localVariable---------------------------------------------------------------------------------------------------
3. Global Scope :
Variables declared Globally (outside any function) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript program.
Variables declared with
var,letandconstare quite similar when declared outside a block ,They all have Global Scope.----------------------------------------------------------------------------------------------------
Automatically Global
If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.
This code example will declare a global variable myName, even if the value is assigned inside a function.
Example:
myFunction();
// code here can use myName
function myFunction() {
myName= "Hend";
}// code here can use myName

Comments
Post a Comment