Frontend Development: Scope in JavaScript

Peter Jeon·2023년 6월 20일
0

Frontend Development

목록 보기
23/80
post-custom-banner

JavaScript Scope

The scope in JavaScript is a region of your code where a variable can be accessed. JavaScript has two types of scope – global scope and local scope.

Global Scope

Global Scope

A variable declared outside a function becomes a global variable and it represents global scope. This variable can be accessed from any part of the code.

let globalVar = "I am a global variable";

function checkScope() {
  console.log(globalVar); // "I am a global variable"
}
checkScope();

Local Scope

A variable that is declared inside a function becomes a local variable, and it represents local scope. This variable can only be accessed within the function it was declared.

function checkScope() {
  let localVar = "I am a local variable";
  console.log(localVar); // "I am a local variable"
}
checkScope();
console.log(localVar); // Error: localVar is not defined

Block Scope

With ES6, JavaScript got a new type of scope, called block scope. Variables declared with let and const are block scoped, which means they are only accessible within the block they were declared.

if(true){
  let blockVar = "I am a block variable";
  console.log(blockVar); // "I am a block variable"
}
console.log(blockVar); // Error: blockVar is not defined
profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글