Table of contents
No headings in the article.
Scope
In JavaScript, scope refers to the visibility of variables ,Where you can access a specific variety of Function in our code. Scope is Directly depending on lexical Environment. Javascript has the following kind of Scope .
- Global scope
- Local scope -- Block scope -- Function scope
Global Scope
Variables defined outside any function, block, or module scope have global scope. Variables in global scope can be accessed from everywhere in the application.
let person = 'Kavita';
function display()
{
console.log(person); //kavita
}
console.log(person);//kavita
In JavaScript, a variable can also be used without declaring it. If a variable is used without declaring it, that variable automatically becomes a global variable.
function greet() {
a = "hello"
}
greet();
console.log(a); // hello
Local scope
when we define some variables inside curly brackets {} or inside a specific function then those variables are called local variables .The local scope was further broken down into two different scopes: Function scope and Block scope.
Function Scope
Variables defined inside a function are not accessible from outside the function.
let a=5;
function add(){
let b="hello"
console.log(a+b); //5hello
}
add();
console.log(a+b);error
Block Scope
The variable declared inside the curly brackets { and } can be treated as block scope. Variables declared with let and const can have block scope.These curly brackets can be of loops, or conditional statements, or something else.
let a=4;
{
let a=8;
}
console.log(a);//4