JavaScript Scope

JavaScript Scope

JavaScript Scope

In JavaScript, scope determines the visibility and accessibility of variables and functions in your code. There are two types of scope in JavaScript: global scope and local scope.

  1. Global scope: Variables and functions declared outside of any function or block have global scope, which means they can be accessed from anywhere in your code.

For example:

				
					var globalVariable = "I am global!";

function globalFunction() {
  console.log("Hello from globalFunction!");
}

console.log(globalVariable); // Output: "I am global!"
globalFunction(); // Output: "Hello from globalFunction!"

				
			
  1. Local scope: Variables and functions declared inside a function or block have local scope, which means they can only be accessed from within that function or block.

For example:

				
					function localFunction() {
  var localVariable = "I am local!";
  console.log(localVariable);
}

localFunction(); // Output: "I am local!"
console.log(localVariable); // ReferenceError: localVariable is not defined

				
			
  1. In addition to global and local scope, JavaScript also has function scope, which means that variables declared inside a function are only accessible within that function.

For example:        

				
					console.log( 'Code is Poetry' );function functionScope() {
  var x = 10;
  if (true) {
    var y = 20;
    console.log(x); // Output: 10
    console.log(y); // Output: 20
  }
  console.log(x); // Output: 10
  console.log(y); // Output: 20
}

functionScope();
console.log(x); // ReferenceError: x is not defined
console.log(y); // ReferenceError: y is not defined

				
			
  1. Starting from ECMAScript 2015 (ES6), JavaScript also supports block scope, which means that variables declared with let and const inside a block are only accessible within that block.

For example:

				
					function blockScope() {
  let x = 10;
  if (true) {
    let y = 20;
    const z = 30;
    console.log(x); // Output: 10
    console.log(y); // Output: 20
    console.log(z); // Output: 30
  }
  console.log(x); // Output: 10
  console.log(y); // ReferenceError: y is not defined
  console.log(z); // ReferenceError: z is not defined
}

blockScope();

				
			

Understanding scope is important in JavaScript to avoid naming collisions and to write code that is easier to maintain and debug.

Join To Get Our Newsletter
Spread the love