desain7 Frontend Interview and Coding Notes
website·Indexed 30 days ago
https://desain7.github.io/A collection of frontend development study notes covering Vue.js (performance optimization, reactivity, ref vs reactive, $nextTick), JavaScript coding challenges (deep/shallow copy, currying, publish-subscribe pattern), and network protocols (HTTP versions, TCP/UDP, WebSocket, CORS).
What's inside desain7 Frontend Notes
- A cross-origin request occurs when a web page requests resources from a different domain, protocol, or port. This is restricted by the Same-Origin Policy (SOP), a security measure implemented by browsers to prevent malicious sites from accessing sensitive user information. If the same-origin requirement is not met, the following are restricted: 1. Sharing of Cookies, LocalStorage, and IndexedDB; 2. Accessing the DOM; 3. Sending AJAX requests.
Understand WebSocket protocol characteristics
WebSocket is an application-layer protocol providing full-duplex communication between a browser and a server over a single TCP connection. Unlike the traditional HTTP request-response model, it allows both the server and client to push messages independently. Key characteristics include:
- Full-Duplex Communication: Simultaneous bidirectional data transfer.
- Persistent Connection: Connection remains open after the initial handshake until explicitly closed, reducing overhead.
- Low Latency: Eliminates the need for repeated HTTP headers and handshakes for every message.
- Cross-Origin Support: Supports communication across different domains.
- Security: Supports encrypted connections via the
wss://(WebSocket Secure) scheme.
Understand Vue's reactivity principle
Reactivity in Vue allows developers to bind data to views declaratively. When data changes, Vue automatically tracks these changes and updates the corresponding parts of the view to keep the data and UI in sync. In general terms, reactivity means that when a piece of data changes, all parts of the application that depend on that data will respond to the change (typically by re-executing a function or method).Understand Shallow Copying in JavaScript
A shallow copy creates a new object and copies the property values of the original object. For primitive data types, the actual value is copied. For reference data types (objects, arrays), only the memory address (reference) is copied. Consequently, if a nested reference type property is modified in one object, the change will be reflected in the other object because they both point to the same memory location.Implement function currying in JavaScript
Function currying is implemented using closures and recursion. The goal is to transform a function that takes multiple arguments into a sequence of functions. The implementation follows these steps:
- Create a
curryfunction that accepts a target function (fn) and returns a new function. - Use a closure to keep track of the arguments collected so far.
- Compare the number of collected arguments (
args.length) against the original function's expected parameter count (fn.length). - If the number of arguments is sufficient, execute the original function using
applywith the collected arguments. - If the arguments are insufficient, return a new function that collects more arguments and recursively calls the curried function, merging the previous arguments with the new ones.
// Function currying is typically implemented via closures and recursion function curry(fn) { // Return the curried version of the function return function curried(...args) { // If the number of arguments is greater than or equal to the original function's length, execute it if (args.length >= fn.length) { return fn.apply(this, args); } else { // Otherwise, return a new function to continue collecting arguments return function (...newArgs) { // Merge existing arguments with new arguments and recurse return curried.apply(this, args.concat(newArgs)); }; } }; }- Create a
Import third-party UI libraries on-demand
To reduce the final bundle size, avoid importing entire UI libraries (like Element Plus or Ant Design). Instead, import only the specific components you need and register them individually.import { createApp } from 'vue'; import { Button, Select } from 'element-plus'; const app = createApp() app.use(Button) app.use(Select)Choose between TCP and UDP based on application needs
Select the protocol based on the priority of accuracy versus efficiency:
Use TCP when accuracy is critical and efficiency is secondary:
- File transfers (FTP)
- Email (SMTP/IMAP)
- Remote login (SSH)
- Web applications (HTTP/HTTPS)
Use UDP when real-time efficiency is critical and minor data loss is acceptable:
- Instant messaging (e.g., QQ chat)
- Live streaming
- Online gaming
- Broadcast communications
Implement route lazy loading in Vue
Use dynamic imports to defer the loading of route components until they are needed. This reduces the initial bundle size and load time by splitting the application into smaller code chunks.const router = createRouter({ routes: [ // Use dynamic import() to implement async components { path: '/foo', component: () => import('./Foo.vue') } ] })Reuse DOM elements with v-show
Usev-showinstead ofv-ifwhen toggling between views that contain heavy components.v-showkeeps the element in the DOM and only toggles the CSSdisplayproperty, avoiding the overhead of repeatedly destroying and recreating expensive components.<template> <div class="cell"> <!-- Use v-show to reuse DOM for heavy components --> <div v-show="value" class="on"> <Heavy :n="10000"/> </div> <section v-show="!value" class="off"> <Heavy :n="10000"/> </section> </div> </template>Transmit data using URL Parameters (Path Parameters)
URL parameters are data embedded directly within the URL path. These are typically handled by server-side frameworks or single-page application (SPA) routers to extract specific resource identifiers.http://baidu.com/person/abc// 'abc' is the url param
Transmit data using URL Query Strings
Query strings transmit data by appending a string to the URL after a?character, with key-value pairs separated by&. Non-English or special characters must be encoded usingencodeURIComponentor a library likequerystring.http://baidu.com/person?name=abc&age=20// Using native API const query = "?name=" + encodeURIComponent('abc') + "&age=" + encodeURIComponent(20); // Using querystring library const query = querystring.stringify({ name: 'abc', age: 20 });Use nextTick to execute code after DOM updates in Vue 3
In Vue 3,
nextTickis a global method used to defer a callback function to run after the next DOM update cycle has completed. This is essential because Vue performs DOM updates asynchronously;nextTickensures that the callback is executed only after the DOM has been synchronized with the latest data changes.Common Use Cases:
- Post-update DOM manipulation: Performing operations on an element that only exists or has changed after the render cycle.
- Data retrieval after update: Fetching values from the DOM (e.g., element dimensions or input values) that depend on the most recent state update.
// Inside a Vue component method methods: { exampleMethod() { // 1. Modify data this.message = 'Updated Message' // 2. Defer execution until the next DOM update cycle this.$nextTick(() => { // This code runs after the DOM is updated const updatedElement = document.getElementById('my-element') // Perform operations on the updated element }) } }