Scope in JavaScript

Global Scope

//global scope
var name = 'abhayjain13'
console.log(name); //abhayjain13
function print(){
console.log(name); //abhayjain13 is accessible here
}
print(); //abhayjain13

Local Scope

//global scope
function foo1(){
//local scope 1
function foo2(){
//local scope 2
}

function foo3(){
//local scope 3
}
}
//global scope
function foo4(){
//local scope 4
}
//global scope

1. Function Scope

function foo(){
var name ='abhayjain13';
console.log('inside function: ',name);
}
foo(); //inside function: abhayjain13
console.log(name); //error: name is not defined

2. Block Scope

function foo(){
if(true){
var name1 = 'abhayjain'; //exist in function scope
const name2 = 'abhayjain1'; //exist in block scope
let name3 = 'abhayjain13'; //exist in block scope
}
console.log(name1);
console.log(name2);
console.log(name3);
}
foo();
//result:
//abhayjain
//error: name2 is not defined
//error: name3 is not defined

3. Lexical Scope

function foo1(){
var name1 = 'abhayjain';
const name2 = 'abhayjain1';
let name3 = 'abhayjain13';
function foo2(){
console.log(name1);
console.log(name2);
console.log(name3);
}
foo2();
}
foo1();//result:
//abhayjain
//abhayjain1
//abhayjain13

--

--

--

Developer with 3 yrs of industrial experience in developing scalable web applications.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How To Easily Store And Display User Images In React

Starting from Scratch Part 1: Building the Frontend with React.

Thoughts About Micro-Frontends in 2020

Missing VueJS components and changes not showing up 🤦‍♀️🤦‍♂️😢

https://www.oddbird.net/static/images/blog/2018/vueconf.jpg

Portfolio Project #5: React, Redux, Rails API — SelfCare

Handling User Input in React  — CRUD

Counter App with ReactJS

Java 15 is here with 14 new features

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.

More from Medium

Special Concepts about JavaScript & MongoDB

ES2022 features with simple examples

Basics of JavaScript for technical interviews

Function Buzzwords in Javascript