diff --git a/blog/2025-08-13-interview-tips-2025-8.md b/blog/2025-08-13-interview-tips-2025-8.md new file mode 100644 index 0000000..8bde991 --- /dev/null +++ b/blog/2025-08-13-interview-tips-2025-8.md @@ -0,0 +1,323 @@ +--- +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). + +- 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 `
`. + +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. \ No newline at end of file diff --git a/docs/learning-note/stenography/weekly-fe-perusal/note-p3.md b/docs/learning-note/stenography/weekly-fe-perusal/note-p3.md index 95c40e1..a71590b 100644 --- a/docs/learning-note/stenography/weekly-fe-perusal/note-p3.md +++ b/docs/learning-note/stenography/weekly-fe-perusal/note-p3.md @@ -173,6 +173,20 @@ LOD(Level of Detail),数据详细级别。LOD 表达式,在一个查询中 - 抽象是架构设计的难点,不要纠结于完美的抽象 - 总结:业务变化驱动架构不断演变 +## 263.精读《我们为何弃用 css-in-js》 -