Making Sense of Scope: Beginner’s Guide

Scope:

Types of Scopes:

Block Scope:

//var
{
var name = “kiran”;
console.log(name); // kiran
}
console.log(name); //kiran
//let
{
let name = “kiran”;
console.log(name); //kiran
}
console.log(name); //not defined
//const
{
const name = “kiran”;
console.log(name); //kiran
}
console.log(name); // not defined
for (let i = 0; i < number; i++) {
var count =0;
console.log(count)// 0
}
console.log(count)// 0

Local Scope:

Function Scope:

// Without calling the function
function check( ){
var x = 10;
console.log( x ) // undefined
}
// If you console.log( x ), you will get undefined. Because you didn't call the function.// Calling the function
function check(){
var x = 10;
console.log( x ) // 10
}
check( )

Global Scope:

function one( ){
name = "kiran" // Even though name is inside the function, it acts as global scope
// and can be accessed anywhere. Because you haven't declared with any of the variables var, let, and const.
}

Final Words:

--

--

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