A Simple Explanation of scope in JavaScript ?

WHAT IS SCOPE?

A scope defines where a variable or function is accessible.

Scopes are hierarchical, where child scopes can access  parent scopes, but not vice versa.

There are three core “buckets” of scope: global, function, and block.

GLOBAL SCOPE

A variable declared outside of any function is called a global variable. It is available to any other code in the current document.

* * * 

let foo=’foo’;

FUNCTION SCOPE

A variable declared within a function is available only within that function. They are bound to their respective functions and are not accessible in other functions.

* * *

/ /Global Scope

function someFunction() {

/ /Local Scope #1

function someOtherFunction () {

Local Scope #2

}

}

/ / Global Scope

function anotherFunction() {

/ / Local Scope #3

}

/ / Global Scope

BLOCK SCOPE

A block scope variable is only accessible within a code block (anything that exists within { }).Block scope can only be utilized with let and const. The Var will not work as expected.

* * *

if (awake) {

/ / name is in the global scope because of the ‘var” keyword

var name= ‘Saily’;

/ / Likes is in the Local scope because of the ‘let’  keyword

let likes= ‘Coding’;

/ / skills is in the local scope because of the ‘const’ keyword

Const skills = “Javascript’;

}

console.log(name); / / logs  ‘Saily’

console.log(likes ) ; / / Uncaught ReferenceError: likes is not defined

console.log(skills); / /  Uncaught ReferenceError: skills is not defined

When used appropriately, scoping helps you contribute code without having to worry about collisions.

Hopefully, this post helped you gain a better understanding.

Leave a Reply

Your email address will not be published.