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).

Tokens
13.2K
Snippets
64
Records
85
Agent score
75%

What's inside desain7 Frontend Notes

  1. Understand the Same-Origin Policy and Cross-Origin requests

    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.
  2. 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.
  3. 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).
  4. 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.
  5. 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:

    1. Create a curry function that accepts a target function (fn) and returns a new function.
    2. Use a closure to keep track of the arguments collected so far.
    3. Compare the number of collected arguments (args.length) against the original function's expected parameter count (fn.length).
    4. If the number of arguments is sufficient, execute the original function using apply with the collected arguments.
    5. 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));
          };
        }
      };
    }
  6. 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
  7. 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') }
      ]
    })
    
  8. Reuse DOM elements with v-show

    Use v-show instead of v-if when toggling between views that contain heavy components. v-show keeps the element in the DOM and only toggles the CSS display property, 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>
  9. 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 using encodeURIComponent or a library like querystring.
    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 });
  10. Use nextTick to execute code after DOM updates in Vue 3

    In Vue 3, nextTick is 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; nextTick ensures 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
        })
      }
    }