Lab: Type Playground
Lab: Type Playground
Section titled “Lab: Type Playground”ใน lab นี้คุณจะได้สำรวจ type system ของ JavaScript ผ่านการทดลองจริง
-
สร้างตัวแปรแต่ละ type
สร้างตัวแปร 7 ตัว แต่ละตัวเป็น primitive type ที่ต่างกัน แล้ว log
typeofของแต่ละตัว -
ทดสอบ 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); -
สร้าง function ตรวจ type
เขียน function
describeType(value)ที่รับค่าอะไรก็ได้ แล้ว return string อธิบาย:- ถ้าเป็น
null→"null" - ถ้าเป็น array →
"array" - นอกนั้น → ใช้
typeof
- ถ้าเป็น
-
Template literal challenge
สร้าง object
productที่มีname,price,inStockแล้วใช้ template literal สร้าง HTML string แสดงข้อมูลสินค้า
Solution
Section titled “Solution”Show Solution
Step 1: ตัวแปรแต่ละ type
const str = "สวัสดี"; // stringconst num = 42; // numberconst bool = true; // booleanconst nothing = null; // null (typeof = "object")const notDefined = undefined; // undefinedconst sym = Symbol("id"); // symbolconst 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 เป็น objecttypeof null; // "object" — bug ดั้งเดิม"5" + 3; // "53" — + ทำ string concatenation"5" - 3; // 2 — - บังคับแปลงเป็น numberStep 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);