0%

In frontend interviews and daily development, Promise.race is a very common yet often overlooked API. Its rule is simple:

Multiple Promises “race” against each other—whichever settles first (fulfilled or rejected) determines the final result.

In this article, we will:

  • Clearly explain how Promise.race behaves and when to use it
  • Implement a custom myPromiseRace from scratch
  • Cover edge cases, optimizations, and common interview questions

1. What Is Promise.race?

Promise.race(iterable) accepts an iterable (usually an array) and returns a new Promise:

  • If any Promise fulfills first, the returned Promise fulfills
  • If any Promise rejects first, the returned Promise rejects
  • It does not wait for all Promises to finish
  • It does not cancel the remaining Promises—they continue running

2. Common Use Cases

2.1 Timeout Control (Most Common)

For example, treat a request as failed if it takes longer than 3 seconds:

  • fetch(url) vs timeoutPromise(3000)
  • Whichever finishes first determines the result

2.2 Multiple Data Sources (Fallback Strategy)

Fetch the same resource from multiple CDNs (CDN1/CDN2).
Use whichever responds first.

2.3 First-Render Racing

Load primary data, fallback data, and cached data simultaneously.
Render the page as soon as the fastest result arrives.

3. Implementing myPromiseRace

This implementation closely matches native behavior:

  • Validates that the input is iterable
  • Iterates over all inputs
  • Uses Promise.resolve to normalize non-Promise values
  • Resolves or rejects as soon as one Promise settles
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function myPromiseRace(promises) {
return new Promise((resolve, reject) => {
// Validate iterable input
if (!promises || typeof promises[Symbol.iterator] !== 'function') {
return reject(new TypeError('Argument is not iterable'));
}

// Iterate over each Promise or value
for (const promise of promises) {
// Wrap with Promise.resolve to handle thenables and values
Promise.resolve(promise)
.then(resolve) // First fulfilled wins
.catch(reject); // First rejected wins
}
});
}

4. Key Insight: Why Use Promise.resolve?

The input to Promise.race does not have to be Promises. It may include:

  • Plain values: Promise.race([1, 2, 3])
  • Thenables: { then(resolve) { resolve(123) } }

Using Promise.resolve(x) ensures:

  • Plain values become immediately fulfilled Promises
  • Thenables are properly assimilated into the Promise chain

This behavior is consistent with the native Promise.race.

5. Handling Empty Iterables

Native Promise.race([]) returns a Promise that remains pending forever.

Your current implementation behaves the same way, since the loop never executes.
This matches the ECMAScript specification.

You could add explicit handling, but it’s not required.

6. Additional Test Cases

6.1 Rejection Wins First

1
2
3
4
5
6
7
const p1 = new Promise(res => setTimeout(() => res('p1'), 1000));
const p2 = new Promise(res => setTimeout(() => res('p2'), 500));
const p3 = new Promise((res, rej) => setTimeout(() => rej('p3 error'), 300));

myPromiseRace([p1, p2, p3])
.then(console.log)
.catch(console.error); // Output: p3 error

6.2 Plain Values Participate in the Race

1
2
3
4
5
6
7
8
9
myPromiseRace([
Promise.resolve('A'),
123,
new Promise(res => setTimeout(() => res('B'), 10))
])
.then(console.log)
.catch(console.error);

// Output: 123 (plain value wins immediately)

6.3 Empty Array Remains Pending

1
2
3
const p = myPromiseRace([]);
setTimeout(() => console.log('still pending...'), 1000);
// After 1 second: "still pending..."

7. Practical Example: Request Timeout with race

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function timeout(ms) {
return new Promise((_, reject) => {
setTimeout(() => reject(new Error(`Timeout after ${ms}ms`)), ms);
});
}

async function fetchWithTimeout(url, ms = 3000) {
return myPromiseRace([fetch(url), timeout(ms)]);
}

// Usage
fetchWithTimeout('https://example.com/api', 2000)
.then(res => res.json())
.then(data => console.log('data:', data))
.catch(err => console.error('error:', err.message));

