Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความแตกต่างระหว่างการประกาศ (Declaring) และการกำหนดค่าเริ่มต้น (Initializing) ตัวแปรใน JavaScript

ตามข้อกำหนด ECMAScript specification ระบุเกี่ยวกับการประกาศและการกำหนดค่าเริ่มต้นของตัวแปรไว้ดังนี้:

A var statement declares variables that are scoped to the running execution context's VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialized to undefined when created. [...] A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer's AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.

ข้างต้นกำหนดความแตกต่างไว้ชัดเจน:

  • ทุกตัวแปรถูก initialize ด้วยค่า undefined
  • การประกาศตัวแปรถูก initialize ด้วย undefined เมื่อ lexical environment ถูกสร้าง
  • การ initialize นี้ ไม่ได้ทำงานเหมือนการกำหนดค่า (assignment)

ตัวอย่างชัดเจน

// Declaration only (declaration + implicit initialization)
var a; // a === undefined

// Declaration + Initialization
var b = 10; // b === 10

// แยกเป็น 2 ขั้นตอน (เหมือน hoisting ทำงาน)
var c;       // Declaration: c === undefined
c = 20;      // Initialization/Assignment: c === 20

let/const (ES6+)

  • let x; — Declaration + Initialization เป็น undefined (แต่ใน TDZ จนถึงบรรทัดประกาศ)
  • const y = 5; — ต้องมี Initializer ทันที (ไม่สามารถแยกได้)