DEV Community

Cover image for Scope in Javascript with example
Aiviraj Rajput
Aiviraj Rajput

Posted on

Scope in Javascript with example

JavaScript is a powerful and versatile programming language that is widely used for web development. One of the key concepts in JavaScript is scope, which refers to the accessibility of variables, functions, and objects within a program. In this blog post, we will explain the different types of scope in JavaScript, including global scope, local scope, and function scope, and provide examples to help you understand how they work.

Global scope

Global scope in JavaScript refers to variables, functions, and objects that can be accessed from anywhere within a program. These variables, functions, and objects are defined outside of any function or block of code.
For example, consider the following code:

let globalVariable = "Hello, World!";

function myFunction() {
  console.log(globalVariable); // prints "Hello, World!"
}

console.log(globalVariable); // prints "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

In this example, the variable globalVariable is declared outside of any function or block of code, making it accessible from anywhere within the program. Both the myFunction function and the console.log statement outside of the function are able to access and print the value of globalVariable.

Local scope
Local scope in JavaScript refers to variables, functions, and objects that can only be accessed within a specific block of code. These variables, functions, and objects are defined within a block of code, such as a if statement or a for loop.
For example, consider the following code:

if (true) {
  let localVariable = "Hello, World!";
  console.log(localVariable); // prints "Hello, World!"
}

console.log(localVariable); // throws an error, localVariable is not defined
Enter fullscreen mode Exit fullscreen mode

In this example, the variable localVariable is defined within the if statement, making it only accessible within that block of code. The console.log statement within the if statement is able to access and print the value of localVariable, but the console.log statement outside of the if statement throws an error because localVariable is not defined in the global scope.

In conclusion, understanding the concept of scope in JavaScript is essential for writing clean, efficient, and maintainable code. JavaScript has three main types of scope: global scope, function scope, and block scope (commonly referred to as local scope).

  • Global scope applies to variables and functions that are declared outside of any function or block, making them accessible throughout the entire program.

  • Function scope means variables declared within a function are only accessible inside that function.

  • Block scope, introduced with let and const in ES6, restricts variable access to the block (e.g., within {}) in which they are defined.

Top comments (0)