8. Common Interview Questions (Bonus Points)

  • Q: Can Promise.race cancel the other Promises?
    No. Promises are not cancellable by default. Cancellation requires tools like AbortController or custom logic.

  • Q: What happens if you pass a plain value into race?
    It is wrapped by Promise.resolve and usually wins immediately.

  • Q: What’s the difference between race, any, and allSettled?

    • race: settles as soon as the first Promise settles
    • any: fulfills as soon as the first Promise fulfills (rejects only if all reject)
    • allSettled: waits for all Promises and returns their final states

9. Summary

The core idea behind implementing Promise.race can be summarized in one sentence:

Iterate over the iterable, wrap each item with Promise.resolve, attach the same resolve and reject, and let the first settled Promise decide the outcome.

In JavaScript, the new operator is a core concept that frequently appears in both interviews and everyday development.
Many developers use new regularly, but few truly understand what actually happens behind the scenes.

In this article, we’ll implement new by hand, breaking down its internal mechanics step by step to help you fully understand how JavaScript objects are created.

1. What Does the new Operator Actually Do?

When we execute the following line of code:

1
const person = new Person('Alice', 25);

JavaScript actually performs four steps internally:

  1. Create a new empty object
  2. Set the object’s prototype to the constructor’s prototype
  3. Execute the constructor and bind this to the new object
  4. If the constructor returns an object, return it; otherwise return the new object

Understanding these four steps is the key to understanding how new works.

2. Why Implement new Manually?

There are three main benefits to handwriting new:

  • Deepens your understanding of the prototype chain and this binding
  • It is a high-frequency frontend interview question
  • Helps you understand how frameworks create objects internally

Let’s jump straight into the code.

3. Handwriting the new Operator

1
2
3
4
5
6
7
8
9
10
11
function myNew(constructor, ...args) {
// 1. Create a new object and link its prototype
const obj = Object.create(constructor.prototype);

// 2. Execute the constructor with `this` bound to the new object
const result = constructor.apply(obj, args);

// 3. If the constructor returns an object, return it
// Otherwise, return the newly created object
return result instanceof Object ? result : obj;
}

This implementation fully reproduces the core behavior of the new operator.

4. Line-by-Line Breakdown

1. The Role of Object.create

1
const obj = Object.create(constructor.prototype);

This is equivalent to:

1
obj.__proto__ === constructor.prototype

Which means:

  • The new object can access methods on the constructor’s prototype
  • The prototype chain is properly established

2. constructor.apply(obj, args)

1
const result = constructor.apply(obj, args);

This step does two things:

  • Executes the constructor function
  • Binds this inside the constructor to the new object

So code like this:

1
2
this.name = name;
this.age = age;

Actually assigns properties directly to obj.

3. Why Do We Check the Return Value?

1
return result instanceof Object ? result : obj;

This is a detail many developers overlook.

Consider this example:

1
2
3
4
5
6
7
function Test() {
this.a = 1;
return { b: 2 };
}

const t = new Test();
console.log(t); // { b: 2 }

If a constructor explicitly returns an object, the new operator returns that object instead of this.

That’s why we must handle this case in our myNew implementation.

5. Testing Our myNew Function

1
2
3
4
5
6
7
8
9
10
function Person(name, age) {
this.name = name;
this.age = age;
}

const p1 = myNew(Person, 'Alice', 25);

console.log(p1.name); // Alice
console.log(p1.age); // 25
console.log(p1 instanceof Person); // true

The behavior matches native new perfectly.

6. Comparing myNew and Native new

Behavior new myNew
Create new object
Bind prototype
Bind this
Handle returned object

In practice, myNew reproduces about 90% of the real new operator’s behavior, which is more than sufficient for interviews and deep understanding.

7. Common Interview Follow-Up Questions

Q1: Why not simply use const obj = {}?

Because objects created with {} have their prototype set to Object.prototype.
Objects created with new must have their prototype set to the constructor’s prototype.

Q2: Can constructor.apply be replaced with call?

Yes. The only difference is how arguments are passed:

