Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
322 changes: 322 additions & 0 deletions blog/2025-08-13-interview-tips-2025-8.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,322 @@
---
title: Interview Tips
description: Interview Tips that generated by ChatGPT 5
tags: [javascript, node.js, interview]
hide_table_of_contents: false
---

## JavaScript Core

1) What is a closure?
- A closure is a function that remembers its outer scope via the **lexical environment**, even after the outer function returns.
- If asked: It keeps access to variables where it was created. Example: `function outer(){ let x=1; return function(){ console.log(x) } }`.

2) Hoisting in JavaScript?
- **Declarations** are moved to the top; **var** hoists with undefined, **let/const** hoist but stay in **TDZ**.
- If asked: `var` is usable before line but is `undefined`. `let/const` throw if used before declared. Example: `console.log(a); var a=1;` vs `console.log(b); let b=1;`.

3) How does “this” work?
- **this** depends on **call site**: default, **method**, **call/apply/bind**, **new**, or **arrow** (lexical).
<!-- truncate -->
- If asked: In a method, `this` is the object. With `call/apply/bind`, you set it. Arrow uses the outer `this`. Example: `obj.fn()` vs `fn.call(obj)`.

4) Prototype vs class?
- **Prototype chain** is native inheritance; **class** is syntax sugar over prototypes.
- If asked: `class` makes prototype code look cleaner. Under the hood it still uses prototypes. Example: `class A{}` ≈ function + `A.prototype`.

5) Event loop basics?
- JS is **single-threaded**; **event loop** runs **call stack**, then **microtasks** (Promises), then **macrotasks**.
- If asked: Promises run before timers in the same tick. Example order: sync → microtasks → timers.

6) Promise vs async/await?
- **Promises** model async; **async/await** is syntax for **sequential** style with **try/catch**.
- If asked: `await` pauses inside async function. Use `try/catch` for errors. Example: `const x = await fetch()`.

7) Debounce vs throttle?
- **Debounce** waits for silence; **Throttle** limits calls to a **rate**.
- If asked: Debounce: run after user stops typing. Throttle: run at most once per 100ms while scrolling.

8) == vs ===?
- **===** checks **type + value**; **==** does **coercion** (avoid unless sure).
- If asked: `0 == false` is true; `0 === false` is false. Prefer `===` to avoid surprises.

9) var vs let vs const?
- **var** is **function-scoped**; **let/const** are **block-scoped**; **const** blocks **reassignment**.
- If asked: Use `const` by default, `let` when you reassign, avoid `var`. Blocks are `{ ... }`.

10) Arrow function differences?
- **Arrow** has **lexical this**, no **arguments**, not **constructible**.
- If asked: Don’t use arrow as constructors or methods needing their own `this`.

11) Shallow vs deep copy?
- **Shallow** copies top level; **Deep** copies nested data (**references** matter).
- If asked: Shallow: `const b = {...a}`. Deep: use `structuredClone(a)` (modern) or a lib.

12) How to avoid memory leaks?
- Clear **timers**, remove **listeners**, avoid **globals**, break heavy **closures**.
- If asked: Keep `addEventListener` balanced with `removeEventListener`. Clear intervals on unmount.

13) What is currying?
- Turn a function of **n args** into **n functions** of one arg for **reuse**/**composition**.
- If asked: `sum(1)(2)` instead of `sum(1,2)`. Useful to preset arguments.

14) Immutable data—why?
- **Immutability** reduces **side effects**, helps **debugging**/**change detection**.
- If asked: Don’t modify input. Return new arrays/objects. Example: `const b = a.map(x=>x)`.

15) Module systems: CommonJS vs ES Modules?
- **CommonJS** is **sync** (Node legacy); **ESM** is **static**, supports **tree-shaking**.
- If asked: CJS: `const x = require('x')`. ESM: `import x from 'x'`.

16) What is CORS?
- **Cross-Origin** control via **HTTP headers** for **browser** access across **origins**.
- If asked: Server must allow your origin with headers like `Access-Control-Allow-Origin`.

17) How does garbage collection work?
- Uses **reachability**; **mark-and-sweep** removes **unreachable** objects.
- If asked: If nothing references an object, GC frees it automatically.

