JavaScript Scope


In JavaScript, the term "scope" refers to the portion of a program that allows access to a variable, function, or object. The element's definition in the program usually sets the element's scope, which controls the visibility and lifetime of the element.

JavaScript has four types of scope:

  1. Global Scope
  2. Local Scope
  3. Block Scope
  4. Function Scope

1. Global Scope

Global scope refers to the area of the code where a variable or function is accessible throughout the entire program. Variables declared outside of any functions have global scope, and they can be accessed from anywhere in the program, including inside functions. When declared outside of a block, variables declared with "var," "let," and "const" are quite similar to one another.

Example

Preview

2. Local Scope

Local scope refers to the area of the code where a variable or function is accessible only within a particular block of code, such as a function or a loop. Variables declared inside a function have local scope and can only be accessed from within that function. Variables with the same name can be used in separate functions since local variables can only be utilized within of their respective routines. As a function begins, local variables are generated, and they are removed after the function is finished.

Example

Preview

3. Block Scope

Block scope is a type of local scope in JavaScript that is introduced with the "let" and "const" keywords in ES6. In block scope, variables are accessible only within the block of code where they are declared, which is typically defined by curly braces {}.

Example

Preview

4. Function scope

Function scope is a type of local scope in JavaScript that is created when a variable is declared inside a function using the var keyword. Variables with function scope are accessible only within the function where they are declared, and are not accessible outside the function.

Example

Preview

5. Automatically Global

In JavaScript, a variable that is declared without any keyword (such as var, let, or const) inside a function or a block of code is automatically declared in the global scope. This means that the variable is accessible from anywhere in the program, just like a global variable declared outside of any functions or blocks.

Example

Preview

6. Strict Mode

Strict mode is a feature in JavaScript that allows you to place your code in a restricted operating context, which prevents certain actions from being taken and throws more errors when certain mistakes are made. It is implemented using the 'use strict' statement at the beginning of a script or a function.