1
constructor.call(obj, ...args);

Q3: How does instanceof work?

1
p1 instanceof Person

Internally, JavaScript checks whether:

1
Person.prototype exists in p1’s prototype chain

8. Summary

  • The new operator is not magic—it follows a well-defined execution process
  • Handwriting new is one of the best ways to understand prototype chains, this, and constructors
  • Mastering this concept helps when learning Vue, React, and Node.js internals

If you can both write and explain this implementation,
90% of interviewers will consider your JavaScript fundamentals solid.

JavaScript Basics Summary (Hoisting, Strict Mode)


Rules for Variable and Function Hoisting

  • Variable hoisting: Execution still happens in order; variable declarations are hoisted but assignments are not.
  • Function hoisting: The entire function body is hoisted to the top of its scope.
  • Priority: Function hoisting > Variable hoisting.
1
2
3
4
5
6
7
console.log(a); // undefined
var a = 2;

foo(); // works normally
function foo() {
console.log("Function hoisting succeeded");
}

Using Strict Mode with use strict

What it does:

  • Prevents creating accidental global variables;
  • Disallows using undeclared variables, helping avoid memory leaks;
  • Binds this to undefined by default instead of window.
1
2
3
4
5
6
7
function foo() {
"use strict";
console.log(this.a); // ❌ TypeError
}

var a = 2;
foo(); // in strict mode, this is undefined, so this.a cannot be read

1
2
3
4
5
6
7
8
9
10
(function() {
"use strict";
foo(); // calling foo here doesn't change its default binding
})();

function foo() {
console.log(this.a);
}

var a = 2;

In web development, XSS (Cross-Site Scripting) is one of the most common and most dangerous security vulnerabilities.
Once a website contains an XSS flaw, attackers may execute malicious scripts in users’ browsers, allowing them to steal cookies, hijack sessions, deface pages, or even take over user accounts.

This article explains how to effectively defend against XSS attacks from both a theoretical and practical perspective, covering frontend and full-stack security best practices.

1. What Is an XSS Attack?

The essence of XSS is simple:

An attacker injects malicious JavaScript into a webpage, which is then executed in other users’ browsers.

Common types of XSS attacks include:

  • Reflected XSS: malicious scripts are delivered through URL parameters
  • Stored XSS: malicious scripts are stored in a database and served to users
  • DOM-based XSS: frontend JavaScript logic directly handles untrusted data

No matter the type, the root cause is the same:
👉 User input is treated as executable code.

2. Input Validation and Filtering (The Most Basic Defense)

Never trust user input.

1. Basic Frontend Validation

On the frontend, basic validation can improve user experience, such as:

  • Limiting input length
  • Enforcing input formats (e.g., email, phone numbers)
  • Filtering obviously dangerous characters

Example (for basic validation only):

1
2
3
function sanitizeInput(input) {
return input.replace(/[<>]/g, '');
}

⚠️ Important:
Frontend validation is not a security boundary and should never be relied on alone.

2. Strict Backend Validation (Critical)

Effective input validation must be performed on the server side:

  • Validate data types
  • Enforce length constraints
  • Reject inputs that violate business rules
  • Escape or sanitize HTML content using whitelists

Recommended principles:

  • Deny by default
  • Whitelist over blacklist

3. Output Encoding (More Important Than Input Filtering)

Many XSS vulnerabilities occur not because input is unsafe, but because output is handled incorrectly.

1. HTML Escaping on Output

When rendering user input, always encode HTML characters:

Character Escaped Form
< &lt;
> &gt;
" &quot;
' &#39;

Most modern template engines (Vue, React, Handlebars) escape output by default.
Do not disable this behavior unless absolutely necessary.

2. Avoid Dangerous APIs

Avoid patterns like:

1
element.innerHTML = userInput;

Safer alternatives include:

1
element.textContent = userInput;

Or:

1
2
3
const el = document.createElement('div');
el.textContent = userInput;
container.appendChild(el);

4. Use Safe APIs and Framework Protections

Modern frontend frameworks include built-in XSS protections.

