1. แบบ Global ตือ ตัวแปรทั่วไป สามารถเข้าถึงตัวแปรได้ทุกที่ในโปรแกรม
2. แบบ Local คือ ตัวแปรท้องถิ่น สามารถเข้าถึงตัวแปรได้เฉพาะขอบเขตที่กำหนดเท่านั้น ไม่สามารถเข้าถึงได้จากภายนอกขอบเขต บล็อก(block) บล็อกเปิดใช้เครื่องหมายปีกกาเปิด ( { ) บล็อกปิดใช้เครื่องหมายปีกกาปิด ( } )
var num=10
function test()
{ //บล็อกเริ่มต้น
var num=100
console.log("value of num in test() "+num)
} //บล็อกสิ้นสุด
console.log("value of num outside test() "+num)
test()
ผลลัพธ์ที่ได้
value of num outside test() 10 //ตัวแปรแบบ Global
value of num in test() 100 //ตัวแปรแบบ Local
"use strict"
function test()
{
var num=100
console.log("value of num in test() "+num)
{
console.log("Inner Block begins")
let num=200
console.log("value of num : "+num)
}
}
test()
ผลลัพธ์
value of num in test() 100
Inner Block begins
value of num : 200
var no =10;
var no =20;
console.log(no);
ผลลัพธ์คือ
20
let no =10;
let no =20;
console.log(no);
error: Identifier 'no' has already been declared.
Example
const x=10
x=12 // ผลลัพธ์ที่ได้จะ error เพราะไปเปลี่ยนแปลงค่าคงที่
var main = function()
{
for(var x=0;x<5;x++)
{
console.log(x);
}
console.log("x can be accessed outside the block scope x value is :"+x);
console.log('x is hoisted to the function scope');
}
main();
ผลลัพธ์
0 1 2 3 4
x can be accessed outside the block scope x value is :5 // เข้าถึงค่าสุดท้ายของตัวแปรได้เมื่ออยู่นอกชอบเขต
x is hoisted to the function scope //สามารถปรับค่าได้เมื่ออยุ่ในขอบเขตของฟังก์ชัน
การประกาศตัวแปรภายในขอบเขตเหมาะสาำหรับการปรับค่าตัวแปรแบบต่อเนื่อง แต่ไม่เหมาะสำหรับกำหนดค่าเริ่มต้นของตัวแปร (เพราะค่าอาจถูกเปลี่ยนไปในแต่ละรอบของการประมวลผลได้) ในการประกาศตัวแปรควรไว้บนสุดของโปรแกรมแบบ Global หรือไว้บนสุดของฟังก์ชัน เพื่อจะสามารถกำหนดค่าต่าง ๆ ได้