Skip to content

Variables & Types

การประกาศตัวแปร

Section titled “การประกาศตัวแปร”

JavaScript มี 3 วิธีประกาศตัวแปร:

// const — ค่าคงที่ เปลี่ยน reassign ไม่ได้
const API_URL = "https://api.example.com";
// let — ตัวแปรที่เปลี่ยนค่าได้ (block-scoped)
let count = 0;
count = 1; // ✅ OK
// var — แบบเก่า (function-scoped) ❌ หลีกเลี่ยง
var oldWay = "avoid this";
Typeตัวอย่างtypeof
string"hello", 'world'"string"
number42, 3.14, NaN"number"
booleantrue, false"boolean"
nullnull"object" ⚠️
undefinedundefined"undefined"
symbolSymbol("id")"symbol"
bigint9007199254740991n"bigint"
const name = "สมชาย";
const age = 25;
// แบบเก่า — string concatenation
const msg1 = "สวัสดี " + name + " อายุ " + age + " ปี";
// แบบใหม่ — template literal (backtick)
const msg2 = `สวัสดี ${name} อายุ ${age} ปี`;
// multiline ได้เลย
const html = `
<div>
<h1>${name}</h1>
<p>Age: ${age}</p>
</div>
`;
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" ⚠️
console.log(typeof [1, 2, 3]); // "object" (array เป็น object)
console.log(typeof { a: 1 }); // "object"