1. Default Protections in React and Vue

  • JSX and template syntax escape output by default
  • Dangerous APIs are explicitly labeled (e.g., v-html, dangerouslySetInnerHTML)

⚠️ If you use these APIs, you must ensure the content is 100% trusted.

2. Avoid String-Based HTML Construction

❌ Unsafe example:

1
container.innerHTML = `<div>${userInput}</div>`;

✅ Safe alternative:

1
2
3
const div = document.createElement('div');
div.textContent = userInput;
container.appendChild(div);

5. Use Content Security Policy (CSP)

Content Security Policy (CSP) is one of the most powerful defenses against XSS.

1. What CSP Can Do

  • Block inline script execution
  • Restrict allowed script sources
  • Prevent loading malicious third-party resources

Example HTTP header:

1
2
3
4
Content-Security-Policy:
default-src 'self';
script-src 'self';
object-src 'none';

Even if an attacker injects a script, CSP can prevent the browser from executing it.

2. Why CSP Is So Important

Because it provides:

  • Browser-level protection
  • A strong fallback even when application code has flaws

6. Use HttpOnly and Secure Cookies

1. Purpose of HttpOnly

When setting cookies, add the HttpOnly flag:

1
Set-Cookie: sessionId=xxx; HttpOnly;

This prevents JavaScript from accessing cookies, reducing the impact of XSS attacks.

2. Combine with Secure and SameSite

For stronger protection, also use:

  • Secure
  • SameSite=Strict or Lax

This significantly improves session security.

7. Keep Third-Party Libraries Up to Date

In real-world projects, many XSS vulnerabilities come from third-party dependencies:

  • Outdated UI components
  • Unmaintained plugins
  • Vulnerable npm packages

Best practices:

  • Update dependencies regularly
  • Use npm audit
  • Monitor security advisories

8. Develop Secure Coding Habits

Preventing XSS is not about a single technique, but about consistent habits:

  • Never trust external input
  • Avoid innerHTML unless necessary
  • Do not ignore security warnings
  • Prioritize security over convenience

9. Summary

  • XSS is one of the most common and dangerous web security threats
  • Effective protection requires frontend, backend, and browser-level defenses
  • Input validation is only the beginning—safe output handling and CSP are critical
  • Good security habits are more valuable than any single patch

For frontend developers,
understanding how to prevent XSS is a key step toward true professionalism.


What Is Serialization

Data transmitted over a TCP channel can only be in binary form. So converting a data structure or an object into binary form is called serialization. The reverse process is called deserialization. The rules that define how they convert back and forth are called a protocol.


What Is RPC

RPC stands for Remote Procedure Call. Most RPC systems are based on TCP. The general implementation flow is as follows:

  1. The frontend calls the corresponding interface through a Proxy. The Proxy converts information such as the RPC service name, method name, and parameters into an RPC Request object and passes it to the RPC framework.
  2. The RPC framework serializes the RPC Request object into binary form according to the RPC protocol.
  3. The RPC framework sends the binary data to the backend through a TCP channel.
  4. The backend deserializes the binary data back into an RPC Request object.
  5. The backend maps the deserialized data to the actual method it implements, passes in the parameters, obtains the result, and then packages it into an RPC Response object for the RPC framework.
  6. The RPC framework serializes the RPC Response object into binary form according to the RPC protocol and sends it back to the frontend through the TCP channel.
  7. After receiving the binary data, the frontend deserializes it into an RPC Response object, and the Proxy returns the result to the business code.

Notes on Encountering the Unknown Self

What is the “Unknown”?

The “self” refers to the “true self.” From the question “Who am I?” to the concept of “from existence to non-existence,” the entire book is structured around dialogues between Ruoling and a wise elder, revealing many profound life concepts.


