JavaScript has feature called Scope. it is not simple as you think ,many developers are confuse till now. i'll try my best to understand scope in javascript.
What is Scope ?
- Scope is the accessibility of variables, functions and objects in some particular part of your code during runtime.
Scope in JavaScript :
- in JavaScript there are two types of scopes :
- Global Scope
- Local Scope
Local Scope : Variable which is define within function , variable has local scope.
Global Scope : Variable which is defined outside of function, variable has global scope.
Global Scope :
- When you start writing JavaScript in a document, you are already in global scope.
- a variable has global scope, it written outside a function.
let name = "Akshar"; //by default global scope.
- If variable has global scope, we can use the variable inside a function also. for Example :
let name = "Akshar"; //it has global scope
console.log(name) // Akshar
function printName(){
console.log(name); //Akshar
}
printName( );
Local Scope :
- Variable defined within a function it called local scope.
- for example :
//global scope function
function globalFunction(){
// local scope function
function otherFunction(){
// code
}
}
Block Statement :
- Block statements like if and switch has block scope.
- if we have create variable inside block statements a variable has block scope.
- for Example :
- only var keyword support a declaration in block scope.
if(true){ var name = "Akshar"; } console.log(name) //Akshar
- let and const keyword does not support declaration in block scope, for example :
if(true){
//var keyword has global scope by default and also block scope
var name = "Akshar"; // Akshar
//let keyword doesn't have block scope.
let likes = "coding"; //ReferenceError
//const keyword doesn't have block scope.
const skills = "Javascript"; //ReferenceError
}
console.log(name);
console.log(likes);
console.log(skills);