Skip to content

Lab: Type Playground

ใน lab นี้คุณจะได้สำรวจ type system ของ JavaScript ผ่านการทดลองจริง

  1. สร้างตัวแปรแต่ละ type

    สร้างตัวแปร 7 ตัว แต่ละตัวเป็น primitive type ที่ต่างกัน แล้ว log typeof ของแต่ละตัว

  2. ทดสอบ type coercion

    ทำนายผลลัพธ์ก่อน แล้วรัน code เหล่านี้:

    console.log(typeof NaN);
    console.log(typeof [1, 2, 3]);
    console.log(typeof null);
    console.log("5" + 3);
    console.log("5" - 3);
  3. สร้าง function ตรวจ type

    เขียน function describeType(value) ที่รับค่าอะไรก็ได้ แล้ว return string อธิบาย:

    • ถ้าเป็น null"null"
    • ถ้าเป็น array → "array"
    • นอกนั้น → ใช้ typeof
  4. Template literal challenge

    สร้าง object product ที่มี name, price, inStock แล้วใช้ template literal สร้าง HTML string แสดงข้อมูลสินค้า

Show Solution

Step 1: ตัวแปรแต่ละ type

const str = "สวัสดี"; // string
const num = 42; // number
const bool = true; // boolean
const nothing = null; // null (typeof = "object")
const notDefined = undefined; // undefined
const sym = Symbol("id"); // symbol
const big = 9007199254740991n; // bigint
console.log(typeof str); // "string"
console.log(typeof num); // "number"
console.log(typeof bool); // "boolean"
console.log(typeof nothing); // "object" ⚠️
console.log(typeof notDefined); // "undefined"
console.log(typeof sym); // "symbol"
console.log(typeof big); // "bigint"

Step 2: Type coercion

typeof NaN; // "number" — NaN ยังเป็น number!
typeof [1, 2, 3]; // "object" — array เป็น object
typeof null; // "object" — bug ดั้งเดิม
"5" + 3; // "53" — + ทำ string concatenation
"5" - 3; // 2 — - บังคับแปลงเป็น number

Step 3: function describeType

function describeType(value) {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
return typeof value;
}
console.log(describeType(null)); // "null"
console.log(describeType([1, 2])); // "array"
console.log(describeType(42)); // "number"
console.log(describeType("hello")); // "string"

Step 4: Template literal

const product = { name: "เสื้อยืด", price: 350, inStock: true };
const html = `
<div class="product">
<h2>${product.name}</h2>
<p>ราคา: ${product.price} บาท</p>
<p>สถานะ: ${product.inStock ? "มีสินค้า" : "หมด"}</p>
</div>
`;
console.log(html);