Core Concepts

  • There is no one outside—only yourself.
    All external situations are actually projections of your inner world.

  • Golden Moments to Talk with the Subconscious
    The best times to imagine you’ve already achieved your goals are the moments between waking and sleeping—early morning just before fully waking up, or late at night before falling asleep. These times are when we are closest to our subconscious.

  • Key Practices: Awareness, Surrender, Overcoming the Peptide Self (Ego)

    • Awareness: Focus on your present self. Observe your emotions and reactions without judgment.
    • Surrender: Accept reality instead of resisting it.
    • Peptide Self (Ego): Represents inner voices of fear, comparison, and anxiety. Learn to recognize and transcend them.
  • Meditation, Gratitude, Giving

    • During meditation, visualize yourself already living your desired life.
    • Be grateful even before your goals are achieved.
    • Maintain a selfless, giving mindset.
  • Care Less About Others, Care More About Yourself

    • Bring your attention back to yourself and your inner world.
    • When emotions arise, be aware of which part of your body feels uncomfortable and understand its message.

Conclusion

This book is not only about discovering “who you are,” but also about reminding you to “become that true self.” Awakening inner strength requires continuous awareness, practice, and transcending the ego.

What I Talk About When I Talk About Running

It was through this book that I realized there could be another version of myself out there, doing something I love. Before reading this book, I had never read anything by Murakami. I knew he was popular and had many famous books, but I hadn’t really paid attention. But when it comes to running, I felt there could be a connection.

If I keep running, will I eventually reach the moon? Running isn’t about living longer, but about making life feel easier and lighter within the time we have.

I was surprised by Murakami’s imagination while running—so free and boundless. I really enjoy that. I’ve imagined many things too, like suddenly recalling a lyric while running—something like “speeding up to chase happiness,” blabla… Long-distance running requires endurance, but also imagination. Of course, the premise is loving to run. If someone doesn’t like running, no matter how much you say, it won’t matter. But if someone does love it, they’ll even want to meet another version of themselves during a break in the rain. Humans are inherently lonely, but the spirit can resonate with others.

I plan to keep running no matter how the world changes. Once, I walked 30 kilometers in one day. Despite the sunburn, I loved the spiritual fulfillment more. If you haven’t experienced it, you have no voice. Maybe I’m like Chen Kun—a pessimistic optimist. I live actively in this world, but I also see through its illusions. Neither joyful because of things, nor sorrowful because of myself.

My pulse has dropped to just over 50 beats per minute. Seems like I’m built for jogging. After all, it’s about interest. As long as my freedom isn’t restricted, anything is acceptable.

I hope next year I’ll join a marathon, with people cheering me on. That would be so happy.

“I’m not a person, but a pure machine. So I don’t need to feel anything, just keep running forward.”

What’s most similar is that we both love to run non-stop. Not the type who walks when tired or stops to enjoy the scenery. Maybe people have different views, but I think the true king is the one who can keep running without stopping.

When reaching the finish line, I’d feel so cool, a rush of pride, like winning the lottery or getting incredibly lucky. It’s a principle—and also my pride.

Oh, right—just like Brother Shang waiting at the finish line, and I’d smile proudly.

Aunt Tai

Aunt Tai is strong-willed and resilient. Her optimistic attitude is something worth learning from. The greatest thing my father ever did was marrying my mother—a truly great woman. A real woman should face everything with positivity and build the future she desires with her own hands.

Although she resorted to stealing, it was driven by hardship—survival and family. Setting aside pride to do things against her will is, in a way, a form of strength. It’s not about crying and making a scene, but staying proactive in adversity.

Thinking about it, the author’s achievements are inseparable from his great mother.

Ah, that lovely mother! To preserve her husband’s dignity and happiness, she insisted on completing the house. Isn’t that a form of strength too? To follow her heart courageously is truly admirable.

In fact, the person who understands my father the most is my mother. She knows his pride. Isn’t this what love is? You don’t need to say it—I understand. I understand you, and you understand me, and that’s why we’ve been together for so long.

Zhang Meili

Get up from where you fell. Zhang Meili seems like someone who pursued true love and worked hard for what she desired. Though she was eventually forced to liberate herself sexually, I still respect her for everything she once did.

Public opinion is powerful, but Zhang Meili’s inner strength is even more powerful.