18) for...in vs for...of?
- **for...in** iterates **keys**; **for...of** iterates **values** of **iterables**.
- If asked: Use `for...in` for object keys; `for...of` for arrays, strings, maps.

19) How to handle errors in async code?
- Use **try/catch** with **async/await** or **.catch**; add **unhandledRejection** handler.
- If asked: Always handle promise rejections. Example: `await fn().catch(handle)` or `try { await fn() } catch(e){}`.

20) What is event delegation?
- Bind one **listener** to a **parent** and use **bubbling** for **performance**.
- If asked: Listen on `<ul>`, check `event.target`, handle `<li>` clicks.

21) What is tree-shaking?
- Remove **unused exports** using **ESM** to reduce **bundle size**.
- If asked: Export only what you use; bundlers drop the rest in production.

22) What is code splitting?
- Split **bundles** and **lazy-load** for better **initial load**.
- If asked: Load pages/components on demand. Example: `import('page')`.

23) What are Web Workers?
- Run code in **background threads** to keep **UI** responsive.
- If asked: Move heavy loops to a worker; communicate via `postMessage`.

24) How to prevent XSS on the client?
- **Escape/encode** output, avoid **innerHTML**, use **CSP**, sanitize **untrusted** input.
- If asked: Never render raw user input. Use libraries that auto-escape templates.

25) Map vs Object?
- **Map** keeps **insertion order**, any **key type**, better for **adds/removes**; **Object** for **structured data**.
- If asked: Use `Map` for dynamic keys; use plain objects for fixed shape data.

## TypeScript

26) any vs unknown vs never?
- **any** disables checks; **unknown** needs **narrowing**; **never** means no value (**throw**).
- If asked: Prefer `unknown` over `any`. `never` is for functions that throw or never finish.

27) interface vs type?
- **interface** supports **declaration merging**; **type** is more **flexible** (unions).
- If asked: Use `interface` for objects you expect to extend. Use `type` for unions/complex types.

28) What are generics?
- **Generics** make code **reusable** and **type-safe** by parameterizing types.
- If asked: Like a function for types: `Array<T>` can be `Array<number>` or `Array<string>`.

29) Type narrowing?
- Use **typeof**, **instanceof**, **in**, **type guards** to refine **unions**.
- If asked: Check before use. Example: `if (typeof x === 'string') x.toUpperCase()`.

30) Discriminated unions?
- Use a **tag field** to switch on **variant** types safely.
- If asked: Example: `{ kind: 'ok', data } | { kind: 'err', error }` and switch on `kind`.

31) Utility types you use?
- **Partial**, **Required**, **Readonly**, **Pick**, **Omit**, **Record**, **ReturnType**, **NonNullable**.
- If asked: They transform types. Example: `Partial<T>` makes all fields optional.

32) What is a type guard?
- A function with a **predicate** (x is T) that **narrows** types.
- If asked: Example: `function isNum(x: unknown): x is number { return typeof x==='number' }`.

33) Enums vs const enums?
- **Enum** emits JS; **const enum** is **inlined** (needs consistent config).
- If asked: Prefer unions of string literals for simple cases: `'red' | 'blue'`.

34) Strict mode benefits?
- **strict** catches **null/undefined**, implicit **any**, improves **safety**.
- If asked: It finds bugs early. Keep `strict: true` in `tsconfig.json`.

35) When to use never?
- **Exhaustive** switches; functions that **don’t return**.
- If asked: Use `never` in a `default` case to ensure all union members are handled.

36) Module resolution and path aliases?
- Set **baseUrl/paths** in **tsconfig**; align **bundler/test** configs.
- If asked: Example `paths`: `"@/utils/*": ["src/utils/*"]`.

- Use **generics** (e.g., `React.FC<Props>`, `Request<Params,Res,Body>`).
- If asked: For Express: `Request<P, ResBody, ReqBody, Query>`.

38) Share types between server and client?
- Use a **shared package/folder** with **.ts/.d.ts**; **workspace** link.
- If asked: Put types in `shared/` and import from both sides; publish as npm workspace if needed.

## Node.js

