Skip to main content
JavaScriptWeb Dev

Scope in JavaScript & the 4 different types scope – Part 1

By January 24, 2022July 20th, 2022No Comments
4 different types of scope in JavaScript: local global block lexcical

The word “scope” itself means “extent “or “range” to which a subject matter is limited to. In context to coding this means, that whether you can use a variable or not, is determined by where it is declared in your code. There are 4 types of scope in a JavaScript document, for example script.js

1. Global scope

Inside a JavaScript document, global scope is the area outside any functions and blocks of code which are determined by the presence of opening and closing curly braces {}. For example:


//Global scope

function x() {

}    

2. Local scope

Local scope refers to variables that are declared and/or assigned a value within a function.


function localScope() {

  // local scope

}

3. Block scope

A block scope is defined as the area within curly braces {}. For example, if – else conditional statements, switch conditions, for and while loops and others.

{
 //block scope
}

4. Lexical scope

Within a function, any code blocks and child functions have access to the variables defined inside the main parent function’s scope. This is called lexical scope.


function parentScope() {

  //variables declared here

  function child() {

    //variables can be accessed here

  }

  child();

}

Leave a Reply