The book does contain a lot of his own “biases,” but I find him authentic and humorous. His language is simple and understandable, and each subtitle essentially tells us what we should do.

Understanding Life

Life is never about what you want it to be. It’s good to discover beauty and to view things from others’ perspectives. At the same time, one should have self-awareness.

Understanding Love

Sheldon once said: “The pursuit of another human to spend life with is something I’ve never understood. Maybe I’m too interesting to need company. So I wish you the same joy with each other as I have with myself.”
One can never escape loneliness through another person; only through passion for life. Managing a relationship requires rationality. Freedom is inalienable. I once checked my ex’s phone—I realized it was wrong and won’t do it again.

Understanding Strategy

This section mainly introduces the strategies of courting and how to maintain a good relationship—true wisdom. Never sacrifice your career for family. Don’t live with in-laws (though I think it depends). Have your own hobbies.

Understanding Marriage

Endure and stay loyal. As for non-marriage beliefs, there’s nothing more to say.

Understanding Setbacks

Every breakup is just making way for true love. Don’t force it. I love you, so I wish you well, even if I’m not the one by your side.
Do what you want regardless of others’ opinions. Only care about those who matter to you.

Understanding Reading

What, Why, How. Keep reading. Don’t chase speed, but depth.

Understanding Romance

He shares sweet daily stories with his wife. If you don’t break up, you won’t discover how many better people there are out there. If you find one—lucky. If not—you can still live happily on your own.
Live with emotional intelligence and the world becomes beautiful.

Understanding Socializing

Associate with decent people. Different people require different approaches. Rejecting others is an art. If you don’t have the guts to ask for your money back, don’t lend it.

Understanding Human Nature

I tend to be skeptical about human nature. You can’t control others, so just manage yourself. Don’t be vulgar.

Understanding Good and Evil

Some people enter your life just to teach you a lesson. Good or evil—I prefer believing in others, as trust is given before it’s earned.
Even if deceived, it’s a lesson learned—don’t fall into the same trap again. But don’t stop trusting altogether; kind people still exist.
God made the right hand a right hand as a reward; same for kind people—kindness is its own reward.
I recall being in a restroom without tissue once. I was going to ask a friend, but a stranger overheard and handed me tissues. Such kindness moved me deeply.
Kindness must come with principles—otherwise it may hurt others or yourself.

Understanding Wealth

The poor stay poor because of narrow thinking. To get rich, don’t just invest in your body—think bigger. See the essence of problems.
Time is limited—how to get rich fast? Find a subject you love, apply it, think broadly, and work in fields closely tied to society.

Understanding Society

Have ambition. Take one step at a time. Build an independent personality. Be accountable for your actions. Learn to transform your ability to feel happiness—then change yourself.

Understanding Life and Death

Death studies include concepts like: No death, no life; face death to live; understand death to be reborn. Interesting and thought-provoking.
Knowing that we will die is what pushes us to live fully. When the time comes, I think I’ll embrace death.

What the world lacks isn’t perfect people, but justice, sincerity, courage, and compassion from the heart. — My biggest takeaway after watching Forever Young today.
We all know cause and effect—but causes and effects come from relationships. Someday, I’ll read Schopenhauer and Nietzsche properly.

Understanding Travel

This part recounts Mr. Zhuomo’s experiences in Tibet. Many dream of going there—maybe because it helps people truly understand life’s struggles.
The US is less disciplined than the UK. Japan has great food culture and says “sorry” a lot—avoiding bothering others.

Understanding Career

First learn to endure hardship. Then understand yourself and your talents. Begin with the end in mind and stay focused.

Understanding Education

Every child is born pure. Without proper education, they won’t become pillars of the nation.

Understanding Entertainment & Freedom

Life has two paths: one for career ambition—keep passion; the other for living warmly—keep humanity.
Open your eyes each day and tell yourself: Oh yeah!

Differences between var, let, and const?

✅ Scope

  1. Variables declared with var do not have block scope. They can be accessed outside blocks but not outside functions.
  2. Variables declared with let have block scope, accessible only within the declared block.
  3. const defines constants, must be initialized, accessible only in the declared block, and cannot be reassigned.

