ใช้ String() แปลง null เป็น String จะได้ "null" (String ตัวอักษร 4 ตัว)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body>
<p>Convert null to String</p>
<script>
var myVal = null;
document.write("String: " + String(myVal)); // ผลลัพธ์: "null"
</script>
</body>
</html>
Type Conversion Table: null
| Method | Result | Type |
String(null) | "null" | String |
Number(null) | 0 | Number |
Boolean(null) | false | Boolean |
null + "" | "null" | String (Coercion) |
\`\${null}\` | "null" | Template Literal |
String(null) === "null" | true | Strict Equality |
คำอธิบาย
String(null) → "null" ตาม Spec: ToString(null) = "null"
- ต่างจาก
undefined: String(undefined) → "undefined"
- Coercion:
"" + null === "null", \`Value: \${null}\` === "Value: null"
Best Practice
- ใช้
String(val) สำหรับ Explicit Conversion (ชัดเจนกว่า val + "" หรือ \`\${val}\`)
- Nullish Coalescing สำหรับ Default:
const str = value ?? 'N/A'
- Optional Chaining + Nullish:
obj?.prop ?? 'default'
- JSON:
JSON.stringify(null) → "null" (JSON Literal)
Null vs Undefined String Conversion
| Value | String() | JSON.stringify() |
null | "null" | "null" |
undefined | "undefined" | undefined (Omitted in Object) |