Understand JavaScript Scope with Clear Explanation & Examples

Get a comprehensive understanding of JavaScript scope with clear explanations and examples. Learn about the two types of scope (global & local) and how closure works in nested functions.

In JavaScript, scope refers to the accessibility and visibility of variables in a program. There are two types of scope in JavaScript: Global scope and Local scope

Global scope

Variables declared outside of a function are in the global scope and can be accessed from anywhere in the code.


let x = 10;

function showX() {

showX(); // Output: 10

Local scope

Variables declared inside a function are in the local scope and can only be accessed within the function.


function showY() {
  let y = 20;

showY(); // Output: 20
console.log(y); // Uncaught ReferenceError: y is not defined

In JavaScript, a nested function can access variables declared in its outer function, but an outer function cannot access variables declared in its inner function. This is known as closure.


function outerFunction() {
  let x = 10;
  function innerFunction() {
  return innerFunction;

let closureFunction = outerFunction();
closureFunction(); // Output: 10

JavaScript scope conclusion

In conclusion, understanding the scope of variables in JavaScript is crucial for writing efficient and maintainable code. Variables declared in the global scope are accessible from anywhere in the code, while variables declared in a function have local scope and can only be accessed within the function.

Understanding scope helps prevent unintended behavior and unexpected results in your code. Additionally, closure in JavaScript allows nested functions to access variables declared in their outer function, which can be useful in various programming scenarios.

Latest posts by W3TWEAKS (see all)


Leave a Reply

Your email address will not be published. Required fields are marked *