✅ Declaration Rules

  • A variable name can only be declared once using one of these methods; otherwise, it throws an error.

✅ Difference when using with this

Feature var / let / const
Can change this context ✅ Yes
First parameter is the object this refers to ✅ Yes
No object or undefined/null Defaults to global window
Parameter passing apply uses array, call uses parameter list, bind supports multiple arguments
Execution method apply/call execute immediately, bind returns a new function
What is event delegation?
  • Event delegation attaches events to a parent or ancestor element instead of individual child elements.
  • When the event reaches the target element, it bubbles up and triggers the handler on the outer element.
Difference between debounce and throttle?
  • Debounce: Executes only the last trigger. Even if the event keeps firing, it waits until n seconds after the last event to execute.
  • Throttle: Controls the execution frequency. Fires every n seconds during continuous event triggers.
How does frontend prevent SQL injection?
  1. Parameterized Queries: Use prepared statements or parameterized queries.
  2. Input Validation: Ensure user input follows expected format.
  3. Escape Special Characters: Escape characters when constructing SQL queries.
  4. Limit Permissions: Restrict user privileges to prevent unsafe operations.
  5. Whitelist Validation: Only allow expected values in input.
  6. Code Review: Regularly review code, especially DB-related parts.
Difference between HTTP and HTTPS
  1. HTTPS requires a certificate from a CA, which may cost money.
  2. HTTP transmits data in plaintext, while HTTPS uses SSL encryption.
  3. They use different connection methods and ports: HTTP uses 80, HTTPS uses 443.
  4. HTTP is stateless; HTTPS combines SSL + HTTP for encrypted, authenticated, secure communication.
Difference between created and mounted?
  • created runs before mounted. DOM is not fully rendered, but API requests can be made early here.
  • mounted is triggered when the DOM has been rendered, so it’s suitable for manipulating DOM elements.
Explain the event loop mechanism

🔁 What is the Event Loop?

JavaScript is single-threaded. In addition to the call stack, it relies on task queues to control asynchronous code execution order.

This whole process is called the Event Loop.

🧠 Core Concepts

  • Only one event loop in a single thread.
  • Multiple task queues:
    • Macro Tasks
    • Micro Tasks

⏱ Execution Order

Macro Task ➝ Clear all Micro Tasks ➝ Next Macro Task ➝ Clear all Micro Tasks…

  1. Execute a macro task (like the whole script)
  2. Execute all micro tasks created during this macro task
  3. If micro tasks generate more micro tasks, execute them too
  4. Begin the next macro task loop

🧩 Examples of Macro Tasks

  • script
  • setTimeout
  • setInterval
  • setImmediate (Node.js)
  • I/O operations
  • UI rendering

🧬 Examples of Micro Tasks

  • process.nextTick (Node.js, higher priority)
  • Promise.then / catch / finally
  • async / await
  • MutationObserver
Explain the CSS box model

The CSS box model includes IE and standard W3C models.

  • In standard W3C box model, width only includes content. box-sizing: content-box (default).
  • In IE box model, width includes content + padding + border. box-sizing: border-box.
  • box-sizing: padding-box includes left/right padding + width.
Differences between Vue 2 and Vue 3
  1. Two-way binding:
    • Vue 2: uses Object.defineProperty() (ES5), which only watches individual properties.
    • Vue 3: uses Proxy (ES6), which can observe entire objects and arrays.
  2. Lifecycle hooks:
    • Vue 2: beforeCreate, created, beforeMount, mounted, etc.
    • Vue 3: setup, onBeforeMount, onMounted, etc.
  3. Vue 2 requires a root tag; Vue 3 allows multiple root tags via Fragment.
  4. API:
    • Vue 2: Options API (functions and data handled separately).
    • Vue 3: Composition API (related code grouped together).
  5. Slots:
    • Named slot: Vue 2 uses slot="", Vue 3 uses v-slot="".
    • Scoped slot: Vue 2 uses slot-scope="data", Vue 3 uses #data or #default="{data}".