39) Node event loop phases?
- **timers**, **pending callbacks**, **idle/prepare**, **poll**, **check**, **close**; **microtasks** between phases.
- If asked: `setImmediate` runs in `check` phase, often after I/O; `process.nextTick` runs before other microtasks.

40) Streams—why use them?
- Handle **large/incremental** data with low **memory**; support **backpressure**.
- If asked: Read a big file chunk by chunk. Pipe: `fs.createReadStream().pipe(res)`.

41) What is a Buffer?
- **Buffer** holds **binary** data for **I/O**, **encoding/decoding**.
- If asked: Example: `Buffer.from('hi')` gives bytes; use for TCP/file ops.

42) cluster vs worker_threads?
- **cluster** uses **processes**; **worker_threads** share **memory** for **CPU-bound** work.
- If asked: Use workers for CPU heavy tasks (hashing). Use cluster to use many CPU cores for HTTP.

43) child_process use cases?
- Run **shell commands**, **spawn** tools, offload work; manage **stdout/stderr**/**exit codes**.
- If asked: Example: `exec('ls -la', cb)`; `spawn` for streaming output.

44) Express middleware order?
- Order is **top-to-bottom**: **parsers**, **security**, **routes**, **error handler**.
- If asked: Error handler has 4 args `(err, req, res, next)` and goes last.

45) Handling config and secrets?
- Use **env vars**, **dotenv** (dev), or **secret manager**; don’t commit **secrets**.
- If asked: Keep `.env` out of git. In cloud, use managed secret stores.

46) Logging best practices?
- **Structured logs** (JSON), **correlation IDs**, **levels**, avoid **PII**.
- If asked: Include `requestId` in each log line to trace a request.

47) Securing a Node API?
- **helmet**, **rate limiting**, **CORS** rules, **input validation** (zod/joi), update **deps**.
- If asked: Validate all inputs at the edge. Return 400 on bad data.

48) Common Node perf tips?
- Avoid **sync I/O**, use **pooling**, reuse **sockets**, use **caching**.
- If asked: Use async DB calls and connection pools. Cache hot reads in Redis.

49) Graceful shutdown?
- On **SIGTERM/SIGINT**: stop **accepting**, finish **in-flight**, **close**, then **exit**.
- If asked: Listen to signals, close server, close DB, then `process.exit(0)`.

50) Handling unhandled rejections?
- Listen to **unhandledRejection**, log, and consider **fail-fast** with **restart**.
- If asked: Process may be in bad state; prefer exiting and letting a supervisor restart.

## Testing

51) Unit vs integration vs e2e?
- **Unit**: function; **integration**: modules together; **e2e**: **full flow**.
- If asked: Start with many unit tests, fewer integration, few e2e due to speed.

52) Mock vs stub vs spy?
- **Mock**: behavior + **assertions**; **stub**: **canned** responses; **spy**: **record** calls.
- If asked: Use a mock when the test must fail if a function wasn’t called.

53) Test Pyramid?
- More **unit**, fewer **integration**, few **e2e** for **speed**/**stability**.
- If asked: UI tests are slow and flaky; keep them minimal but meaningful.

54) Code coverage meaning?
- **Coverage** shows executed code; value is in **meaningful** tests, not **percent**.
- If asked: 100% coverage can still hide bugs. Focus on critical paths.

55) AAA pattern?
- **Arrange**, **Act**, **Assert** for **clarity**/**consistency**.
- If asked: Keep each test short and clear with these three parts.

56) TDD cycle?
- **Red → Green → Refactor**: failing test, make it pass, **clean up**.
- If asked: Write the test first, then code, then improve the code safely.

## CI/CD

57) CI vs CD?
- **CI**: integrate/test **often**; **CD**: deliver/deploy **automatically**/**safely**.
- If asked: CI runs on every push. CD deploys after tests pass.

58) What to cache in CI?
- **Dependencies**, **build artifacts**, **toolchains** to speed **pipelines**.
- If asked: Cache keys should include lockfile hash to avoid stale caches.

59) Artifacts in CI?
- **Artifacts** are saved **build outputs** shared across **jobs/stages**.
- If asked: Example: save `dist/` to reuse in deploy job.

