Block scope เป็นพื้นที่ระหว่างสอง { วงเล็บปีกกา } ซึ่งสามารถอยู่ระหว่างลูปได้ หากมีเงื่อนไขหรือคำสั่ง switch let และ const ที่นำมาใช้ใน ES2015 ช่วยให้เราสร้างตัวแปรขอบเขตบล็อกที่สามารถเข้าถึงได้เฉพาะภายในบล็อกเหล่านั้นเท่านั้น
ต่อไปนี้เป็นรหัสที่แสดงการกำหนดขอบเขตบล็อกใน JavaScript -
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result{
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Block scoping in JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to access variable inside and outside the block</h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
let b = 44;{
let a = 22;
}
resEle.innerHTML = 'Accessing variable inside its block b = ' + b + '<br>';
try{
a
}
catch(err){
resEle.innerHTML += 'Accessing variable outside its block a = ' + err;
}
});
</script>
</body>
</html> ผลลัพธ์
รหัสข้างต้นจะสร้างผลลัพธ์ต่อไปนี้ -

เมื่อคลิกปุ่ม 'คลิกที่นี่' -
