Part 06 · Interview · 6.2
35 câu hỏi JavaScript và TypeScript
Trả lời bằng language/host semantics, observable behavior và production consequence—not thuộc lòng output puzzle.
Answer pattern: định nghĩa semantics → nêu edge/failure → đưa production control hoặc evidence.
Language fundamentals
1. JavaScript engine khác browser runtime?
Engine thực thi ECMAScript; browser cung cấp DOM, fetch, timers và event-loop integration. Node có host APIs/event loop khác.
2. let/const/var?
let/const block scoped và TDZ; var function/global scoped, initialization/hoisting khác. const khóa binding không làm object immutable.
3. Closure giữ gì?
Access tới lexical environment/bindings, không copy values; có thể giữ object reachable và gây leak nếu listener/cache sống lâu.
4. ===, Object.is, SameValueZero?
===: NaN unequal, zeros equal; Object.is: NaN equal, zeros distinct; SameValueZero: NaN equal, zeros equal, dùng trong Set/Map/includes.
5. Vì sao 0.1 + 0.2?
Binary64 không biểu diễn chính xác nhiều decimal; cần tolerance hoặc decimal/minor-unit domain model, không chỉ round tùy ý.
6. Shallow copy caveat?
Spread/assign copy top-level enumerable own values; nested references vẫn alias, prototype/descriptors/private state không clone đầy đủ.
7. Prototype chain?
Property lookup từ own lên [[Prototype]]; class methods ở prototype. Mutation/pollution ảnh hưởng lookup, security và optimization.
8. Arrow function khác function?
Arrow lexical this/arguments/new.target, không constructible/prototype; normal this theo call form và có thể bind/call/apply.
9. Map vs Object?
Map key mọi value, insertion order, size/iteration rõ; Object phù hợp records/property semantics nhưng có prototype/descriptors và string/symbol keys.
10. ESM live binding?
Import quan sát exported binding thay đổi, không copy value; import read-only phía consumer. Circular graph có initialization hazards.
Async và browser
11. Task vs microtask?
Event loop chạy task rồi microtask checkpoint trước render/next task; Promise reactions là microtasks. Microtask chain vô hạn có thể starve UI.
12. async function trả gì?
Luôn trả Promise; return adopts value/thenable, throw thành rejection. await suspend function và continuation thành job.
13. Promise.all vs allSettled?
all fail-fast nhưng underlying work không tự cancel; allSettled đợi mọi settlement. Chọn theo atomic/partial-result requirement.
14. Race condition trong UI dù single thread?
Async completions interleave: request cũ về sau ghi đè state mới. Dùng abort, request identity/version hoặc state machine.
15. Cancel fetch?
AbortController/Signal truyền abort; handle abort riêng và cleanup. Promise wrapper không tự dừng underlying I/O.
16. Fetch 404 có reject?
Thường không; fetch resolves Response khi HTTP response nhận được, phải check ok/status. Reject cho network/abort classes.
17. Event delegation?
Listener ancestor dùng bubbling và target/closest để xử lý children động; cân nhắc non-bubbling events, shadow DOM/composed path và cleanup.
18. CORS có bảo vệ API?
Không phải authorization; nó hạn chế browser script đọc cross-origin response. Server vẫn authn/authz/CSRF/input validation.
19. localStorage lưu token?
JS-readable nên XSS có thể lấy; synchronous và không expiry built-in. Chọn session/security architecture; HttpOnly cookie có CSRF considerations.
20. Memory leak browser thường từ đâu?
Listeners/timers/subscriptions, unbounded caches, closures và detached DOM còn reachable. Cleanup/abort/bound cache và heap profile.
TypeScript và production
21. any vs unknown?
any tắt checking và lan truyền; unknown nhận mọi value nhưng phải narrow trước dùng. Boundary external nên unknown + runtime validation.
22. Structural typing caveat?
Compatibility theo shape, không nominal intent; excess checks không exact và mutable variance có unsound corners. Brand khi identity domain cần.
23. Discriminated union?
Union có literal tag cho state variants, narrowing và exhaustive never; tránh optional fields tạo impossible combinations.
24. Type assertion có validate runtime?
Không;
as chỉ hướng checker và erased. JSON/network cần parser/schema validator/type guard có runtime evidence.25. Generic khi nào hữu ích?
Khi cần bảo tồn quan hệ type giữa inputs/outputs/members; generic chỉ xuất hiện một chỗ thường không đem information.
26. path alias chạy runtime?
tsconfig paths chủ yếu giúp compiler resolution; runtime/bundler/test runner phải cấu hình tương ứng hoặc emitted import sẽ fail.
27. Tree shaking cần gì?
Static ESM graph, accurate sideEffects và bundler optimization; CommonJS/dynamic access/side effects hạn chế. Verify output analyzer.
28. Core Web Vitals?
LCP loading, INP responsiveness, CLS visual stability; đánh giá field/RUM phân vị theo device/network, không một lab score.
29. Test frontend theo gì?
Theo user-visible behavior/accessibility; pure unit, DOM/component, contract và ít browser E2E. Tránh implementation selectors/snapshots khổng lồ.
30. npm supply-chain risks?
Typosquat/account compromise/install scripts/transitive drift/cache poisoning; lockfile integrity, least CI permission, review/audit/SBOM/provenance và immutable artifact.
Markdown-derived follow-ups
31. Which parts of the event loop come from ECMAScript and which from the host?
ECMAScript defines jobs, execution contexts and Promise reactions; browser/Node supplies timers, I/O queues, rendering and phase integration. Verify host-specific ordering with a pinned reproduction.
32. How does run-to-completion coexist with asynchronous race conditions?
A single job is not interleaved, but separate jobs can complete in a different order after awaits/I/O. Use request identity, cancellation or a state machine to reject stale results.
33. Why does as User not make an API response safe?
Assertions only guide the compiler and disappear from JavaScript. The response remains untrusted until a runtime parser/guard proves the fields and invariants.
34. When can a user-defined type predicate lie to the compiler?
A predicate can return true without checking all required invariants, making narrowed code unsound. Keep predicates small, test malformed inputs and validate nested fields.
35. How do realms affect instanceof across frames?
Each realm has separate intrinsics/prototypes, so an object from another frame may fail local
instanceof. Prefer semantic checks such as Array.isArray or schema validation.