60) Branching strategy?
- Prefer **trunk-based** or short **feature** branches with **PRs**/**reviews**.
- If asked: Keep branches small, merge daily, use feature flags.

61) Versioning and releases?
- **SemVer**, **tags**, **CHANGELOG**, **conventional commits** for **automation**.
- If asked: `fix:` `feat:` `BREAKING CHANGE:` drive release notes and version bumps.

62) Deployment strategies?
- **Blue/Green**, **Canary**, **Rolling** for **risk** reduction and **rollback**.
- If asked: Canary: send small traffic first; rollback fast if errors rise.

63) How to keep pipelines fast?
- Run **in parallel**, **cache**, split **lint/test/build**, **fail fast**.
- If asked: Run unit tests in parallel, e2e separately, cache node_modules.

64) Secrets in CI?
- Store in **CI secrets**, use **scoped tokens**, **rotate** regularly.
- If asked: Don’t echo secrets in logs. Use environment variables from the CI.

## Performance and Reliability

65) Frontend performance quick wins?
- **Lazy-load**, **preload** critical, **compress** (gzip/brotli), optimize **images**.
- If asked: Use `loading="lazy"` for images; compress PNG/JPEG; use WebP/AVIF.

66) Server-side performance quick wins?
- **HTTP caching**, **ETag/Last-Modified**, **keep-alive**, **connection pooling**.
- If asked: Return `Cache-Control` headers; enable Gzip/Brotli.

67) Avoid blocking the event loop?
- Move **CPU-heavy** to **workers/queues**, use **async** APIs.
- If asked: Signs: slow responses for all requests. Fix: worker threads or a job queue.

68) Memoization—when?
- Cache **pure** results for **repeat inputs**; watch **memory**.
- If asked: Good for pure functions like `fib(n)`; clear cache when needed.

69) Observability basics?
- Add **metrics**, **logs**, **traces**, **correlation IDs**.
- If asked: Use three signals together to find and fix issues faster.

70) Rate limiting and quotas?
- **Token bucket** or **sliding window** for **protection**/**fair use**.
- If asked: Return 429 when limit is hit; include `Retry-After` header.

71) Feature flags?
- Ship **dark** code, enable via **flags**, support **canary/rollback**.
- If asked: Keep a kill-switch to disable a feature quickly.

72) Idempotency in APIs?
- Use **idempotency keys** so **retries** don’t duplicate **effects**.
- If asked: Client sends a unique key; server stores result for that key.

73) Handling flaky tests?
- **Isolate** side effects, add **retries** sparingly, fix **root causes**.
- If asked: Tag and quarantine flaky tests; fix them soon.

74) Package management tips?
- Use a **lockfile**, **audit** deps, pin **versions**, remove **unused**.
- If asked: Run audits regularly and update only what you need.

75) CDN usage?
- Serve **static** via **CDN** for lower **latency** and **offload**.
- If asked: Put images, JS, CSS on CDN; use cache invalidation on deploy.

### Notes
- Speak slowly; keep sentences short.
- If asked for details, add a tiny example.
16 changes: 15 additions & 1 deletion docs/learning-note/stenography/weekly-fe-perusal/note-p3.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,20 @@ LOD(Level of Detail),数据详细级别。LOD 表达式,在一个查询中
- 抽象是架构设计的难点,不要纠结于完美的抽象
- 总结:业务变化驱动架构不断演变

## 263.精读《我们为何弃用 css-in-js》

<div style={{textAlign: 'right'}}><small style={{color: 'grey'}}>last modified at January 3, 2025 17:02</small></div>
优点:
- 无全局样式冲突,模块化能力
- 和普通 JS 代码一起管理
- 支持 JS 变量

缺点:
- 运行时性能,React 18 的调度机制下,在运行时插入样式会暂停渲染,等解析完样式再继续
- 样式优先级无法自定义,class优先级有 header 定义顺序决定,而非 classname 顺序决定

## 29.精读《JS 中的内存管理》



<div style={{textAlign: 'right'}}><small style={{color: 'grey'}}>last modified at August 13, 2025 17:35</small></div>