[
  {
    "path": ".github/workflows/gen-toc.yml",
    "content": "name: Generate table of contents\n\non:\n  pull_request:\n  push:\n    branches:\n      - main\n\njobs:\n  gen-toc:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v3\n        with:\n          ref: ${{ github.head_ref }}\n      - name: Install pnpm\n        uses: pnpm/action-setup@v2\n      - name: Install dependencies\n        run: pnpm install\n      - name: Generate table of contents\n        run: npm run gen\n      - name: 'Commit changes if required'\n        run: |\n          if ! git diff --quiet README.md; then\n            git config user.email \"github-actions[bot]@users.noreply.github.com\"\n            git config user.name \"GitHub Actions\"\n            git add README.md\n            git commit -m \"[auto] regenerate table of contents\"\n            git push\n            echo \"[info] Table of contents updated and committed.\"\n          else\n            echo \"[info] No changes to table of contents.\"\n          fi\n        working-directory: ${{ github.workspace }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n.pnpm-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# Snowpack dependency directory (https://snowpack.dev/)\nweb_modules/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional stylelint cache\n.stylelintcache\n\n# Microbundle cache\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variable files\n.env\n.env.development.local\n.env.test.local\n.env.production.local\n.env.local\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n.parcel-cache\n\n# Next.js build output\n.next\nout\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and not Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# vuepress v2.x temp and cache directory\n.temp\n.cache\n\n# Docusaurus cache and generated files\n.docusaurus\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n# DynamoDB Local files\n.dynamodb/\n\n# TernJS port file\n.tern-port\n\n# Stores VSCode versions used for testing VSCode extensions\n.vscode-test\n\n# yarn v2\n.yarn/cache\n.yarn/unplugged\n.yarn/build-state.yml\n.yarn/install-state.gz\n.pnp.*\n\n# Translations\n.langnostic\n"
  },
  {
    "path": ".prettierignore",
    "content": "README.md\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"bracketSameLine\": true,\n  \"printWidth\": 80,\n  \"proseWrap\": \"never\",\n  \"singleQuote\": true,\n  \"trailingComma\": \"all\"\n}\n"
  },
  {
    "path": "README.md",
    "content": "# Top JavaScript Interview Questions (Updated for 2025)\n\n**Updated for 2025!** This repository contains a few hundred curated JavaScript interview questions with high quality answers for acing your Front End Engineer interviews, brought to you by [GreatFrontEnd](https://www.greatfrontend.com/?utm_source=github&utm_medium=referral&utm_campaign=top-reactjs-qns&gnrs=yangshun).\n\nThe questions are divided into two sections:\n\n1. [**Top questions**](#table-of-contents-top-questions): List of the most important JavaScript interview questions that are commonly-asked during Front End Developer interviews. This README displays the concise version of the answers and links are provided to the full version of answers for further learning. If you are are short on time, start with this section.\n2. [**All questions**](#table-of-contents-all-questions): Comprehensive and elaborate list of JavaScript interview questions that ranges from basic to advanced topics. The answers in this section are more concise. This section is useful if you rusty with JavaScript concepts and need a refresher.\n3. [**Questions by difficulty**](#questions-by-difficulty): Questions categorized by difficulty – basic, intermediate, advanced.\n\n---\n\n<div>\n  <p align=\"center\">\n    <a href=\"https://www.greatfrontend.com/questions/javascript-interview-questions?utm_source=github&utm_medium=referral&utm_campaign=top-js-qns&gnrs=yangshun\">\n      <img src=\"./images/greatfrontend-js-banner4x.png\" alt=\"GreatFrontEnd JavaScript Interview Questions\" width=\"100%\">\n    </a>\n  </p>\n</div>\n\n> Black Friday 2025 sale going on now, enjoy the largest discount of the year! [Get 30% off GreatFrontEnd Premium →](https://www.greatfrontend.com/questions/javascript-interview-questions?utm_source=github&utm_medium=referral&utm_campaign=top-js-qns&gnrs=yangshun) 💡\n\n---\n\n## Table of Contents (Top Questions)\n\nThis list contains the top essential questions that are frequently-asked during Front End Engineer interviews. Concise versions of the answers are presented here with links to elaborate versions for further reading. This section is great if you need a quick refresher of the most important concepts.\n\n<!-- TABLE_OF_CONTENTS:TOP:START -->\n\n| No. | Questions | Level |\n| --- | :-- | :-- |\n| 1 | [Explain the concept of \"hoisting\" in JavaScript](#explain-the-concept-of-hoisting-in-javascript) | Basic |\n| 2 | [What are the differences between JavaScript variables created using `let`, `var` or `const`?](#what-are-the-differences-between-javascript-variables-created-using-let-var-or-const) | Basic |\n| 3 | [What is the difference between `==` and `===` in JavaScript?](#what-is-the-difference-between--and--in-javascript) | Basic |\n| 4 | [What is the event loop in JavaScript runtimes?](#what-is-the-event-loop-in-javascript-runtimes) | Basic |\n| 5 | [Explain event delegation in JavaScript](#explain-event-delegation-in-javascript) | Basic |\n| 6 | [Explain how `this` works in JavaScript](#explain-how-this-works-in-javascript) | Basic |\n| 7 | [Describe the difference between a cookie, `sessionStorage` and `localStorage` in browsers](#describe-the-difference-between-a-cookie-sessionstorage-and-localstorage-in-browsers) | Basic |\n| 8 | [Describe the difference between `<script>`, `<script async>` and `<script defer>`](#describe-the-difference-between-script-script-async-and-script-defer) | Basic |\n| 9 | [What's the difference between a JavaScript variable that is: `null`, `undefined` or undeclared?](#whats-the-difference-between-a-javascript-variable-that-is-null-undefined-or-undeclared) | Basic |\n| 10 | [What's the difference between `.call` and `.apply` in JavaScript?](#whats-the-difference-between-call-and-apply-in-javascript) | Basic |\n| 11 | [Explain `Function.prototype.bind` in JavaScript](#explain-functionprototypebind-in-javascript) | Basic |\n| 12 | [What advantage is there for using the JavaScript arrow syntax for a method in a constructor?](#what-advantage-is-there-for-using-the-javascript-arrow-syntax-for-a-method-in-a-constructor) | Basic |\n| 13 | [Explain how prototypal inheritance works in JavaScript](#explain-how-prototypal-inheritance-works-in-javascript) | Basic |\n| 14 | [Difference between: `function Person(){}`, `const person = Person()`, and `const person = new Person()` in JavaScript?](#difference-between-function-person-const-person--person-and-const-person--new-person-in-javascript) | Basic |\n| 15 | [Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}` in JavaScript](#explain-the-differences-on-the-usage-of-foo-between-function-foo--and-var-foo--function--in-javascript) | Basic |\n| 16 | [What's a typical use case for anonymous functions in JavaScript?](#whats-a-typical-use-case-for-anonymous-functions-in-javascript) | Intermediate |\n| 17 | [What are the various ways to create objects in JavaScript?](#what-are-the-various-ways-to-create-objects-in-javascript) | Basic |\n| 18 | [What is a closure in JavaScript, and how/why would you use one?](#what-is-a-closure-in-javascript-and-howwhy-would-you-use-one) | Intermediate |\n| 19 | [What is the definition of a higher-order function in JavaScript?](#what-is-the-definition-of-a-higher-order-function-in-javascript) | Basic |\n| 20 | [What are the differences between JavaScript ES2015 classes and ES5 function constructors?](#what-are-the-differences-between-javascript-es2015-classes-and-es5-function-constructors) | Basic |\n| 21 | [Describe event bubbling in JavaScript and browsers](#describe-event-bubbling-in-javascript-and-browsers) | Basic |\n| 22 | [Describe event capturing in JavaScript and browsers](#describe-event-capturing-in-javascript-and-browsers) | Basic |\n| 23 | [What is the difference between `mouseenter` and `mouseover` event in JavaScript and browsers?](#what-is-the-difference-between-mouseenter-and-mouseover-event-in-javascript-and-browsers) | Basic |\n| 24 | [What is `'use strict';` in JavaScript for?](#what-is-use-strict-in-javascript-for) | Advanced |\n| 25 | [Explain the difference between synchronous and asynchronous functions in JavaScript](#explain-the-difference-between-synchronous-and-asynchronous-functions-in-javascript) | Basic |\n| 26 | [What are the pros and cons of using Promises instead of callbacks in JavaScript?](#what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks-in-javascript) | Intermediate |\n| 27 | [Explain AJAX in as much detail as possible](#explain-ajax-in-as-much-detail-as-possible) | Basic |\n| 28 | [What are the advantages and disadvantages of using AJAX?](#what-are-the-advantages-and-disadvantages-of-using-ajax) | Basic |\n| 29 | [What are the differences between `XMLHttpRequest` and `fetch()` in JavaScript and browsers?](#what-are-the-differences-between-xmlhttprequest-and-fetch-in-javascript-and-browsers) | Basic |\n| 30 | [How do you abort a web request using `AbortController` in JavaScript?](#how-do-you-abort-a-web-request-using-abortcontroller-in-javascript) | Intermediate |\n| 31 | [What are JavaScript polyfills for?](#what-are-javascript-polyfills-for) | Advanced |\n| 32 | [Why is extending built-in JavaScript objects not a good idea?](#why-is-extending-built-in-javascript-objects-not-a-good-idea) | Intermediate |\n| 33 | [Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?](#why-is-it-in-general-a-good-idea-to-leave-the-global-javascript-scope-of-a-website-as-is-and-never-touch-it) | Intermediate |\n| 34 | [Explain the differences between CommonJS modules and ES modules in JavaScript](#explain-the-differences-between-commonjs-modules-and-es-modules-in-javascript) | Intermediate |\n| 35 | [What are the various data types in JavaScript?](#what-are-the-various-data-types-in-javascript) | Basic |\n| 36 | [What language constructs do you use for iterating over object properties and array items in JavaScript?](#what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items-in-javascript) | Basic |\n| 37 | [What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?](#what-are-the-benefits-of-using-spread-syntax-in-javascript-and-how-is-it-different-from-rest-syntax) | Basic |\n| 38 | [What are iterators and generators in JavaScript and what are they used for?](#what-are-iterators-and-generators-in-javascript-and-what-are-they-used-for) | Advanced |\n| 39 | [Explain the difference between mutable and immutable objects in JavaScript](#explain-the-difference-between-mutable-and-immutable-objects-in-javascript) | Intermediate |\n| 40 | [What is the difference between a `Map` object and a plain object in JavaScript?](#what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript) | Basic |\n| 41 | [What are the differences between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript?](#what-are-the-differences-between-mapset-and-weakmapweakset-in-javascript) | Basic |\n| 42 | [Why might you want to create static class members in JavaScript?](#why-might-you-want-to-create-static-class-members-in-javascript) | Intermediate |\n| 43 | [What are `Symbol`s used for in JavaScript?](#what-are-symbols-used-for-in-javascript) | Intermediate |\n| 44 | [What are server-sent events?](#what-are-server-sent-events) | Advanced |\n| 45 | [What are JavaScript object property flags and descriptors?](#what-are-javascript-object-property-flags-and-descriptors) | Advanced |\n| 46 | [What are JavaScript object getters and setters for?](#what-are-javascript-object-getters-and-setters-for) | Intermediate |\n| 47 | [What are proxies in JavaScript used for?](#what-are-proxies-in-javascript-used-for) | Advanced |\n| 48 | [What tools and techniques do you use for debugging JavaScript code?](#what-tools-and-techniques-do-you-use-for-debugging-javascript-code) | Intermediate |\n| 49 | [What are workers in JavaScript used for?](#what-are-workers-in-javascript-used-for) | Advanced |\n| 50 | [How does JavaScript garbage collection work?](#how-does-javascript-garbage-collection-work) | Advanced |\n\n<!-- TABLE_OF_CONTENTS:TOP:END -->\n\n## Table of Contents (All Questions)\n\nThis list contains a longer list of important JavaScript questions. Not all of them will be asked during Front End Engineer interviews but they provide a well-rounded review of JavaScript concepts ranging from beginner to advanced topics.\n\n<!-- TABLE_OF_CONTENTS:ALL:START -->\n\n| No. | Questions | Level |\n| --- | :-- | :-- |\n| 1 | [What are the various data types in JavaScript?](#what-are-the-various-data-types-in-javascript) | Basic |\n| 2 | [How do you check the data type of a variable?](#how-do-you-check-the-data-type-of-a-variable) | Basic |\n| 3 | [What's the difference between a JavaScript variable that is: `null`, `undefined` or undeclared?](#whats-the-difference-between-a-javascript-variable-that-is-null-undefined-or-undeclared) | Basic |\n| 4 | [What are the differences between JavaScript variables created using `let`, `var` or `const`?](#what-are-the-differences-between-javascript-variables-created-using-let-var-or-const) | Basic |\n| 5 | [Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?](#why-is-it-in-general-a-good-idea-to-leave-the-global-javascript-scope-of-a-website-as-is-and-never-touch-it) | Intermediate |\n| 6 | [How do you convert a string to a number in JavaScript?](#how-do-you-convert-a-string-to-a-number-in-javascript) | Basic |\n| 7 | [What are template literals and how are they used?](#what-are-template-literals-and-how-are-they-used) | Basic |\n| 8 | [Explain the concept of tagged templates](#explain-the-concept-of-tagged-templates) | Intermediate |\n| 9 | [What is the spread operator and how is it used?](#what-is-the-spread-operator-and-how-is-it-used) | Basic |\n| 10 | [What are `Symbol`s used for in JavaScript?](#what-are-symbols-used-for-in-javascript) | Intermediate |\n| 11 | [What are proxies in JavaScript used for?](#what-are-proxies-in-javascript-used-for) | Advanced |\n| 12 | [Explain the concept of \"hoisting\" in JavaScript](#explain-the-concept-of-hoisting-in-javascript) | Basic |\n| 13 | [Explain the difference in hoisting between `var`, `let`, and `const`](#explain-the-difference-in-hoisting-between-var-let-and-const) | Basic |\n| 14 | [How does hoisting affect function declarations and expressions?](#how-does-hoisting-affect-function-declarations-and-expressions) | Advanced |\n| 15 | [What are the potential issues caused by hoisting?](#what-are-the-potential-issues-caused-by-hoisting) | Intermediate |\n| 16 | [How can you avoid problems related to hoisting?](#how-can-you-avoid-problems-related-to-hoisting) | Basic |\n| 17 | [What is the difference between `==` and `===` in JavaScript?](#what-is-the-difference-between--and--in-javascript) | Basic |\n| 18 | [What language constructs do you use for iterating over object properties and array items in JavaScript?](#what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items-in-javascript) | Basic |\n| 19 | [What is the purpose of the `break` and `continue` statements?](#what-is-the-purpose-of-the-break-and-continue-statements) | Basic |\n| 20 | [What is the ternary operator and how is it used?](#what-is-the-ternary-operator-and-how-is-it-used) | Basic |\n| 21 | [How do you access the index of an element in an array during iteration?](#how-do-you-access-the-index-of-an-element-in-an-array-during-iteration) | Basic |\n| 22 | [What is the purpose of the `switch` statement?](#what-is-the-purpose-of-the-switch-statement) | Basic |\n| 23 | [What are rest parameters and how are they used?](#what-are-rest-parameters-and-how-are-they-used) | Basic |\n| 24 | [Explain the concept of the spread operator and its uses](#explain-the-concept-of-the-spread-operator-and-its-uses) | Basic |\n| 25 | [What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?](#what-are-the-benefits-of-using-spread-syntax-in-javascript-and-how-is-it-different-from-rest-syntax) | Basic |\n| 26 | [What are iterators and generators in JavaScript and what are they used for?](#what-are-iterators-and-generators-in-javascript-and-what-are-they-used-for) | Advanced |\n| 27 | [Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}` in JavaScript](#explain-the-differences-on-the-usage-of-foo-between-function-foo--and-var-foo--function--in-javascript) | Basic |\n| 28 | [What is the difference between a parameter and an argument?](#what-is-the-difference-between-a-parameter-and-an-argument) | Basic |\n| 29 | [Explain the concept of hoisting with regards to functions](#explain-the-concept-of-hoisting-with-regards-to-functions) | Basic |\n| 30 | [What's the difference between `.call` and `.apply` in JavaScript?](#whats-the-difference-between-call-and-apply-in-javascript) | Basic |\n| 31 | [Can you offer a use case for the new arrow => function syntax?](#can-you-offer-a-use-case-for-the-new-arrow--function-syntax) | Basic |\n| 32 | [Difference between: `function Person(){}`, `const person = Person()`, and `const person = new Person()` in JavaScript?](#difference-between-function-person-const-person--person-and-const-person--new-person-in-javascript) | Basic |\n| 33 | [What is the definition of a higher-order function in JavaScript?](#what-is-the-definition-of-a-higher-order-function-in-javascript) | Basic |\n| 34 | [What are callback functions and how are they used?](#what-are-callback-functions-and-how-are-they-used) | Basic |\n| 35 | [What's a typical use case for anonymous functions in JavaScript?](#whats-a-typical-use-case-for-anonymous-functions-in-javascript) | Intermediate |\n| 36 | [What is recursion and how is it used in JavaScript?](#what-is-recursion-and-how-is-it-used-in-javascript) | Basic |\n| 37 | [What are default parameters and how are they used?](#what-are-default-parameters-and-how-are-they-used) | Basic |\n| 38 | [Explain why the following doesn't work as an IIFE: `function foo(){}();`. What needs to be changed to properly make it an IIFE?](#explain-why-the-following-doesnt-work-as-an-iife-function-foo-what-needs-to-be-changed-to-properly-make-it-an-iife) | Advanced |\n| 39 | [What are the various ways to create objects in JavaScript?](#what-are-the-various-ways-to-create-objects-in-javascript) | Basic |\n| 40 | [Explain the difference between dot notation and bracket notation for accessing object properties](#explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties) | Basic |\n| 41 | [What are the different methods for iterating over an array?](#what-are-the-different-methods-for-iterating-over-an-array) | Basic |\n| 42 | [How do you add, remove, and update elements in an array?](#how-do-you-add-remove-and-update-elements-in-an-array) | Basic |\n| 43 | [What are the different ways to copy an object or an array?](#what-are-the-different-ways-to-copy-an-object-or-an-array) | Basic |\n| 44 | [Explain the difference between shallow copy and deep copy](#explain-the-difference-between-shallow-copy-and-deep-copy) | Basic |\n| 45 | [What are the advantages of using the spread operator with arrays and objects?](#what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects) | Basic |\n| 46 | [How do you check if an object has a specific property?](#how-do-you-check-if-an-object-has-a-specific-property) | Basic |\n| 47 | [Explain the difference between mutable and immutable objects in JavaScript](#explain-the-difference-between-mutable-and-immutable-objects-in-javascript) | Intermediate |\n| 48 | [Explain the concept of destructuring assignment for objects and arrays](#explain-the-concept-of-destructuring-assignment-for-objects-and-arrays) | Basic |\n| 49 | [What is `Object.freeze()` for?](#what-is-objectfreeze-for) | Intermediate |\n| 50 | [What is `Object.seal()` for?](#what-is-objectseal-for) | Intermediate |\n| 51 | [What is `Object.preventExtensions()` for?](#what-is-objectpreventextensions-for) | Intermediate |\n| 52 | [What are JavaScript object getters and setters for?](#what-are-javascript-object-getters-and-setters-for) | Intermediate |\n| 53 | [What are JavaScript object property flags and descriptors?](#what-are-javascript-object-property-flags-and-descriptors) | Advanced |\n| 54 | [How do you reliably determine whether an object is empty?](#how-do-you-reliably-determine-whether-an-object-is-empty) | Basic |\n| 55 | [What is the event loop in JavaScript runtimes?](#what-is-the-event-loop-in-javascript-runtimes) | Basic |\n| 56 | [Explain the difference between synchronous and asynchronous functions in JavaScript](#explain-the-difference-between-synchronous-and-asynchronous-functions-in-javascript) | Basic |\n| 57 | [Explain the concept of a callback function in asynchronous operations](#explain-the-concept-of-a-callback-function-in-asynchronous-operations) | Basic |\n| 58 | [What are Promises and how do they work?](#what-are-promises-and-how-do-they-work) | Basic |\n| 59 | [Explain the different states of a Promise](#explain-the-different-states-of-a-promise) | Intermediate |\n| 60 | [What are the pros and cons of using Promises instead of callbacks in JavaScript?](#what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks-in-javascript) | Intermediate |\n| 61 | [What is the use of `Promise.all()`](#what-is-the-use-of-promiseall) | Basic |\n| 62 | [How is `Promise.all()` different from `Promise.allSettled()`?](#how-is-promiseall-different-from-promiseallsettled) | Intermediate |\n| 63 | [What is async/await and how does it simplify asynchronous code?](#what-is-asyncawait-and-how-does-it-simplify-asynchronous-code) | Intermediate |\n| 64 | [How do you handle errors in asynchronous operations?](#how-do-you-handle-errors-in-asynchronous-operations) | Basic |\n| 65 | [Explain the concept of a microtask queue](#explain-the-concept-of-a-microtask-queue) | Intermediate |\n| 66 | [What is the difference between `setTimeout()`, `setImmediate()`, and `process.nextTick()`?](#what-is-the-difference-between-settimeout-setimmediate-and-processnexttick) | Intermediate |\n| 67 | [Explain how prototypal inheritance works in JavaScript](#explain-how-prototypal-inheritance-works-in-javascript) | Basic |\n| 68 | [What is the prototype chain and how does it work?](#what-is-the-prototype-chain-and-how-does-it-work) | Intermediate |\n| 69 | [Explain the difference between classical inheritance and prototypal inheritance](#explain-the-difference-between-classical-inheritance-and-prototypal-inheritance) | Basic |\n| 70 | [Explain the concept of inheritance in ES2015 classes](#explain-the-concept-of-inheritance-in-es2015-classes) | Basic |\n| 71 | [What is the purpose of the `new` keyword?](#what-is-the-purpose-of-the-new-keyword) | Basic |\n| 72 | [How do you create a constructor function?](#how-do-you-create-a-constructor-function) | Basic |\n| 73 | [What are the differences between JavaScript ES2015 classes and ES5 function constructors?](#what-are-the-differences-between-javascript-es2015-classes-and-es5-function-constructors) | Basic |\n| 74 | [What advantage is there for using the JavaScript arrow syntax for a method in a constructor?](#what-advantage-is-there-for-using-the-javascript-arrow-syntax-for-a-method-in-a-constructor) | Basic |\n| 75 | [Why might you want to create static class members in JavaScript?](#why-might-you-want-to-create-static-class-members-in-javascript) | Intermediate |\n| 76 | [What is a closure in JavaScript, and how/why would you use one?](#what-is-a-closure-in-javascript-and-howwhy-would-you-use-one) | Intermediate |\n| 77 | [Explain the concept of lexical scoping](#explain-the-concept-of-lexical-scoping) | Basic |\n| 78 | [Explain the concept of scope in JavaScript](#explain-the-concept-of-scope-in-javascript) | Basic |\n| 79 | [How can closures be used to create private variables?](#how-can-closures-be-used-to-create-private-variables) | Basic |\n| 80 | [What are the potential pitfalls of using closures?](#what-are-the-potential-pitfalls-of-using-closures) | Intermediate |\n| 81 | [Explain the difference between global scope, function scope, and block scope](#explain-the-difference-between-global-scope-function-scope-and-block-scope) | Basic |\n| 82 | [Explain how `this` works in JavaScript](#explain-how-this-works-in-javascript) | Basic |\n| 83 | [Explain `Function.prototype.bind` in JavaScript](#explain-functionprototypebind-in-javascript) | Basic |\n| 84 | [Explain the different ways the `this` keyword can be bound](#explain-the-different-ways-the-this-keyword-can-be-bound) | Intermediate |\n| 85 | [What are the common pitfalls of using the `this` keyword?](#what-are-the-common-pitfalls-of-using-the-this-keyword) | Basic |\n| 86 | [Explain the concept of `this` binding in event handlers](#explain-the-concept-of-this-binding-in-event-handlers) | Basic |\n| 87 | [What is the DOM and how is it structured?](#what-is-the-dom-and-how-is-it-structured) | Basic |\n| 88 | [What's the difference between an \"attribute\" and a \"property\" in the DOM?](#whats-the-difference-between-an-attribute-and-a-property-in-the-dom) | Intermediate |\n| 89 | [Explain the difference between `document.querySelector()` and `document.getElementById()`](#explain-the-difference-between-documentqueryselector-and-documentgetelementbyid) | Basic |\n| 90 | [How do you add, remove, and modify HTML elements using JavaScript?](#how-do-you-add-remove-and-modify-html-elements-using-javascript) | Basic |\n| 91 | [What are event listeners and how are they used?](#what-are-event-listeners-and-how-are-they-used) | Basic |\n| 92 | [Explain the event phases in a browser](#explain-the-event-phases-in-a-browser) | Intermediate |\n| 93 | [Describe event bubbling in JavaScript and browsers](#describe-event-bubbling-in-javascript-and-browsers) | Basic |\n| 94 | [Describe event capturing in JavaScript and browsers](#describe-event-capturing-in-javascript-and-browsers) | Basic |\n| 95 | [Explain event delegation in JavaScript](#explain-event-delegation-in-javascript) | Basic |\n| 96 | [How do you prevent the default behavior of an event?](#how-do-you-prevent-the-default-behavior-of-an-event) | Basic |\n| 97 | [What is the difference between `event.preventDefault()` and `event.stopPropagation()`?](#what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation) | Intermediate |\n| 98 | [What is the difference between `mouseenter` and `mouseover` event in JavaScript and browsers?](#what-is-the-difference-between-mouseenter-and-mouseover-event-in-javascript-and-browsers) | Basic |\n| 99 | [What is the difference between `innerHTML` and `textContent`?](#what-is-the-difference-between-innerhtml-and-textcontent) | Intermediate |\n| 100 | [How do you manipulate CSS styles using JavaScript?](#how-do-you-manipulate-css-styles-using-javascript) | Basic |\n| 101 | [Describe the difference between `<script>`, `<script async>` and `<script defer>`](#describe-the-difference-between-script-script-async-and-script-defer) | Basic |\n| 102 | [What is the difference between the Window object and the Document object?](#what-is-the-difference-between-the-window-object-and-the-document-object) | Intermediate |\n| 103 | [Describe the difference between a cookie, `sessionStorage` and `localStorage` in browsers](#describe-the-difference-between-a-cookie-sessionstorage-and-localstorage-in-browsers) | Basic |\n| 104 | [How do you make an HTTP request using the Fetch API?](#how-do-you-make-an-http-request-using-the-fetch-api) | Basic |\n| 105 | [What are the different ways to make an API call in JavaScript?](#what-are-the-different-ways-to-make-an-api-call-in-javascript) | Basic |\n| 106 | [Explain AJAX in as much detail as possible](#explain-ajax-in-as-much-detail-as-possible) | Basic |\n| 107 | [What are the advantages and disadvantages of using AJAX?](#what-are-the-advantages-and-disadvantages-of-using-ajax) | Basic |\n| 108 | [What are the differences between `XMLHttpRequest` and `fetch()` in JavaScript and browsers?](#what-are-the-differences-between-xmlhttprequest-and-fetch-in-javascript-and-browsers) | Basic |\n| 109 | [How do you abort a web request using `AbortController` in JavaScript?](#how-do-you-abort-a-web-request-using-abortcontroller-in-javascript) | Intermediate |\n| 110 | [Explain how JSONP works (and how it's not really Ajax)](#explain-how-jsonp-works-and-how-its-not-really-ajax) | Intermediate |\n| 111 | [What are workers in JavaScript used for?](#what-are-workers-in-javascript-used-for) | Advanced |\n| 112 | [Explain the concept of the Web Socket API](#explain-the-concept-of-the-web-socket-api) | Intermediate |\n| 113 | [What are JavaScript polyfills for?](#what-are-javascript-polyfills-for) | Advanced |\n| 114 | [How do you detect if JavaScript is disabled on a page?](#how-do-you-detect-if-javascript-is-disabled-on-a-page) | Intermediate |\n| 115 | [What is the `Intl` namespace object for?](#what-is-the-intl-namespace-object-for) | Intermediate |\n| 116 | [How do you validate form elements using the Constraint Validation API?](#how-do-you-validate-form-elements-using-the-constraint-validation-api) | Advanced |\n| 117 | [How do you use `window.history` API?](#how-do-you-use-windowhistory-api) | Basic |\n| 118 | [How do `<iframe>` on a page communicate?](#how-do-iframe-on-a-page-communicate) | Intermediate |\n| 119 | [Difference between document `load` event and document `DOMContentLoaded` event?](#difference-between-document-load-event-and-document-domcontentloaded-event) | Intermediate |\n| 120 | [How do you redirect to a new page in JavaScript?](#how-do-you-redirect-to-a-new-page-in-javascript) | Basic |\n| 121 | [How do you get the query string values of the current page in JavaScript?](#how-do-you-get-the-query-string-values-of-the-current-page-in-javascript) | Basic |\n| 122 | [What are server-sent events?](#what-are-server-sent-events) | Advanced |\n| 123 | [What are Progressive Web Applications (PWAs)?](#what-are-progressive-web-applications-pwas) | Intermediate |\n| 124 | [What are modules and why are they useful?](#what-are-modules-and-why-are-they-useful) | Basic |\n| 125 | [Explain the differences between CommonJS modules and ES modules in JavaScript](#explain-the-differences-between-commonjs-modules-and-es-modules-in-javascript) | Intermediate |\n| 126 | [How do you import and export modules in JavaScript?](#how-do-you-import-and-export-modules-in-javascript) | Basic |\n| 127 | [What are the benefits of using a module bundler?](#what-are-the-benefits-of-using-a-module-bundler) | Intermediate |\n| 128 | [Explain the concept of tree shaking in module bundling](#explain-the-concept-of-tree-shaking-in-module-bundling) | Intermediate |\n| 129 | [What are the metadata fields of a module?](#what-are-the-metadata-fields-of-a-module) | Intermediate |\n| 130 | [What do you think of CommonJS vs ESM?](#what-do-you-think-of-commonjs-vs-esm) | Basic |\n| 131 | [What are the different types of errors in JavaScript?](#what-are-the-different-types-of-errors-in-javascript) | Intermediate |\n| 132 | [How do you handle errors using `try...catch` blocks?](#how-do-you-handle-errors-using-trycatch-blocks) | Basic |\n| 133 | [What is the purpose of the `finally` block?](#what-is-the-purpose-of-the-finally-block) | Basic |\n| 134 | [How can you create custom error objects?](#how-can-you-create-custom-error-objects) | Intermediate |\n| 135 | [Explain the concept of error propagation in JavaScript](#explain-the-concept-of-error-propagation-in-javascript) | Intermediate |\n| 136 | [What is currying and how does it work?](#what-is-currying-and-how-does-it-work) | Intermediate |\n| 137 | [Explain the concept of partial application](#explain-the-concept-of-partial-application) | Intermediate |\n| 138 | [What are the benefits of using currying and partial application?](#what-are-the-benefits-of-using-currying-and-partial-application) | Intermediate |\n| 139 | [Provide some examples of how currying and partial application can be used](#provide-some-examples-of-how-currying-and-partial-application-can-be-used) | Basic |\n| 140 | [How do currying and partial application differ from each other?](#how-do-currying-and-partial-application-differ-from-each-other) | Intermediate |\n| 141 | [What are `Set`s and `Map`s and how are they used?](#what-are-sets-and-maps-and-how-are-they-used) | Basic |\n| 142 | [What are the differences between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript?](#what-are-the-differences-between-mapset-and-weakmapweakset-in-javascript) | Basic |\n| 143 | [How do you convert a `Set` to an array in JavaScript?](#how-do-you-convert-a-set-to-an-array-in-javascript) | Basic |\n| 144 | [What is the difference between a `Map` object and a plain object in JavaScript?](#what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript) | Basic |\n| 145 | [How do `Set`s and `Map`s handle equality checks for objects?](#how-do-sets-and-maps-handle-equality-checks-for-objects) | Basic |\n| 146 | [What are some common performance bottlenecks in JavaScript applications?](#what-are-some-common-performance-bottlenecks-in-javascript-applications) | Intermediate |\n| 147 | [Explain the concept of debouncing and throttling](#explain-the-concept-of-debouncing-and-throttling) | Basic |\n| 148 | [How can you optimize DOM manipulation for better performance?](#how-can-you-optimize-dom-manipulation-for-better-performance) | Advanced |\n| 149 | [What are some techniques for reducing reflows and repaints?](#what-are-some-techniques-for-reducing-reflows-and-repaints) | Advanced |\n| 150 | [Explain the concept of lazy loading and how it can improve performance](#explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance) | Basic |\n| 151 | [What are Web Workers and how can they be used to improve performance?](#what-are-web-workers-and-how-can-they-be-used-to-improve-performance) | Advanced |\n| 152 | [Explain the concept of caching and how it can be used to improve performance](#explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance) | Basic |\n| 153 | [What are some tools that can be used to measure and analyze JavaScript performance?](#what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance) | Advanced |\n| 154 | [How can you optimize network requests for better performance?](#how-can-you-optimize-network-requests-for-better-performance) | Advanced |\n| 155 | [What are the different types of testing in software development?](#what-are-the-different-types-of-testing-in-software-development) | Intermediate |\n| 156 | [Explain the difference between unit testing, integration testing, and end-to-end testing](#explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing) | Intermediate |\n| 157 | [What are some popular JavaScript testing frameworks?](#what-are-some-popular-javascript-testing-frameworks) | Basic |\n| 158 | [How do you write unit tests for JavaScript code?](#how-do-you-write-unit-tests-for-javascript-code) | Intermediate |\n| 159 | [Explain the concept of test-driven development (TDD)](#explain-the-concept-of-test-driven-development-tdd) | Intermediate |\n| 160 | [What are mocks and stubs and how are they used in testing?](#what-are-mocks-and-stubs-and-how-are-they-used-in-testing) | Advanced |\n| 161 | [How can you test asynchronous code in JavaScript?](#how-can-you-test-asynchronous-code-in-javascript) | Intermediate |\n| 162 | [What are some best practices for writing maintainable and effective tests in JavaScript?](#what-are-some-best-practices-for-writing-maintainable-and-effective-tests-in-javascript) | Intermediate |\n| 163 | [Explain the concept of code coverage and how it can be used to assess test quality](#explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality) | Intermediate |\n| 164 | [What are some tools that can be used for JavaScript testing?](#what-are-some-tools-that-can-be-used-for-javascript-testing) | Basic |\n| 165 | [What are design patterns and why are they useful?](#what-are-design-patterns-and-why-are-they-useful) | Basic |\n| 166 | [Explain the concept of the Singleton pattern](#explain-the-concept-of-the-singleton-pattern) | Basic |\n| 167 | [What is the Factory pattern and how is it used?](#what-is-the-factory-pattern-and-how-is-it-used) | Intermediate |\n| 168 | [Explain the Observer pattern and its use cases](#explain-the-observer-pattern-and-its-use-cases) | Intermediate |\n| 169 | [What is the Module pattern and how does it help with encapsulation?](#what-is-the-module-pattern-and-how-does-it-help-with-encapsulation) | Intermediate |\n| 170 | [Explain the concept of the Prototype pattern](#explain-the-concept-of-the-prototype-pattern) | Basic |\n| 171 | [What is the Decorator pattern and how is it used?](#what-is-the-decorator-pattern-and-how-is-it-used) | Intermediate |\n| 172 | [Explain the concept of the Strategy pattern](#explain-the-concept-of-the-strategy-pattern) | Intermediate |\n| 173 | [What is the Command pattern and how is it used?](#what-is-the-command-pattern-and-how-is-it-used) | Intermediate |\n| 174 | [Why is extending built-in JavaScript objects not a good idea?](#why-is-extending-built-in-javascript-objects-not-a-good-idea) | Intermediate |\n| 175 | [What is Cross-Site Scripting (XSS) and how can you prevent it?](#what-is-cross-site-scripting-xss-and-how-can-you-prevent-it) | Intermediate |\n| 176 | [Explain the concept of Cross-Site Request Forgery (CSRF) and its mitigation techniques](#explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques) | Intermediate |\n| 177 | [How can you prevent SQL injection vulnerabilities in JavaScript applications?](#how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications) | Intermediate |\n| 178 | [What are some best practices for handling sensitive data in JavaScript?](#what-are-some-best-practices-for-handling-sensitive-data-in-javascript) | Intermediate |\n| 179 | [Explain the concept of Content Security Policy (CSP) and how it enhances security](#explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security) | Intermediate |\n| 180 | [What are some common security headers and their purpose?](#what-are-some-common-security-headers-and-their-purpose) | Intermediate |\n| 181 | [How can you prevent clickjacking attacks?](#how-can-you-prevent-clickjacking-attacks) | Advanced |\n| 182 | [Explain the concept of input validation and its importance in security](#explain-the-concept-of-input-validation-and-its-importance-in-security) | Intermediate |\n| 183 | [What are some tools and techniques for identifying security vulnerabilities in JavaScript code?](#what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code) | Intermediate |\n| 184 | [How can you implement secure authentication and authorization in JavaScript applications?](#how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications) | Advanced |\n| 185 | [Explain the same-origin policy with regards to JavaScript](#explain-the-same-origin-policy-with-regards-to-javascript) | Intermediate |\n| 186 | [What is `'use strict';` in JavaScript for?](#what-is-use-strict-in-javascript-for) | Advanced |\n| 187 | [What tools and techniques do you use for debugging JavaScript code?](#what-tools-and-techniques-do-you-use-for-debugging-javascript-code) | Intermediate |\n| 188 | [How does JavaScript garbage collection work?](#how-does-javascript-garbage-collection-work) | Advanced |\n| 189 | [Explain what a single page app is and how to make one SEO-friendly](#explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly) | Intermediate |\n| 190 | [How can you share code between JavaScript files?](#how-can-you-share-code-between-javascript-files) | Basic |\n| 191 | [How do you organize your code?](#how-do-you-organize-your-code) | Intermediate |\n| 192 | [What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?](#what-are-some-of-the-advantagesdisadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript) | Advanced |\n| 193 | [When would you use `document.write()`?](#when-would-you-use-documentwrite) | Advanced |\n\n<!-- TABLE_OF_CONTENTS:ALL:END -->\n\n## Top Questions with Answers\n\n<!-- QUESTIONS:TOP:START -->\n\n### Explain the concept of \"hoisting\" in JavaScript\n\n<!-- Update here: /questions/explain-hoisting/en-US.mdx -->\n\nHoisting is a JavaScript mechanism where variable and function declarations are moved (\"hoisted\") to the top of their containing scope during the compile phase.\n\n- **Variable declarations (`var`)**: Declarations are hoisted, but not initializations. The value of the variable is `undefined` if accessed before initialization.\n- **Variable declarations (`let` and `const`)**: Declarations are hoisted, but not initialized. Accessing them results in `ReferenceError` until the actual declaration is encountered.\n- **Function expressions (`var`)**: Declarations are hoisted, but not initializations. The value of the variable is `undefined` if accessed before initialization.\n- **Function declarations (`function`)**: Both declaration and definition are fully hoisted.\n- **Class declarations (`class`)**: Declarations are hoisted, but not initialized. Accessing them results in `ReferenceError` until the actual declaration is encountered.\n- **Import declarations (`import`)**: Declarations are hoisted, and side effects of importing the module are executed before the rest of the code.\n\nThe following behavior summarizes the result of accessing the variables before they are declared.\n\n| Declaration                    | Accessing before declaration |\n| ------------------------------ | ---------------------------- |\n| `var foo`                      | `undefined`                  |\n| `let foo`                      | `ReferenceError`             |\n| `const foo`                    | `ReferenceError`             |\n| `class Foo`                    | `ReferenceError`             |\n| `var foo = function() { ... }` | `undefined`                  |\n| `function foo() { ... }`       | Normal                       |\n| `import`                       | Normal                       |\n\n<!-- Update here: /questions/explain-hoisting/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/explain-hoisting?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-hoisting/en-US.mdx)\n\n<br>\n\n### What are the differences between JavaScript variables created using `let`, `var` or `const`?\n\n<!-- Update here: /questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx -->\n\nIn JavaScript, `let`, `var`, and `const` are all keywords used to declare variables, but they differ significantly in terms of scope, initialization rules, whether they can be redeclared or reassigned and the behavior when they are accessed before declaration:\n\n| Behavior | `var` | `let` | `const` |\n| --- | --- | --- | --- |\n| Scope | Function or Global | Block | Block |\n| Initialization | Optional | Optional | Required |\n| Redeclaration | Yes | No | No |\n| Reassignment | Yes | Yes | No |\n| Accessing before declaration | `undefined` | `ReferenceError` | `ReferenceError` |\n\n<!-- Update here: /questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-the-differences-between-variables-created-using-let-var-or-const?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx)\n\n<br>\n\n### What is the difference between `==` and `===` in JavaScript?\n\n<!-- Update here: /questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx -->\n\n`==` is the abstract equality operator while `===` is the strict equality operator. The `==` operator will compare for equality after doing any necessary type conversions. The `===` operator will not do type conversion, so if two values are not the same type `===` will simply return `false`.\n\n| Operator | `==` | `===` |\n| --- | --- | --- |\n| Name | (Loose) Equality operator | Strict equality operator |\n| Type coercion | Yes | No |\n| Compares value and type | No | Yes |\n\n<!-- Update here: /questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-is-the-difference-between-double-equal-and-triple-equal?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx)\n\n<br>\n\n### What is the event loop in JavaScript runtimes?\n\n<!-- Update here: /questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.mdx -->\n\nThe event loop is a concept within the JavaScript runtime environment regarding how asynchronous operations are executed within JavaScript engines. It works as such:\n\n1. The JavaScript engine starts executing scripts, placing synchronous operations on the call stack.\n2. When an asynchronous operation is encountered (e.g., `setTimeout()`, HTTP request), it is offloaded to the respective Web API or Node.js API to handle the operation in the background.\n3. Once the asynchronous operation completes, its callback function is placed in the respective queues – task queues (also known as macrotask queues / callback queues) or microtask queues. We will refer to \"task queue\" as \"macrotask queue\" from here on to better differentiate from the microtask queue.\n4. The event loop continuously monitors the call stack and executes items on the call stack. If/when the call stack is empty:\n   1. Microtask queue is processed. Microtasks include promise callbacks (`then`, `catch`, `finally`), `MutationObserver` callbacks, and calls to `queueMicrotask()`. The event loop takes the first callback from the microtask queue and pushes it to the call stack for execution. This repeats until the microtask queue is empty.\n   2. Macrotask queue is processed. Macrotasks include web APIs like `setTimeout()`, HTTP requests, user interface event handlers like clicks, scrolls, etc. The event loop dequeues the first callback from the macrotask queue and pushes it onto the call stack for execution. However, after a macrotask queue callback is processed, the event loop does not proceed with the next macrotask yet! The event loop first checks the microtask queue. Checking the microtask queue is necessary as microtasks have higher priority than macrotask queue callbacks. The macrotask queue callback that was just executed could have added more microtasks!\n      1. If the microtask queue is non-empty, process them as per the previous step.\n      2. If the microtask queue is empty, the next macrotask queue callback is processed. This repeats until the macrotask queue is empty.\n5. This process continues indefinitely, allowing the JavaScript engine to handle both synchronous and asynchronous operations efficiently without blocking the call stack.\n\nThe unfortunate truth is that it is extremely hard to explain the event loop well using only text. We recommend checking out one of the following excellent videos explaining the event loop:\n\n- [JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue](https://www.youtube.com/watch?v=eiC58R16hb8) (2024): Lydia Hallie is a popular educator on JavaScript and this is the best recent video explaining the event loop. There's also an [accompanying blog post](https://www.lydiahallie.com/blog/event-loop) for those who prefer detailed text-based explanations.\n- [In the Loop](https://www.youtube.com/watch?v=cCOL7MC4Pl0) (2018): Jake Archibald previously from the Chrome team provides a visual demonstration of the event loop during JSConf 2018, accounting for different types of tasks.\n- [What the heck is the event loop anyway?](https://www.youtube.com/watch?v=8aGhZQkoFbQ) (2014): Philip Robert's gave this epic talk at JSConf 2014 and it is one of the most viewed JavaScript videos on YouTube.\n\nWe recommend watching [Lydia's video](https://www.youtube.com/watch?v=eiC58R16hb8) as it is the most modern and concise explanation standing at only 13 minutes long whereas the other videos are at least 30 minutes long. Her video is sufficient for the purpose of interviews.\n\n<!-- Update here: /questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.mdx)\n\n<br>\n\n### Explain event delegation in JavaScript\n\n<!-- Update here: /questions/explain-event-delegation/en-US.mdx -->\n\nEvent delegation is a technique in JavaScript where a single event listener is attached to a parent element instead of attaching event listeners to multiple child elements. When an event occurs on a child element, the event bubbles up the DOM tree, and the parent element's event listener handles the event based on the target element.\n\nEvent delegation provides the following benefits:\n\n- **Improved performance**: Attaching a single event listener is more efficient than attaching multiple event listeners to individual elements, especially for large or dynamic lists. This reduces memory usage and improves overall performance.\n- **Simplified event handling**: With event delegation, you only need to write the event handling logic once in the parent element's event listener. This makes the code more maintainable and easier to update.\n- **Dynamic element support**: Event delegation automatically handles events for dynamically added or removed elements within the parent element. There's no need to manually attach or remove event listeners when the DOM structure changes\n\nHowever, do note that:\n\n- It is important to identify the target element that triggered the event.\n- Not all events can be delegated because they are not bubbled. Non-bubbling events include: `focus`, `blur`, `scroll`, `mouseenter`, `mouseleave`, `resize`, etc.\n\n<!-- Update here: /questions/explain-event-delegation/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/explain-event-delegation?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-event-delegation/en-US.mdx)\n\n<br>\n\n### Explain how `this` works in JavaScript\n\n<!-- Update here: /questions/explain-how-this-works-in-javascript/en-US.mdx -->\n\nThere's no simple explanation for `this`; it is one of the most confusing concepts in JavaScript because it's behavior differs from many other programming languages. The one-liner explanation of the `this` keyword is that it is a dynamic reference to the context in which a function is executed.\n\nA longer explanation is that `this` follows these rules:\n\n1. If the `new` keyword is used when calling the function, meaning the function was used as a function constructor, the `this` inside the function is the newly-created object instance.\n2. If `this` is used in a `class` `constructor`, the `this` inside the `constructor` is the newly-created object instance.\n3. If `apply()`, `call()`, or `bind()` is used to call/create a function, `this` inside the function is the object that is passed in as the argument.\n4. If a function is called as a method (e.g. `obj.method()`) — `this` is the object that the function is a property of.\n5. If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, `this` is the global object. In the browser, the global object is the `window` object. If in strict mode (`'use strict';`), `this` will be `undefined` instead of the global object.\n6. If multiple of the above rules apply, the rule that is higher wins and will set the `this` value.\n7. If the function is an ES2015 arrow function, it ignores all the rules above and receives the `this` value of its surrounding scope at the time it is created.\n\nFor an in-depth explanation, do check out [Arnav Aggrawal's article on Medium](https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3).\n\n<!-- Update here: /questions/explain-how-this-works-in-javascript/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/explain-how-this-works-in-javascript?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-how-this-works-in-javascript/en-US.mdx)\n\n<br>\n\n### Describe the difference between a cookie, `sessionStorage` and `localStorage` in browsers\n\n<!-- Update here: /questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.mdx -->\n\nAll of the following are mechanisms of storing data on the client, the user's browser in this case. `localStorage` and `sessionStorage` both implement the [Web Storage API interface](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API).\n\n- **Cookies**: Suitable for server-client communication, small storage capacity, can be persistent or session-based, domain-specific. Sent to the server on every request.\n- **`localStorage`**: Suitable for long-term storage, data persists even after the browser is closed, accessible across all tabs and windows of the same origin, highest storage capacity among the three.\n- **`sessionStorage`**: Suitable for temporary data within a single page session, data is cleared when the tab or window is closed, has a higher storage capacity compared to cookies.\n\nHere's a table summarizing the 3 client storage mechanisms.\n\n| Property | Cookie | `localStorage` | `sessionStorage` |\n| --- | --- | --- | --- |\n| Initiator | Client or server. Server can use `Set-Cookie` header | Client | Client |\n| Lifespan | As specified | Until deleted | Until tab is closed |\n| Persistent across browser sessions | If a future expiry date is set | Yes | No |\n| Sent to server with every HTTP request | Yes, sent via `Cookie` header | No | No |\n| Total capacity (per domain) | 4kb | 5MB | 5MB |\n| Access | Across windows/tabs | Across windows/tabs | Same tab |\n| Security | JavaScript cannot access `HttpOnly` cookies | None | None |\n\n<!-- Update here: /questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.mdx)\n\n<br>\n\n### Describe the difference between `<script>`, `<script async>` and `<script defer>`\n\n<!-- Update here: /questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx -->\n\nAll of these ways (`<script>`, `<script async>`, and `<script defer>`) are used to load and execute JavaScript files in an HTML document, but they differ in how the browser handles loading and execution of the script:\n\n- `<script>` is the default way of including JavaScript. The browser blocks HTML parsing while the script is being downloaded and executed. The browser will not continue rendering the page until the script has finished executing.\n- `<script async>` downloads the script asynchronously, in parallel with parsing the HTML. Executes the script as soon as it is available, potentially interrupting the HTML parsing. `<script async>` do not wait for each other and execute in no particular order.\n- `<script defer>` downloads the script asynchronously, in parallel with parsing the HTML. However, the execution of the script is deferred until HTML parsing is complete, in the order they appear in the HTML.\n\nHere's a table summarizing the 3 ways of loading `<script>`s in a HTML document.\n\n| Feature | `<script>` | `<script async>` | `<script defer>` |\n| --- | --- | --- | --- |\n| Parsing behavior | Blocks HTML parsing | Runs parallel to parsing | Runs parallel to parsing |\n| Execution order | In order of appearance | Not guaranteed | In order of appearance |\n| DOM dependency | No | No | Yes (waits for DOM) |\n\n<!-- Update here: /questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/describe-the-difference-between-script-async-and-script-defer?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx)\n\n<br>\n\n### What's the difference between a JavaScript variable that is: `null`, `undefined` or undeclared?\n\n<!-- Update here: /questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx -->\n\n| Trait | `null` | `undefined` | Undeclared |\n| --- | --- | --- | --- |\n| Meaning | Explicitly set by the developer to indicate that a variable has no value | Variable has been declared but not assigned a value | Variable has not been declared at all |\n| Type (via `typeof` operator) | `'object'` | `'undefined'` | `'undefined'` |\n| Equality Comparison | `null == undefined` is `true` | `undefined == null` is `true` | Throws a `ReferenceError` |\n\n<!-- Update here: /questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx)\n\n<br>\n\n### What's the difference between `.call` and `.apply` in JavaScript?\n\n<!-- Update here: /questions/whats-the-difference-between-call-and-apply/en-US.mdx -->\n\n`.call` and `.apply` are both used to invoke functions with a specific `this` context and arguments. The primary difference lies in how they accept arguments:\n\n- `.call(thisArg, arg1, arg2, ...)`: Takes arguments individually.\n- `.apply(thisArg, [argsArray])`: Takes arguments as an array.\n\nAssuming we have a function `add`, the function can be invoked using `.call` and `.apply` in the following manner:\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconsole.log(add.call(null, 1, 2)); // 3\nconsole.log(add.apply(null, [1, 2])); // 3\n```\n\n<!-- Update here: /questions/whats-the-difference-between-call-and-apply/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/whats-the-difference-between-call-and-apply?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-the-difference-between-call-and-apply/en-US.mdx)\n\n<br>\n\n### Explain `Function.prototype.bind` in JavaScript\n\n<!-- Update here: /questions/explain-function-prototype-bind/en-US.mdx -->\n\n`Function.prototype.bind` is a method in JavaScript that allows you to create a new function with a specific `this` value and optional initial arguments. It's primary purpose is to:\n\n- **Binding `this` value to preserve context**: The primary purpose of `bind` is to bind the `this` value of a function to a specific object. When you call `func.bind(thisArg)`, it creates a new function with the same body as `func`, but with `this` permanently bound to `thisArg`.\n- **Partial application of arguments**: `bind` also allows you to pre-specify arguments for the new function. Any arguments passed to `bind` after `thisArg` will be prepended to the arguments list when the new function is called.\n- **Method borrowing**: `bind` allows you to borrow methods from one object and apply them to another object, even if they were not originally designed to work with that object.\n\nThe `bind` method is particularly useful in scenarios where you need to ensure that a function is called with a specific `this` context, such as in event handlers, callbacks, or method borrowing.\n\n<!-- Update here: /questions/explain-function-prototype-bind/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/explain-function-prototype-bind?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-function-prototype-bind/en-US.mdx)\n\n<br>\n\n### What advantage is there for using the JavaScript arrow syntax for a method in a constructor?\n\n<!-- Update here: /questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx -->\n\nThe main advantage of using an arrow function as a method inside a constructor is that the value of `this` gets set at the time of the function creation and can't change after that. When the constructor is used to create a new object, `this` will always refer to that object.\n\nFor example, let's say we have a `Person` constructor that takes a first name as an argument has two methods to `console.log()` that name, one as a regular function and one as an arrow function:\n\n```js live\nconst Person = function (name) {\n  this.firstName = name;\n  this.sayName1 = function () {\n    console.log(this.firstName);\n  };\n  this.sayName2 = () => {\n    console.log(this.firstName);\n  };\n};\n\nconst john = new Person('John');\nconst dave = new Person('Dave');\n\njohn.sayName1(); // John\njohn.sayName2(); // John\n\n// The regular function can have its `this` value changed, but the arrow function cannot\njohn.sayName1.call(dave); // Dave (because `this` is now the dave object)\njohn.sayName2.call(dave); // John\n\njohn.sayName1.apply(dave); // Dave (because `this` is now the dave object)\njohn.sayName2.apply(dave); // John\n\njohn.sayName1.bind(dave)(); // Dave (because `this` is now the dave object)\njohn.sayName2.bind(dave)(); // John\n\nconst sayNameFromWindow1 = john.sayName1;\nsayNameFromWindow1(); // undefined (because `this` is now the window object)\n\nconst sayNameFromWindow2 = john.sayName2;\nsayNameFromWindow2(); // John\n```\n\nThe main takeaway here is that `this` can be changed for a normal function, but `this` always stays the same for an arrow function. So even if you are passing around your arrow function to different parts of your application, you wouldn't have to worry about the value of `this` changing.\n\n<!-- Update here: /questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx)\n\n<br>\n\n### Explain how prototypal inheritance works in JavaScript\n\n<!-- Update here: /questions/explain-how-prototypal-inheritance-works/en-US.mdx -->\n\nPrototypical inheritance in JavaScript is a way for objects to inherit properties and methods from other objects. Every JavaScript object has a special hidden property called `[[Prototype]]` (commonly accessed via `__proto__` or using `Object.getPrototypeOf()`) that is a reference to another object, which is called the object's \"prototype\".\n\nWhen a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's `__proto__`, and the `__proto__`'s `__proto__` and so on, until it finds the property defined on one of the `__proto__`s or until it reaches the end of the prototype chain.\n\nThis behavior simulates classical inheritance, but it is really more of [delegation than inheritance](https://davidwalsh.name/javascript-objects).\n\nHere's an example of prototypal inheritance:\n\n```js live\n// Parent object constructor.\nfunction Animal(name) {\n  this.name = name;\n}\n\n// Add a method to the parent object's prototype.\nAnimal.prototype.makeSound = function () {\n  console.log('The ' + this.constructor.name + ' makes a sound.');\n};\n\n// Child object constructor.\nfunction Dog(name) {\n  Animal.call(this, name); // Call the parent constructor.\n}\n\n// Set the child object's prototype to be the parent's prototype.\nObject.setPrototypeOf(Dog.prototype, Animal.prototype);\n\n// Add a method to the child object's prototype.\nDog.prototype.bark = function () {\n  console.log('Woof!');\n};\n\n// Create a new instance of Dog.\nconst bolt = new Dog('Bolt');\n\n// Call methods on the child object.\nconsole.log(bolt.name); // \"Bolt\"\nbolt.makeSound(); // \"The Dog makes a sound.\"\nbolt.bark(); // \"Woof!\"\n```\n\nThings to note are:\n\n- `.makeSound` is not defined on `Dog`, so the JavaScript engine goes up the prototype chain and finds `.makeSound` on the inherited `Animal`.\n- Using `Object.create()` to build the inheritance chain is no longer recommended. Use `Object.setPrototypeOf()` instead.\n\n<!-- Update here: /questions/explain-how-prototypal-inheritance-works/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/explain-how-prototypal-inheritance-works?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-how-prototypal-inheritance-works/en-US.mdx)\n\n<br>\n\n### Difference between: `function Person(){}`, `const person = Person()`, and `const person = new Person()` in JavaScript?\n\n<!-- Update here: /questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx -->\n\n- `function Person(){}`: A function declaration in JavaScript. It can be used as a regular function or as a constructor.\n- `const person = Person()`: Calls `Person` as a regular function, not a constructor. If `Person` is intended to be a constructor, this will lead to unexpected behavior.\n- `const person = new Person()`: Creates a new instance of `Person`, correctly utilizing the constructor function to initialize the new object.\n\n| Aspect | `function Person(){}` | `const person = Person()` | `const person = new Person()` |\n| --- | --- | --- | --- |\n| Type | Function declaration | Function call | Constructor call |\n| Usage | Defines a function | Invokes `Person` as a regular function | Creates a new instance of `Person` |\n| Instance Creation | No instance created | No instance created | New instance created |\n| Common Mistake | N/A | Misusing as constructor leading to `undefined` | None (when used correctly) |\n\n<!-- Update here: /questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/difference-between-function-person-var-person-person-and-var-person-new-person?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx)\n\n<br>\n\n### Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}` in JavaScript\n\n<!-- Update here: /questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx -->\n\n`function foo() {}` a function declaration while the `var foo = function() {}` is a function expression. The key difference is that function declarations have its body hoisted but the bodies of function expressions are not (they have the same hoisting behavior as `var`-declared variables).\n\nIf you try to invoke a function expression before it is declared, you will get an `Uncaught TypeError: XXX is not a function` error.\n\nFunction declarations can be called in the enclosing scope even before they are declared.\n\n```js live\nfoo(); // 'FOOOOO'\nfunction foo() {\n  console.log('FOOOOO');\n}\n```\n\nFunction expressions if called before they are declared will result in an error.\n\n```js live\nfoo(); // Uncaught TypeError: foo is not a function\nvar foo = function () {\n  console.log('FOOOOO');\n};\n```\n\nAnother key difference is in the scope of the function name. Function expressions can be named by defining it after the `function` and before the parenthesis. However when using named function expressions, the function name is only accessible within the function itself. Trying to access it outside will result in an error or `undefined`.\n\n```js live\nconst myFunc = function namedFunc() {\n  console.log(namedFunc); // Works\n};\n\nmyFunc(); // Runs the function and logs the function reference\nconsole.log(namedFunc); // ReferenceError: namedFunc is not defined\n```\n\n**Note**: The examples uses `var` due to legacy reasons. Function expressions can be defined using `let` and `const` and the key difference is in the hoisting behavior of those keywords.\n\n<!-- Update here: /questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx)\n\n<br>\n\n### What's a typical use case for anonymous functions in JavaScript?\n\n<!-- Update here: /questions/whats-a-typical-use-case-for-anonymous-functions/en-US.mdx -->\n\nAnonymous function in Javascript is a function that does not have any name associated with it. They are typically used as arguments to other functions or assigned to variables.\n\n```js live\nconst arr = [-1, 0, 5, 6];\n\n// The filter method is passed an anonymous function.\narr.filter((x) => x > 1); // [5, 6]\n```\n\nThey are often used as arguments to other functions, known as higher-order functions, which can take functions as input and return a function as output. Anonymous functions can access variables from the outer scope, a concept known as closures, allowing them to \"close over\" and remember the environment in which they were created.\n\n```js live\n// Encapsulating Code\n(function () {\n  // Some code here.\n})();\n\n// Callbacks\nsetTimeout(function () {\n  console.log('Hello world!');\n}, 1000);\n\n// Functional programming constructs\nconst arr = [1, 2, 3];\nconst double = arr.map(function (el) {\n  return el * 2;\n});\nconsole.log(double); // [2, 4, 6]\n```\n\n<!-- Update here: /questions/whats-a-typical-use-case-for-anonymous-functions/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/whats-a-typical-use-case-for-anonymous-functions?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-a-typical-use-case-for-anonymous-functions/en-US.mdx)\n\n<br>\n\n### What are the various ways to create objects in JavaScript?\n\n<!-- Update here: /questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx -->\n\nCreating objects in JavaScript offers several methods:\n\n- **Object literals (`{}`)**: Simplest and most popular approach. Define key-value pairs within curly braces.\n- **`Object()` constructor**: Use `new Object()` with dot notation to add properties.\n- **`Object.create()`**: Create new objects using existing objects as prototypes, inheriting properties and methods.\n- **Constructor functions**: Define blueprints for objects using functions, creating instances with `new`.\n- **ES2015 classes**: Structured syntax similar to other languages, using `class` and `constructor` keywords.\n\n<!-- Update here: /questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-the-various-ways-to-create-objects-in-javascript?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx)\n\n<br>\n\n### What is a closure in JavaScript, and how/why would you use one?\n\n<!-- Update here: /questions/what-is-a-closure-and-how-why-would-you-use-one/en-US.mdx -->\n\nIn the book [\"You Don't Know JS\"](https://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/scope-closures) (YDKJS) by Kyle Simpson, a closure is defined as follows:\n\n> Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope\n\nIn simple terms, functions have access to variables that were in their scope at the time of their creation. This is what we call the function's lexical scope. A closure is a function that retains access to these variables even after the outer function has finished executing. This is like the function has a memory of its original environment.\n\n```js live\nfunction outerFunction() {\n  const outerVar = 'I am outside of innerFunction';\n\n  function innerFunction() {\n    console.log(outerVar); // `innerFunction` can still access `outerVar`.\n  }\n\n  return innerFunction;\n}\n\nconst inner = outerFunction(); // `inner` now holds a reference to `innerFunction`.\n\ninner(); // \"I am outside of innerFunction\"\n// Even though `outerFunction` has completed execution, `inner` still has access to variables defined inside `outerFunction`.\n```\n\nKey points to remember:\n\n- Closure occurs when an inner function has access to variables in its outer (lexical) scope, even when the outer function has finished executing.\n- Closure allows a function to **remember** the environment in which it was created, even if that environment is no longer present.\n- Closures are used extensively in JavaScript, such as in callbacks, event handlers, and asynchronous functions.\n\n<!-- Update here: /questions/what-is-a-closure-and-how-why-would-you-use-one/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-is-a-closure-and-how-why-would-you-use-one?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-a-closure-and-how-why-would-you-use-one/en-US.mdx)\n\n<br>\n\n### What is the definition of a higher-order function in JavaScript?\n\n<!-- Update here: /questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx -->\n\nA higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a result.\n\nHigher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is `Array.prototype.map()`, which takes an array and a function as arguments. `Array.prototype.map()` then uses this function to transform each item in the array, returning a new array with the transformed data. Other popular examples in JavaScript are `Array.prototype.forEach()`, `Array.prototype.filter()`, and `Array.prototype.reduce()`. A higher-order function doesn't just need to be manipulating arrays as there are many use cases for returning a function from another function. `Function.prototype.bind()` is an example that returns another function.\n\nImagine a scenario where we have an array of names that we need to transform to uppercase. The imperative way will be as such:\n\n```js live\nconst names = ['irish', 'daisy', 'anna'];\n\nfunction transformNamesToUppercase(names) {\n  const results = [];\n  for (let i = 0; i < names.length; i++) {\n    results.push(names[i].toUpperCase());\n  }\n  return results;\n}\n\nconsole.log(transformNamesToUppercase(names)); // ['IRISH', 'DAISY', 'ANNA']\n```\n\nUsing `Array.prototype.map(transformerFn)` makes the code shorter and more declarative.\n\n```js live\nconst names = ['irish', 'daisy', 'anna'];\n\nfunction transformNamesToUppercase(names) {\n  return names.map((name) => name.toUpperCase());\n}\n\nconsole.log(transformNamesToUppercase(names)); // ['IRISH', 'DAISY', 'ANNA']\n```\n\n<!-- Update here: /questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-is-the-definition-of-a-higher-order-function?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx)\n\n<br>\n\n### What are the differences between JavaScript ES2015 classes and ES5 function constructors?\n\n<!-- Update here: /questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx -->\n\nES2015 introduces a new way of creating classes, which provides a more intuitive and concise way to define and work with objects and inheritance compared to the ES5 function constructor syntax. Here's an example of each:\n\n```js\n// ES5 function constructor\nfunction Person(name) {\n  this.name = name;\n}\n\n// ES2015 Class\nclass Person {\n  constructor(name) {\n    this.name = name;\n  }\n}\n```\n\nFor simple constructors, they look pretty similar. The main difference in the constructor comes when using inheritance. If we want to create a `Student` class that subclasses `Person` and add a `studentId` field, this is what we have to do.\n\n```js live\n// ES5 inheritance\n// Superclass\nfunction Person1(name) {\n  this.name = name;\n}\n\n// Subclass\nfunction Student1(name, studentId) {\n  // Call constructor of superclass to initialize superclass-derived members.\n  Person1.call(this, name);\n\n  // Initialize subclass's own members.\n  this.studentId = studentId;\n}\nStudent1.prototype = Object.create(Person1.prototype);\nStudent1.prototype.constructor = Student1;\n\nconst student1 = new Student1('John', 1234);\nconsole.log(student1.name, student1.studentId); // \"John\" 1234\n\n// ES2015 inheritance\n// Superclass\nclass Person2 {\n  constructor(name) {\n    this.name = name;\n  }\n}\n\n// Subclass\nclass Student2 extends Person2 {\n  constructor(name, studentId) {\n    super(name);\n    this.studentId = studentId;\n  }\n}\n\nconst student2 = new Student2('Alice', 5678);\nconsole.log(student2.name, student2.studentId); // \"Alice\" 5678\n```\n\nIt's much more verbose to use inheritance in ES5 and the ES2015 version is easier to understand and remember.\n\n**Comparison of ES5 function constructors vs ES2015 classes**\n\n| Feature | ES5 Function Constructor | ES2015 Class |\n| --- | --- | --- |\n| Syntax | Uses function constructors and prototypes | Uses `class` keyword |\n| Constructor | Function with properties assigned using `this` | `constructor` method inside the class |\n| Method Definition | Defined on the prototype | Defined inside the class body |\n| Static Methods | Added directly to the constructor function | Defined using the `static` keyword |\n| Inheritance | Uses `Object.create()` and manually sets prototype chain | Uses `extends` keyword and `super` function |\n| Readability | Less intuitive and more verbose | More concise and intuitive |\n\n<!-- Update here: /questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-the-differences-between-es6-class-and-es5-function-constructors?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx)\n\n<br>\n\n### Describe event bubbling in JavaScript and browsers\n\n<!-- Update here: /questions/describe-event-bubbling/en-US.mdx -->\n\nEvent bubbling is a DOM event propagation mechanism where an event (e.g. a click), starts at the target element and bubbles up to the root of the document. This allows ancestor elements to also respond to the event.\n\nEvent bubbling is essential for event delegation, where a single event handler manages events for multiple child elements, enhancing performance and code simplicity. While convenient, failing to manage event propagation properly can lead to unintended behavior, such as multiple handlers firing for a single event.\n\n<!-- Update here: /questions/describe-event-bubbling/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/describe-event-bubbling?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-event-bubbling/en-US.mdx)\n\n<br>\n\n### Describe event capturing in JavaScript and browsers\n\n<!-- Update here: /questions/describe-event-capturing/en-US.mdx -->\n\nEvent capturing is a lesser-used counterpart to [event bubbling](https://www.greatfrontend.com/questions/quiz/describe-event-bubbling) in the DOM event propagation mechanism. It follows the opposite order, where an event triggers first on the ancestor element and then travels down to the target element.\n\nEvent capturing is rarely used as compared to event bubbling, but it can be used in specific scenarios where you need to intercept events at a higher level before they reach the target element. It is disabled by default but can be enabled through an option on `addEventListener()`.\n\n<!-- Update here: /questions/describe-event-capturing/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/describe-event-capturing?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-event-capturing/en-US.mdx)\n\n<br>\n\n### What is the difference between `mouseenter` and `mouseover` event in JavaScript and browsers?\n\n<!-- Update here: /questions/what-is-the-difference-between-mouseenter-and-mouseover-event/en-US.mdx -->\n\nThe main difference lies in the bubbling behavior of `mouseenter` and `mouseover` events. `mouseenter` does not bubble while `mouseover` bubbles.\n\n`mouseenter` events do not bubble. The `mouseenter` event is triggered only when the mouse pointer enters the element itself, not its descendants. If a parent element has child elements, and the mouse pointer enters child elements, the `mouseenter` event will not be triggered on the parent element again, it's only triggered once upon entry of parent element without regard for its contents. If both parent and child have `mouseenter` listeners attached and the mouse pointer moves from the parent element to the child element, `mouseenter` will only fire for the child.\n\n`mouseover` events bubble up the DOM tree. The `mouseover` event is triggered when the mouse pointer enters the element or one of its descendants. If a parent element has child elements, and the mouse pointer enters child elements, the `mouseover` event will be triggered on the parent element again as well. If the parent element has multiple child elements, this can result in multiple event callbacks fired. If there are child elements, and the mouse pointer moves from the parent element to the child element, `mouseover` will fire for both the parent and the child.\n\n| Property | `mouseenter` | `mouseover` |\n| --- | --- | --- |\n| Bubbling | No | Yes |\n| Trigger | Only when entering itself | When entering itself and when entering descendants |\n\n<!-- Update here: /questions/what-is-the-difference-between-mouseenter-and-mouseover-event/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-is-the-difference-between-mouseenter-and-mouseover-event?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-mouseenter-and-mouseover-event/en-US.mdx)\n\n<br>\n\n### What is `'use strict';` in JavaScript for?\n\n<!-- Update here: /questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx -->\n\n`'use strict'` is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.\n\n**Advantages**\n\n- Makes it impossible to accidentally create global variables.\n- Makes assignments which would otherwise silently fail to throw an exception.\n- Makes attempts to delete undeletable properties throw an exception (where before the attempt would simply have no effect).\n- Requires that function parameter names be unique.\n- `this` is `undefined` in the global context.\n- It catches some common coding bloopers, throwing exceptions.\n- It disables features that are confusing or poorly thought out.\n\n**Disadvantages**\n\n- Many missing features that some developers might be used to.\n- No more access to `function.caller` and `function.arguments`.\n- Concatenation of scripts written in different strict modes might cause issues.\n\nOverall, the benefits outweigh the disadvantages and there is not really a need to rely on the features that strict mode prohibits. We should all be using strict mode by default.\n\n<!-- Update here: /questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx)\n\n<br>\n\n### Explain the difference between synchronous and asynchronous functions in JavaScript\n\n<!-- Update here: /questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx -->\n\nSynchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. As a result, programs containing only synchronous code are evaluated exactly in order of the statements. The execution of the program is paused if one of the statements take a very long time.\n\n```js live\nfunction sum(a, b) {\n  console.log('Inside sum function');\n  return a + b;\n}\n\nconst result = sum(2, 3); // The program waits for sum() to complete before assigning the result\nconsole.log('Result: ', result); // Output: 5\n```\n\nAsynchronous functions usually accept a callback as a parameter and execution continue on to the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John', age: 30 };\n    callback(data); // Calling the callback function with data\n  }, 2000); // Simulating a 2-second delay\n}\n\nconsole.log('Fetching data...');\n\nfetchData((data) => {\n  console.log(data); // Output: { name: 'John', age: 30 } (after 2 seconds)\n});\n\nconsole.log('Call made to fetch data'); // This will print before the data is fetched\n```\n\n<!-- Update here: /questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/explain-the-difference-between-synchronous-and-asynchronous-functions?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx)\n\n<br>\n\n### What are the pros and cons of using Promises instead of callbacks in JavaScript?\n\n<!-- Update here: /questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/en-US.mdx -->\n\nPromises offer a cleaner alternative to callbacks, helping to avoid callback hell and making asynchronous code more readable. They facilitate writing sequential and parallel asynchronous operations with ease. However, using promises may introduce slightly more complex code.\n\n<!-- Update here: /questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/en-US.mdx)\n\n<br>\n\n### Explain AJAX in as much detail as possible\n\n<!-- Update here: /questions/explain-ajax-in-as-much-detail-as-possible/en-US.mdx -->\n\nAJAX (Asynchronous JavaScript and XML) facilitates asynchronous communication between the client and server, enabling dynamic updates to web pages without reloading. It uses techniques like `XMLHttpRequest` or the `fetch()` API to send and receive data in the background. In modern web applications, the `fetch()` API is more commonly used to implement AJAX.\n\n**Using `XMLHttpRequest`**\n\n```js live\nlet xhr = new XMLHttpRequest();\nxhr.onreadystatechange = function () {\n  if (xhr.readyState === XMLHttpRequest.DONE) {\n    if (xhr.status === 200) {\n      console.log(xhr.responseText);\n    } else {\n      console.error('Request failed: ' + xhr.status);\n    }\n  }\n};\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.send();\n```\n\n**Using `fetch()`**\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Fetch error:', error));\n```\n\n<!-- Update here: /questions/explain-ajax-in-as-much-detail-as-possible/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/explain-ajax-in-as-much-detail-as-possible?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-ajax-in-as-much-detail-as-possible/en-US.mdx)\n\n<br>\n\n### What are the advantages and disadvantages of using AJAX?\n\n<!-- Update here: /questions/what-are-the-advantages-and-disadvantages-of-using-ajax/en-US.mdx -->\n\nAJAX (Asynchronous JavaScript and XML) is a technique in JavaScript that allows web pages to send and retrieve data asynchronously from servers without refreshing or reloading the entire page.\n\n**Advantages**\n\n- **Smoother user experience**: Updates happen without full page reloads, like in mail and chat applications.\n- **Lighter server Load**: Only necessary data is fetched via AJAX, reducing server load and improving perceived performance of webpages.\n- **Maintains client state**: User interactions and any client states are persisted within the page.\n\n**Disadvantages**\n\n- **Reliance on JavaScript**: If disabled, Ajax functionality breaks.\n- **Bookmarking issues**: Dynamic content makes bookmarking specific page states difficult.\n- **SEO Challenges**: Search engines may struggle to index dynamic content.\n- **Performance Concerns**: Processing Ajax data on low-end devices can be slow.\n\n<!-- Update here: /questions/what-are-the-advantages-and-disadvantages-of-using-ajax/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-the-advantages-and-disadvantages-of-using-ajax?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-advantages-and-disadvantages-of-using-ajax/en-US.mdx)\n\n<br>\n\n### What are the differences between `XMLHttpRequest` and `fetch()` in JavaScript and browsers?\n\n<!-- Update here: /questions/what-are-the-differences-between-xmlhttprequest-and-fetch/en-US.mdx -->\n\n`XMLHttpRequest` (XHR) and `fetch()` API are both used for asynchronous HTTP requests in JavaScript (AJAX). `fetch()` offers a cleaner syntax, promise-based approach, and more modern feature set compared to XHR. However, there are some differences:\n\n- `XMLHttpRequest` event callbacks, while `fetch()` utilizes promise chaining.\n- `fetch()` provides more flexibility in headers and request bodies.\n- `fetch()` support cleaner error handling with `catch()`.\n- Handling caching with `XMLHttpRequest` is difficult but caching is supported by `fetch()` by default in the `options.cache` object (`cache` value of second parameter) to `fetch()` or `Request()`.\n- `fetch()` requires an `AbortController` for cancelation, while for `XMLHttpRequest`, it provides `abort()` property.\n- `XMLHttpRequest` has good support for progress tracking, which `fetch()` lacks.\n- `XMLHttpRequest` is only available in the browser and not natively supported in Node.js environments. On the other hand `fetch()` is part of the JavaScript language and is supported on all modern JavaScript runtimes.\n\nThese days `fetch()` is preferred for its cleaner syntax and modern features.\n\n<!-- Update here: /questions/what-are-the-differences-between-xmlhttprequest-and-fetch/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-the-differences-between-xmlhttprequest-and-fetch?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-xmlhttprequest-and-fetch/en-US.mdx)\n\n<br>\n\n### How do you abort a web request using `AbortController` in JavaScript?\n\n<!-- Update here: /questions/how-do-you-abort-a-web-request-using-abortcontrollers/en-US.mdx -->\n\n`AbortController` is used to cancel ongoing asynchronous operations like fetch requests.\n\n```js live\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nfetch('https://jsonplaceholder.typicode.com/todos/1', { signal })\n  .then((response) => {\n    // Handle response\n  })\n  .catch((error) => {\n    if (error.name === 'AbortError') {\n      console.log('Request aborted');\n    } else {\n      console.error('Error:', error);\n    }\n  });\n\n// Call abort() to abort the request\ncontroller.abort();\n```\n\nAborting web requests is useful for:\n\n- Canceling requests based on user actions.\n- Prioritizing the latest requests in scenarios with multiple simultaneous requests.\n- Canceling requests that are no longer needed, e.g. after the user has navigated away from the page.\n\n<!-- Update here: /questions/how-do-you-abort-a-web-request-using-abortcontrollers/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/how-do-you-abort-a-web-request-using-abortcontrollers?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-abort-a-web-request-using-abortcontrollers/en-US.mdx)\n\n<br>\n\n### What are JavaScript polyfills for?\n\n<!-- Update here: /questions/what-are-javascript-polyfills-for/en-US.mdx -->\n\nPolyfills in JavaScript are pieces of code that provide modern functionality to older browsers that lack native support for those features. They bridge the gap between the JavaScript language features and APIs available in modern browsers and the limited capabilities of older browser versions.\n\nThey can be implemented manually or included through libraries and are often used in conjunction with feature detection.\n\nCommon use cases include:\n\n- **New JavaScript Methods**: For example, `Array.prototype.includes()`, `Object.assign()`, etc.\n- **New APIs**: Such as `fetch()`, `Promise`, `IntersectionObserver`, etc. Modern browsers support these now but for a long time they have to be polyfilled.\n\nLibraries and services for polyfills:\n\n- **`core-js`**: A modular standard library for JavaScript which includes polyfills for a wide range of ECMAScript features.\n\n  ```js\n  import 'core-js/actual/array/flat-map'; // With this, Array.prototype.flatMap is available to be used.\n\n  [1, 2].flatMap((it) => [it, it]); // => [1, 1, 2, 2]\n  ```\n\n- **Polyfill.io**: A service that provides polyfills based on the features and user agents specified in the request.\n\n  ```js\n  <script src=\"https://polyfill.io/v3/polyfill.min.js\"></script>\n  ```\n\n<!-- Update here: /questions/what-are-javascript-polyfills-for/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-javascript-polyfills-for?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-polyfills-for/en-US.mdx)\n\n<br>\n\n### Why is extending built-in JavaScript objects not a good idea?\n\n<!-- Update here: /questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/en-US.mdx -->\n\nExtending a built-in/native JavaScript object means adding properties/functions to its `prototype`. While this may seem like a good idea at first, it is dangerous in practice. Imagine your code uses a few libraries that both extend the `Array.prototype` by adding the same `contains` method, the implementations will overwrite each other and your code will have unpredictable behavior if these two methods do not work the same way.\n\nThe only time you may want to extend a native object is when you want to create a polyfill, essentially providing your own implementation for a method that is part of the JavaScript specification but might not exist in the user's browser due to it being an older browser.\n\n<!-- Update here: /questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/why-is-extending-built-in-javascript-objects-not-a-good-idea?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/en-US.mdx)\n\n<br>\n\n### Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?\n\n<!-- Update here: /questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/en-US.mdx -->\n\nJavaScript that is executed in the browser has access to the global scope (the `window` object). In general it's a good software engineering practice to not pollute the global namespace unless you are working on a feature that truly needs to be global – it is needed by the entire page. Several reasons to avoid touching the global scope:\n\n- **Naming conflicts**: Sharing the global scope across scripts can cause conflicts and bugs when new global variables or changes are introduced.\n- **Cluttered global namespace**: Keeping the global namespace minimal avoids making the codebase hard to manage and maintain.\n- **Scope leaks**: Unintentional references to global variables in closures or event handlers can cause memory leaks and performance issues.\n- **Modularity and encapsulation**: Good design promotes keeping variables and functions within their specific scopes, enhancing organization, reusability, and maintainability.\n- **Security concerns**: Global variables are accessible by all scripts, including potentially malicious ones, posing security risks, especially if sensitive data is stored there.\n- **Compatibility and portability**: Heavy reliance on global variables reduces code portability and integration ease with other libraries or frameworks.\n\nFollow these best practices to avoid global scope pollution:\n\n- **Use local variables**: Declare variables within functions or blocks using `var`, `let`, or `const` to limit their scope.\n- **Pass variables as function parameters**: Maintain encapsulation by passing variables as parameters instead of accessing them globally.\n- **Use immediately invoked function expressions (IIFE)**: Create new scopes with IIFEs to prevent adding variables to the global scope.\n- **Use modules**: Encapsulate code with module systems to maintain separate scopes and manageability.\n\n<!-- Update here: /questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/en-US.mdx)\n\n<br>\n\n### Explain the differences between CommonJS modules and ES modules in JavaScript\n\n<!-- Update here: /questions/explain-the-differences-between-commonjs-modules-and-es-modules/en-US.mdx -->\n\nIn JavaScript, modules are reusable pieces of code that encapsulate functionality, making it easier to manage, maintain, and structure your applications. Modules allow you to break down your code into smaller, manageable parts, each with its own scope.\n\n**CommonJS** is an older module system that was initially designed for server-side JavaScript development with Node.js. It uses the `require()` function to load modules and the `module.exports` or `exports` object to define the exports of a module.\n\n```js\n// my-module.js\nconst value = 42;\nmodule.exports = { value };\n\n// main.js\nconst myModule = require('./my-module.js');\nconsole.log(myModule.value); // 42\n```\n\n**ES Modules** (ECMAScript Modules) are the standardized module system introduced in ES6 (ECMAScript 2015). They use the `import` and `export` statements to handle module dependencies.\n\n```js\n// my-module.js\nexport const value = 42;\n\n// main.js\nimport { value } from './my-module.js';\nconsole.log(value); // 42\n```\n\n**CommonJS vs ES modules**\n\n| Feature | CommonJS | ES modules |\n| --- | --- | --- |\n| Module Syntax | `require()` for importing `module.exports` for exporting | `import` for importing `export` for exporting |\n| Environment | Primarily used in Node.js for server-side development | Designed for both browser and server-side JavaScript (Node.js) |\n| Loading | Synchronous loading of modules | Asynchronous loading of modules |\n| Structure | Dynamic imports, can be conditionally called | Static imports/exports at the top level |\n| File extensions | `.js` (default) | `.mjs` or `.js` (with `type: \"module\"` in `package.json`) |\n| Browser support | Not natively supported in browsers | Natively supported in modern browsers |\n| Optimization | Limited optimization due to dynamic nature | Allows for optimizations like tree-shaking due to static structure |\n| Compatibility | Widely used in existing Node.js codebases and libraries | Newer standard, but gaining adoption in modern projects |\n\n<!-- Update here: /questions/explain-the-differences-between-commonjs-modules-and-es-modules/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/explain-the-differences-between-commonjs-modules-and-es-modules?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-differences-between-commonjs-modules-and-es-modules/en-US.mdx)\n\n<br>\n\n### What are the various data types in JavaScript?\n\n<!-- Update here: /questions/what-are-the-various-data-types-in-javascript/en-US.mdx -->\n\nIn JavaScript, data types can be categorized into `primitive` and `non-primitive` types:\n\n**Primitive data types**\n\n- **Number**: Represents both integers and floating-point numbers.\n- **String**: Represents sequences of characters.\n- **Boolean**: Represents `true` or `false` values.\n- **Undefined**: A variable that has been declared but not assigned a value.\n- **Null**: Represents the intentional absence of any object value.\n- **Symbol**: A unique and immutable value used as object property keys. Read more in our [deep dive on `Symbol`s](https://www.greatfrontend.com/questions/quiz/what-are-symbols-used-for)\n- **BigInt**: Represents integers with arbitrary precision.\n\n**Non-primitive (Reference) data types**\n\n- **Object**: Used to store collections of data.\n- **Array**: An ordered collection of data.\n- **Function**: A callable object.\n- **Date**: Represents dates and times.\n- **RegExp**: Represents regular expressions.\n- **Map**: A collection of keyed data items.\n- **Set**: A collection of unique values.\n\nThe primitive types store a single value, while non-primitive types can store collections of data or complex entities.\n\n<!-- Update here: /questions/what-are-the-various-data-types-in-javascript/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-the-various-data-types-in-javascript?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-various-data-types-in-javascript/en-US.mdx)\n\n<br>\n\n### What language constructs do you use for iterating over object properties and array items in JavaScript?\n\n<!-- Update here: /questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx -->\n\nThere are multiple ways to iterate over object properties as well as arrays in JavaScript:\n\n**`for...in` loop**\n\nThe `for...in` loop iterates over all enumerable properties of an object, including inherited enumerable properties. So it is important to have a check if you only want to iterate over object's own properties\n\n```js live\nconst obj = {\n  a: 1,\n  b: 2,\n  c: 3,\n};\n\nfor (const key in obj) {\n  // To avoid iterating over inherited properties\n  if (Object.hasOwn(obj, key)) {\n    console.log(`${key}: ${obj[key]}`);\n  }\n}\n```\n\n**`Object.keys()`**\n\n`Object.keys()` returns an array of the object's own enumerable property names. You can then use a for...of loop or forEach to iterate over this array.\n\n```js live\nconst obj = {\n  a: 1,\n  b: 2,\n  c: 3,\n};\n\nObject.keys(obj).forEach((key) => {\n  console.log(`${key}: ${obj[key]}`);\n});\n```\n\nMost common ways to iterate over array are using `for` loop and `Array.prototype.forEach` method.\n\n**Using `for` loop**\n\n```js live\nlet array = [1, 2, 3, 4, 5, 6];\nfor (let index = 0; index < array.length; index++) {\n  console.log(array[index]);\n}\n```\n\n**Using `Array.prototype.forEach` method**\n\n```js live\nlet array = [1, 2, 3, 4, 5, 6];\narray.forEach((number, index) => {\n  console.log(`${number} at index ${index}`);\n});\n```\n\n**Using `for...of`**\n\nThis method is the newest and most convenient way to iterate over arrays. It automatically iterates over each element without requiring you to manage the index.\n\n```js live\nconst numbers = [1, 2, 3, 4, 5];\n\nfor (const number of numbers) {\n  console.log(number);\n}\n```\n\nThere are also other inbuilt methods available which are suitable for specific scenarios for example:\n\n- `Array.prototype.filter`: You can use the `filter` method to create a new array containing only the elements that satisfy a certain condition.\n- `Array.prototype.map`: You can use the `map` method to create a new array based on the existing one, transforming each element with a provided function.\n- `Array.prototype.reduce`: You can use the `reduce` method to combine all elements into a single value by repeatedly calling a function that takes two arguments: the accumulated value and the current element.\n\n<!-- Update here: /questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx)\n\n<br>\n\n### What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?\n\n<!-- Update here: /questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx -->\n\n**Spread syntax** (`...`) allows an iterable (like an array or string) to be expanded into individual elements. This is often used as a convenient and modern way to create new arrays or objects by combining existing ones.\n\n| Operation      | Traditional                     | Spread                 |\n| -------------- | ------------------------------- | ---------------------- |\n| Array cloning  | `arr.slice()`                   | `[...arr]`             |\n| Array merging  | `arr1.concat(arr2)`             | `[...arr1, ...arr2]`   |\n| Object cloning | `Object.assign({}, obj)`        | `{ ...obj }`           |\n| Object merging | `Object.assign({}, obj1, obj2)` | `{ ...obj1, ...obj2 }` |\n\n**Rest syntax** is the opposite of what spread syntax does. It collects a variable number of arguments into an array. This is often used in function parameters to handle a dynamic number of arguments.\n\n```js live\n// Using rest syntax in a function\nfunction sum(...numbers) {\n  return numbers.reduce((total, num) => total + num, 0);\n}\n\nconsole.log(sum(1, 2, 3)); // Output: 6\n```\n\n<!-- Update here: /questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx)\n\n<br>\n\n### What are iterators and generators in JavaScript and what are they used for?\n\n<!-- Update here: /questions/what-are-iterators-and-generators-and-what-are-they-used-for/en-US.mdx -->\n\nIn JavaScript, iterators and generators are powerful tools for managing sequences of data and controlling the flow of execution in a more flexible way.\n\n**Iterators** are objects that define a sequence and potentially a return value upon its termination. It adheres to a specific interface:\n\n- An iterator object must implement a `next()` method.\n- The `next()` method returns an object with two properties:\n  - `value`: The next value in the sequence.\n  - `done`: A boolean that is `true` if the iterator has finished its sequence, otherwise `false`.\n\nHere's an example of an object implementing the iterator interface.\n\n```js live\nconst iterator = {\n  current: 0,\n  last: 5,\n  next() {\n    if (this.current <= this.last) {\n      return { value: this.current++, done: false };\n    } else {\n      return { value: undefined, done: true };\n    }\n  },\n};\n\nlet result = iterator.next();\nwhile (!result.done) {\n  console.log(result.value); // Logs 0, 1, 2, 3, 4, 5\n  result = iterator.next();\n}\n```\n\n**Generators** are a special functions that **can pause execution and resume at a later point**. It uses the `function*` syntax and the `yield` keyword to control the flow of execution. When you call a generator function, it doesn't execute completely like a regular function. Instead, it returns an iterator object. Calling the `next()` method on the returned iterator advances the generator to the next `yield` statement, and the value after `yield` becomes the return value of `next()`.\n\n```js live\nfunction* numberGenerator() {\n  let num = 0;\n  while (num <= 5) {\n    yield num++;\n  }\n}\n\nconst gen = numberGenerator();\nconsole.log(gen.next()); // { value: 0, done: false }\nconsole.log(gen.next()); // { value: 1, done: false }\nconsole.log(gen.next()); // { value: 2, done: false }\nconsole.log(gen.next()); // { value: 3, done: false }\nconsole.log(gen.next()); // { value: 4, done: false }\nconsole.log(gen.next()); // { value: 5, done: false }\nconsole.log(gen.next()); // { value: undefined, done: true }\n```\n\nGenerators are powerful for creating iterators on-demand, especially for infinite sequences or complex iteration logic. They can be used for:\n\n- Lazy evaluation – processing elements only when needed, improving memory efficiency for large datasets.\n- Implementing iterators for custom data structures.\n- Creating asynchronous iterators for handling data streams.\n\n<!-- Update here: /questions/what-are-iterators-and-generators-and-what-are-they-used-for/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-iterators-and-generators-and-what-are-they-used-for?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-iterators-and-generators-and-what-are-they-used-for/en-US.mdx)\n\n<br>\n\n### Explain the difference between mutable and immutable objects in JavaScript\n\n<!-- Update here: /questions/explain-the-difference-between-mutable-and-immutable-objects/en-US.mdx -->\n\n**Mutable objects** allow for modification of properties and values after creation, which is the default behavior for most objects.\n\n```js live\nconst mutableObject = {\n  name: 'John',\n  age: 30,\n};\n\n// Modify the object\nmutableObject.name = 'Jane';\n\n// The object has been modified\nconsole.log(mutableObject); // Output: { name: 'Jane', age: 30 }\n```\n\n**Immutable objects** cannot be directly modified after creation. Its content cannot be changed without creating an entirely new value.\n\n```js live\nconst immutableObject = Object.freeze({\n  name: 'John',\n  age: 30,\n});\n\n// Attempt to modify the object\nimmutableObject.name = 'Jane';\n\n// The object remains unchanged\nconsole.log(immutableObject); // Output: { name: 'John', age: 30 }\n```\n\nThe key difference between mutable and immutable objects is modifiability. Immutable objects cannot be modified after they are created, while mutable objects can be.\n\n<!-- Update here: /questions/explain-the-difference-between-mutable-and-immutable-objects/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/explain-the-difference-between-mutable-and-immutable-objects?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-mutable-and-immutable-objects/en-US.mdx)\n\n<br>\n\n### What is the difference between a `Map` object and a plain object in JavaScript?\n\n<!-- Update here: /questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/en-US.mdx -->\n\nBoth `Map` objects and plain objects in JavaScript can store key-value pairs, but they have several key differences:\n\n| Feature | `Map` | Plain object |\n| --- | --- | --- |\n| Key type | Any data type | String (or Symbol) |\n| Key order | Maintained | Not guaranteed |\n| Size property | Yes (`size`) | None |\n| Iteration | `forEach`, `keys()`, `values()`, `entries()` | `for...in`, `Object.keys()`, etc. |\n| Inheritance | No | Yes |\n| Performance | Generally better for larger datasets and frequent additions/deletions | Faster for small datasets and simple operations |\n| Serializable | No | Yes |\n\n<!-- Update here: /questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/en-US.mdx)\n\n<br>\n\n### What are the differences between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript?\n\n<!-- Update here: /questions/what-are-the-differences-between-map-set-and-weakmap-weakset/en-US.mdx -->\n\nThe primary difference between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript lies in how they handle keys. Here's a breakdown:\n\n**`Map` vs. `WeakMap`**\n\n`Map`s allows any data type (strings, numbers, objects) as keys. The key-value pairs remain in memory as long as the `Map` object itself is referenced. Thus they are suitable for general-purpose key-value storage where you want to maintain references to both keys and values. Common use cases include storing user data, configuration settings, or relationships between objects.\n\n`WeakMap`s only allows objects as keys. However, these object keys are held weakly. This means the garbage collector can remove them from memory even if the `WeakMap` itself still exists, as long as there are no other references to those objects. `WeakMap`s are ideal for scenarios where you want to associate data with objects without preventing those objects from being garbage collected. This can be useful for things like:\n\n- Caching data based on objects without preventing garbage collection of the objects themselves.\n- Storing private data associated with DOM nodes without affecting their lifecycle.\n\n**`Set` vs. `WeakSet`**\n\nSimilar to `Map`, `Set`s allow any data type as keys. The elements within a `Set` must be unique. `Set`s are useful for storing unique values and checking for membership efficiently. Common use cases include removing duplicates from arrays or keeping track of completed tasks.\n\nOn the other hand, `WeakSet` only allows objects as elements, and these object elements are held weakly, similar to `WeakMap` keys. `WeakSet`s are less commonly used, but applicable when you want a collection of unique objects without affecting their garbage collection. This might be necessary for:\n\n- Tracking DOM nodes that have been interacted with without affecting their memory management.\n- Implementing custom object weak references for specific use cases.\n\n**Here's a table summarizing the key differences:**\n\n| Feature | Map | WeakMap | Set | WeakSet |\n| --- | --- | --- | --- | --- |\n| Key Types | Any data type | Objects (weak references) | Any data type (unique) | Objects (weak references, unique) |\n| Garbage Collection | Keys and values are not garbage collected | Keys can be garbage collected if not referenced elsewhere | Elements are not garbage collected | Elements can be garbage collected if not referenced elsewhere |\n| Use Cases | General-purpose key-value storage | Caching, private DOM node data | Removing duplicates, membership checks | Object weak references, custom use cases |\n\n**Choosing between them**\n\n- Use `Map` and `Set` for most scenarios where you need to store key-value pairs or unique elements and want to maintain references to both the keys/elements and the values.\n- Use `WeakMap` and `WeakSet` cautiously in specific situations where you want to associate data with objects without affecting their garbage collection. Be aware of the implications of weak references and potential memory leaks if not used correctly.\n\n<!-- Update here: /questions/what-are-the-differences-between-map-set-and-weakmap-weakset/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-the-differences-between-map-set-and-weakmap-weakset?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-map-set-and-weakmap-weakset/en-US.mdx)\n\n<br>\n\n### Why might you want to create static class members in JavaScript?\n\n<!-- Update here: /questions/why-you-might-want-to-create-static-class-members/en-US.mdx -->\n\nStatic class members (properties/methods) has a `static` keyword prepended. Such members cannot be directly accessed on instances of the class. Instead, they're accessed on the class itself.\n\n```js live\nclass Car {\n  static noOfWheels = 4;\n  static compare() {\n    return 'Static method has been called.';\n  }\n}\n\nconsole.log(Car.noOfWheels); // 4\n```\n\nStatic members are useful under the following scenarios:\n\n- **Namespace organization**: Static properties can be used to define constants or configuration values that are specific to a class. This helps organize related data within the class namespace and prevents naming conflicts with other variables. Examples include `Math.PI`, `Math.SQRT2`.\n- **Helper functions**: Static methods can be used as helper functions that operate on the class itself or its instances. This can improve code readability and maintainability by separating utility logic from the core functionality of the class. Examples of frequently used static methods include `Object.assign()`, `Math.max()`.\n- **Singleton pattern**: In some rare cases, static properties and methods can be used to implement a singleton pattern, where only one instance of a class ever exists. However, this pattern can be tricky to manage and is generally discouraged in favor of more modern dependency injection techniques.\n\n<!-- Update here: /questions/why-you-might-want-to-create-static-class-members/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/why-you-might-want-to-create-static-class-members?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-you-might-want-to-create-static-class-members/en-US.mdx)\n\n<br>\n\n### What are `Symbol`s used for in JavaScript?\n\n<!-- Update here: /questions/what-are-symbols-used-for/en-US.mdx -->\n\n`Symbol`s in JavaScript are a new primitive data type introduced in ES6 (ECMAScript 2015). They are unique and immutable identifiers that is primarily for object property keys to avoid name collisions. These values can be created using `Symbol(...)` function, and each `Symbol` value is guaranteed to be unique, even if they have the same key/description. `Symbol` properties are not enumerable in `for...in` loops or `Object.keys()`, making them suitable for creating private/internal object state.\n\n```js live\nlet sym1 = Symbol();\nlet sym2 = Symbol('myKey');\n\nconsole.log(typeof sym1); // \"symbol\"\nconsole.log(sym1 === sym2); // false, because each symbol is unique\n\nlet obj = {};\nlet sym = Symbol('uniqueKey');\n\nobj[sym] = 'value';\nconsole.log(obj[sym]); // \"value\"\n```\n\n**Note**: The `Symbol()` function must be called without the `new` keyword. It is not exactly a constructor because it can only be called as a function instead of with `new Symbol()`.\n\n<!-- Update here: /questions/what-are-symbols-used-for/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-symbols-used-for?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-symbols-used-for/en-US.mdx)\n\n<br>\n\n### What are server-sent events?\n\n<!-- Update here: /questions/what-are-server-sent-events/en-US.mdx -->\n\n[Server-sent events (SSE)](https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface) is a standard that allows a web page to receive automatic updates from a server via an HTTP connection. Server-sent events are used with `EventSource` instances that opens a connection with a server and allows client to receive events from the server. Connections created by server-sent events are persistent (similar to the `WebSocket`s), however there are a few differences:\n\n| Property | `WebSocket` | `EventSource` |\n| --- | --- | --- |\n| Direction | Bi-directional – both client and server can exchange messages | Unidirectional – only server sends data |\n| Data type | Binary and text data | Only text |\n| Protocol | WebSocket protocol (`ws://`) | Regular HTTP (`http://`) |\n\n**Creating an event source**\n\n```js\nconst eventSource = new EventSource('/sse-stream');\n```\n\n**Listening for events**\n\n```js\n// Fired when the connection is established.\neventSource.addEventListener('open', () => {\n  console.log('Connection opened');\n});\n\n// Fired when a message is received from the server.\neventSource.addEventListener('message', (event) => {\n  console.log('Received message:', event.data);\n});\n\n// Fired when an error occurs.\neventSource.addEventListener('error', (error) => {\n  console.error('Error occurred:', error);\n});\n```\n\n**Sending events from server**\n\n```js\nconst express = require('express');\nconst app = express();\n\napp.get('/sse-stream', (req, res) => {\n  // `Content-Type` need to be set to `text/event-stream`.\n  res.setHeader('Content-Type', 'text/event-stream');\n  res.setHeader('Cache-Control', 'no-cache');\n  res.setHeader('Connection', 'keep-alive');\n\n  // Each message should be prefixed with data.\n  const sendEvent = (data) => res.write(`data: ${data}\\n\\n`);\n\n  sendEvent('Hello from server');\n\n  const intervalId = setInterval(() => sendEvent(new Date().toString()), 1000);\n\n  res.on('close', () => {\n    console.log('Client closed connection');\n    clearInterval(intervalId);\n  });\n});\n\napp.listen(3000, () => console.log('Server started on port 3000'));\n```\n\nIn this example, the server sends a \"Hello from server\" message initially, and then sends the current date every second. The connection is kept alive until the client closes it\n\n<!-- Update here: /questions/what-are-server-sent-events/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-server-sent-events?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-server-sent-events/en-US.mdx)\n\n<br>\n\n### What are JavaScript object property flags and descriptors?\n\n<!-- Update here: /questions/what-are-javascript-object-property-flags-and-descriptors/en-US.mdx -->\n\nIn JavaScript, property flags and descriptors manage the behavior and attributes of object properties.\n\n**Property flags**\n\nProperty flags are used to specify the behavior of a property on an object. Here are the available flags:\n\n- `writable`: Specifies whether the property can be written to. Defaults to `true`.\n- `enumerable`: Specifies whether the property is enumerable. Defaults to `true`.\n- `configurable`: Specifies whether the property can be deleted or its attributes changed. Default is `true`.\n\n**Property descriptors**\n\nThese provide detailed information about an object's property, including its value and flags. They are retrieved using `Object.getOwnPropertyDescriptor()` and set using `Object.defineProperty()`.\n\nThe use cases of property descriptors are as follows:\n\n- Making a property non-writable by setting `writable: false` to ensure data consistency.\n- Hiding a property from enumeration by setting `enumerable: false`.\n- Preventing property deletion and modification by setting `configurable: false`.\n- Freezing or sealing objects to prevent modifications globally.\n\n<!-- Update here: /questions/what-are-javascript-object-property-flags-and-descriptors/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-javascript-object-property-flags-and-descriptors?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-object-property-flags-and-descriptors/en-US.mdx)\n\n<br>\n\n### What are JavaScript object getters and setters for?\n\n<!-- Update here: /questions/what-are-javascript-object-getters-and-setters-for/en-US.mdx -->\n\nJavaScript object getters and setters are used to control access to an object's properties. They provide a way to encapsulate the implementation details of a property and define custom behavior when getting or setting its value.\n\nGetters and setters are defined using the `get` and `set` keywords, respectively, followed by a function that is executed when the property is accessed or assigned a new value.\n\nHere's a code example demonstrating the use of getters and setters:\n\n```js live\nconst person = {\n  _name: 'John Doe', // Private property\n\n  get name() {\n    // Getter\n    return this._name;\n  },\n  set name(newName) {\n    // Setter\n    if (newName.trim().length > 0) {\n      this._name = newName;\n    } else {\n      console.log('Invalid name');\n    }\n  },\n};\n\n// Accessing the name property using the getter\nconsole.log(person.name); // Output: 'John Doe'\n\n// Setting the name property using the setter\nperson.name = 'Jane Smith'; // Setter is called\nconsole.log(person.name); // Output: 'Jane Smith'\n\nperson.name = ''; // Setter is called, but the value is not set due to validation\nconsole.log(person.name); // Output: 'Jane Smith'\n```\n\n<!-- Update here: /questions/what-are-javascript-object-getters-and-setters-for/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-javascript-object-getters-and-setters-for?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-object-getters-and-setters-for/en-US.mdx)\n\n<br>\n\n### What are proxies in JavaScript used for?\n\n<!-- Update here: /questions/what-are-proxies-in-javascript-used-for/en-US.mdx -->\n\nIn JavaScript, a proxy is an object that acts as an intermediary between an object and the code. Proxies are used to intercept and customize the fundamental operations of JavaScript objects, such as property access, assignment, function invocation, and more.\n\nHere's a basic example of using a `Proxy` to log every property access:\n\n```js live\nconst myObject = {\n  name: 'John',\n  age: 42,\n};\n\nconst handler = {\n  get: function (target, prop, receiver) {\n    console.log(`Someone accessed property \"${prop}\"`);\n    return target[prop];\n  },\n};\n\nconst proxiedObject = new Proxy(myObject, handler);\n\nconsole.log(proxiedObject.name);\n// Someone accessed property \"name\"\n// 'John'\n\nconsole.log(proxiedObject.age);\n// Someone accessed property \"age\"\n// 42\n```\n\nUse cases include:\n\n- **Property access interception**: Intercept and customize property access on an object.\n  - **Property assignment validation**: Validate property values before they are set on the target object.\n  - **Logging and debugging**: Create wrappers for logging and debugging interactions with an object\n  - **Creating reactive systems**: Trigger updates in other parts of your application when object properties change (data binding).\n  - **Data transformation**: Transforming data being set or retrieved from an object.\n  - **Mocking and stubbing in tests**: Create mock or stub objects for testing purposes, allowing you to isolate dependencies and focus on the unit under test\n- **Function invocation interception**: Used to cache and return the result of frequently accessed methods if they involve network calls or computationally intensive logic, improving performance\n- **Dynamic property creation**: Useful for defining properties on-the-fly with default values and avoid storing redundant data in objects.\n\n<!-- Update here: /questions/what-are-proxies-in-javascript-used-for/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-proxies-in-javascript-used-for?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-proxies-in-javascript-used-for/en-US.mdx)\n\n<br>\n\n### What tools and techniques do you use for debugging JavaScript code?\n\n<!-- Update here: /questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/en-US.mdx -->\n\nSome of the most commonly used tools and techniques for debugging JavaScript:\n\n- JavaScript language\n  - `console` methods (e.g. `console.log()`, `console.error()`, `console.warn()`, `console.table()`)\n  - `debugger` statement\n- Breakpoints (browser or IDE)\n- JavaScript frameworks\n  - [React Devtools](https://github.com/facebook/react-devtools)\n  - [Redux Devtools](https://github.com/gaearon/redux-devtools)\n  - [Vue Devtools](https://github.com/vuejs/vue-devtools)\n- Browser developer tools\n  - **Chrome DevTools**: The most widely used tool for debugging JavaScript. It provides a rich set of features including the ability to set breakpoints, inspect variables, view the call stack, and more.\n  - **Firefox Developer Tools**: Similar to Chrome DevTools with its own set of features for debugging.\n  - **Safari Web Inspector**: Provides tools for debugging on Safari.\n  - **Edge Developer Tools**: Similar to Chrome DevTools, as Edge is now Chromium-based.\n- Network requests\n  - **Postman**: Useful for debugging API calls.\n  - **Fiddler**: Helps capture and inspect HTTP/HTTPS traffic.\n  - **Charles Proxy**: Another tool for intercepting and debugging network calls.\n\n<!-- Update here: /questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-tools-and-techniques-do-you-use-for-debugging-javascript-code?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/en-US.mdx)\n\n<br>\n\n### What are workers in JavaScript used for?\n\n<!-- Update here: /questions/what-are-workers-in-javascript-used-for/en-US.mdx -->\n\nWorkers in JavaScript are background threads that allow you to run scripts in parallel with the main execution thread, without blocking or interfering with the user interface. Their key features include:\n\n- **Parallel processing**: Workers run in a separate thread from the main thread, allowing your web page to remain responsive to user interactions while the worker performs its tasks. It's useful for moving CPU-intensive work off the main thread and be free from JavaScript's single-threaded nature.\n- **Communication**: Uses `postMessage()` and `onmessage`/ `'message'` event for messaging.\n- **Access to web APIs**: Workers have access to various Web APIs, including `fetch()`, IndexedDB, and Web Storage, allowing them to perform tasks like data fetching and persisting data independently.\n- **No DOM access**: Workers cannot directly manipulate the DOM, thus cannot interact with the UI, ensuring they don't accidentally interfere with the main thread's operation.\n\nThere are three main types of workers in JavaScript:\n\n- **Web workers / Dedicated workers**\n  - Run scripts in background threads, separate from the main UI thread.\n  - Useful for CPU-intensive tasks like data processing, calculations, etc.\n  - Cannot directly access or manipulate the DOM.\n- **Service workers**\n  - Act as network proxies, handling requests between the app and network.\n  - Enable offline functionality, caching, and push notifications.\n  - Runs independently of the web page, even when it's closed.\n- **Shared workers**\n  - Can be shared by multiple scripts running in different windows or frames, as long as they're in the same domain.\n  - Scripts communicate with the shared worker by sending and receiving messages.\n  - Useful for coordinating tasks across different parts of a web page.\n\n<!-- Update here: /questions/what-are-workers-in-javascript-used-for/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/what-are-workers-in-javascript-used-for?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-workers-in-javascript-used-for/en-US.mdx)\n\n<br>\n\n### How does JavaScript garbage collection work?\n\n<!-- Update here: /questions/how-does-javascript-garbage-collection-work/en-US.mdx -->\n\nGarbage collection in JavaScript is an automatic memory management mechanism that reclaims memory occupied by objects and variables that are no longer in use by the program. The two most common algorithms are mark-and-sweep and generational garbage collection.\n\n**Mark-and-sweep**\n\nThe most common garbage collection algorithm used in JavaScript is the Mark-and-sweep algorithm. It operates in two phases:\n\n- **Marking phase**: The garbage collector traverses the object graph, starting from the root objects (global variables, currently executing functions, etc.), and marks all reachable objects as \"in-use\".\n- **Sweeping phase**: The garbage collector sweeps through memory, removing all unmarked objects, as they are considered unreachable and no longer needed.\n\nThis algorithm effectively identifies and removes objects that have become unreachable, freeing up memory for new allocations.\n\n**Generational garbage collection**\n\nLeveraged by modern JavaScript engines, objects are divided into different generations based on their age and usage patterns. Frequently accessed objects are moved to younger generations, while less frequently used objects are promoted to older generations. This optimization reduces the overhead of garbage collection by focusing on the younger generations, where most objects are short-lived.\n\nDifferent JavaScript engines (differs according to browsers) implement different garbage collection algorithms and there's no standard way of doing garbage collection.\n\n<!-- Update here: /questions/how-does-javascript-garbage-collection-work/en-US.mdx -->\n\n<br>\n    \n> Read the [detailed answer](https://www.greatfrontend.com/questions/quiz/how-does-javascript-garbage-collection-work?language=js&tab=quiz) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n\n[Back to top ↑](#table-of-contents-top-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-does-javascript-garbage-collection-work/en-US.mdx)\n\n<br>\n\n\n<!-- QUESTIONS:TOP:END -->\n\n## All Questions with Answers\n\n<!-- QUESTIONS:ALL:START -->\n\n### What are the various data types in JavaScript?\n\n<!-- Update here: /questions/what-are-the-various-data-types-in-javascript/en-US.mdx -->\n\nIn JavaScript, data types can be categorized into `primitive` and `non-primitive` types:\n\n**Primitive data types**\n\n- **Number**: Represents both integers and floating-point numbers.\n- **String**: Represents sequences of characters.\n- **Boolean**: Represents `true` or `false` values.\n- **Undefined**: A variable that has been declared but not assigned a value.\n- **Null**: Represents the intentional absence of any object value.\n- **Symbol**: A unique and immutable value used as object property keys. Read more in our [deep dive on `Symbol`s](https://www.greatfrontend.com/questions/quiz/what-are-symbols-used-for)\n- **BigInt**: Represents integers with arbitrary precision.\n\n**Non-primitive (Reference) data types**\n\n- **Object**: Used to store collections of data.\n- **Array**: An ordered collection of data.\n- **Function**: A callable object.\n- **Date**: Represents dates and times.\n- **RegExp**: Represents regular expressions.\n- **Map**: A collection of keyed data items.\n- **Set**: A collection of unique values.\n\nThe primitive types store a single value, while non-primitive types can store collections of data or complex entities.\n\n<!-- Update here: /questions/what-are-the-various-data-types-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-various-data-types-in-javascript/en-US.mdx)\n\n<br>\n\n### How do you check the data type of a variable?\n\n<!-- Update here: /questions/how-do-you-check-the-data-type-of-a-variable/en-US.mdx -->\n\nTo check the data type of a variable in JavaScript, you can use the `typeof` operator. For example, `typeof variableName` will return a string indicating the type of the variable, such as `\"string\"`, `\"number\"`, `\"boolean\"`, `\"object\"`, `\"function\"`, `\"undefined\"`, or `\"symbol\"`. For arrays and `null`, you can use `Array.isArray(variableName)` and `variableName === null`, respectively.\n\n<!-- Update here: /questions/how-do-you-check-the-data-type-of-a-variable/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-check-the-data-type-of-a-variable/en-US.mdx)\n\n<br>\n\n### What's the difference between a JavaScript variable that is: `null`, `undefined` or undeclared?\n\n<!-- Update here: /questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx -->\n\n| Trait | `null` | `undefined` | Undeclared |\n| --- | --- | --- | --- |\n| Meaning | Explicitly set by the developer to indicate that a variable has no value | Variable has been declared but not assigned a value | Variable has not been declared at all |\n| Type (via `typeof` operator) | `'object'` | `'undefined'` | `'undefined'` |\n| Equality Comparison | `null == undefined` is `true` | `undefined == null` is `true` | Throws a `ReferenceError` |\n\n<!-- Update here: /questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx)\n\n<br>\n\n### What are the differences between JavaScript variables created using `let`, `var` or `const`?\n\n<!-- Update here: /questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx -->\n\nIn JavaScript, `let`, `var`, and `const` are all keywords used to declare variables, but they differ significantly in terms of scope, initialization rules, whether they can be redeclared or reassigned and the behavior when they are accessed before declaration:\n\n| Behavior | `var` | `let` | `const` |\n| --- | --- | --- | --- |\n| Scope | Function or Global | Block | Block |\n| Initialization | Optional | Optional | Required |\n| Redeclaration | Yes | No | No |\n| Reassignment | Yes | Yes | No |\n| Accessing before declaration | `undefined` | `ReferenceError` | `ReferenceError` |\n\n<!-- Update here: /questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx)\n\n<br>\n\n### Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?\n\n<!-- Update here: /questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/en-US.mdx -->\n\nJavaScript that is executed in the browser has access to the global scope (the `window` object). In general it's a good software engineering practice to not pollute the global namespace unless you are working on a feature that truly needs to be global – it is needed by the entire page. Several reasons to avoid touching the global scope:\n\n- **Naming conflicts**: Sharing the global scope across scripts can cause conflicts and bugs when new global variables or changes are introduced.\n- **Cluttered global namespace**: Keeping the global namespace minimal avoids making the codebase hard to manage and maintain.\n- **Scope leaks**: Unintentional references to global variables in closures or event handlers can cause memory leaks and performance issues.\n- **Modularity and encapsulation**: Good design promotes keeping variables and functions within their specific scopes, enhancing organization, reusability, and maintainability.\n- **Security concerns**: Global variables are accessible by all scripts, including potentially malicious ones, posing security risks, especially if sensitive data is stored there.\n- **Compatibility and portability**: Heavy reliance on global variables reduces code portability and integration ease with other libraries or frameworks.\n\nFollow these best practices to avoid global scope pollution:\n\n- **Use local variables**: Declare variables within functions or blocks using `var`, `let`, or `const` to limit their scope.\n- **Pass variables as function parameters**: Maintain encapsulation by passing variables as parameters instead of accessing them globally.\n- **Use immediately invoked function expressions (IIFE)**: Create new scopes with IIFEs to prevent adding variables to the global scope.\n- **Use modules**: Encapsulate code with module systems to maintain separate scopes and manageability.\n\n<!-- Update here: /questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/en-US.mdx)\n\n<br>\n\n### How do you convert a string to a number in JavaScript?\n\n<!-- Update here: /questions/how-do-you-convert-a-string-to-a-number-in-javascript/en-US.mdx -->\n\nIn JavaScript, you can convert a string to a number using several methods. The most common ones are `Number()`, `parseInt()`, `parseFloat()`, and the unary plus operator (`+`). For example, `Number(\"123\")` converts the string `\"123\"` to the number `123`, and `parseInt(\"123.45\")` converts the string `\"123.45\"` to the integer `123`.\n\n<!-- Update here: /questions/how-do-you-convert-a-string-to-a-number-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-convert-a-string-to-a-number-in-javascript/en-US.mdx)\n\n<br>\n\n### What are template literals and how are they used?\n\n<!-- Update here: /questions/what-are-template-literals-and-how-are-they-used/en-US.mdx -->\n\nTemplate literals are a feature in JavaScript that allow for easier string interpolation and multi-line strings. They are enclosed by backticks (`` ` ``) instead of single or double quotes. You can embed expressions within template literals using `${expression}` syntax.\n\nExample:\n\n```js live\nconst myName = 'John';\nconst greeting = `Hello, ${myName}!`;\nconsole.log(greeting); // Output: Hello, John!\n```\n\n<!-- Update here: /questions/what-are-template-literals-and-how-are-they-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-template-literals-and-how-are-they-used/en-US.mdx)\n\n<br>\n\n### Explain the concept of tagged templates\n\n<!-- Update here: /questions/explain-the-concept-of-tagged-templates/en-US.mdx -->\n\nTagged templates in JavaScript allow you to parse template literals with a function. The function receives the literal strings and the values as arguments, enabling custom processing of the template. For example:\n\n```js live\nfunction tag(strings, ...values) {\n  return strings[0] + values[0] + strings[1] + values[1] + strings[2];\n}\n\nconst result = tag`Hello ${'world'}! How are ${'you'}?`;\nconsole.log(result); // \"Hello world! How are you?\"\n```\n\n<!-- Update here: /questions/explain-the-concept-of-tagged-templates/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-tagged-templates/en-US.mdx)\n\n<br>\n\n### What is the spread operator and how is it used?\n\n<!-- Update here: /questions/what-is-the-spread-operator-and-how-is-it-used/en-US.mdx -->\n\nThe spread operator, represented by three dots (`...`), is used in JavaScript to expand iterable objects like arrays or strings into individual elements. It can also be used to spread object properties. For example, you can use it to combine arrays, copy arrays, or pass array elements as arguments to a function.\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\nconst combined = [...arr1, ...arr2];\nconsole.log(combined); // [1, 2, 3, 4, 5, 6]\n\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { c: 3, d: 4 };\nconst combinedObj = { ...obj1, ...obj2 };\nconsole.log(combinedObj); // { a: 1, b: 2, c: 3, d: 4 }\n```\n\n<!-- Update here: /questions/what-is-the-spread-operator-and-how-is-it-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-spread-operator-and-how-is-it-used/en-US.mdx)\n\n<br>\n\n### What are `Symbol`s used for in JavaScript?\n\n<!-- Update here: /questions/what-are-symbols-used-for/en-US.mdx -->\n\n`Symbol`s in JavaScript are a new primitive data type introduced in ES6 (ECMAScript 2015). They are unique and immutable identifiers that is primarily for object property keys to avoid name collisions. These values can be created using `Symbol(...)` function, and each `Symbol` value is guaranteed to be unique, even if they have the same key/description. `Symbol` properties are not enumerable in `for...in` loops or `Object.keys()`, making them suitable for creating private/internal object state.\n\n```js live\nlet sym1 = Symbol();\nlet sym2 = Symbol('myKey');\n\nconsole.log(typeof sym1); // \"symbol\"\nconsole.log(sym1 === sym2); // false, because each symbol is unique\n\nlet obj = {};\nlet sym = Symbol('uniqueKey');\n\nobj[sym] = 'value';\nconsole.log(obj[sym]); // \"value\"\n```\n\n**Note**: The `Symbol()` function must be called without the `new` keyword. It is not exactly a constructor because it can only be called as a function instead of with `new Symbol()`.\n\n<!-- Update here: /questions/what-are-symbols-used-for/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-symbols-used-for/en-US.mdx)\n\n<br>\n\n### What are proxies in JavaScript used for?\n\n<!-- Update here: /questions/what-are-proxies-in-javascript-used-for/en-US.mdx -->\n\nIn JavaScript, a proxy is an object that acts as an intermediary between an object and the code. Proxies are used to intercept and customize the fundamental operations of JavaScript objects, such as property access, assignment, function invocation, and more.\n\nHere's a basic example of using a `Proxy` to log every property access:\n\n```js live\nconst myObject = {\n  name: 'John',\n  age: 42,\n};\n\nconst handler = {\n  get: function (target, prop, receiver) {\n    console.log(`Someone accessed property \"${prop}\"`);\n    return target[prop];\n  },\n};\n\nconst proxiedObject = new Proxy(myObject, handler);\n\nconsole.log(proxiedObject.name);\n// Someone accessed property \"name\"\n// 'John'\n\nconsole.log(proxiedObject.age);\n// Someone accessed property \"age\"\n// 42\n```\n\nUse cases include:\n\n- **Property access interception**: Intercept and customize property access on an object.\n  - **Property assignment validation**: Validate property values before they are set on the target object.\n  - **Logging and debugging**: Create wrappers for logging and debugging interactions with an object\n  - **Creating reactive systems**: Trigger updates in other parts of your application when object properties change (data binding).\n  - **Data transformation**: Transforming data being set or retrieved from an object.\n  - **Mocking and stubbing in tests**: Create mock or stub objects for testing purposes, allowing you to isolate dependencies and focus on the unit under test\n- **Function invocation interception**: Used to cache and return the result of frequently accessed methods if they involve network calls or computationally intensive logic, improving performance\n- **Dynamic property creation**: Useful for defining properties on-the-fly with default values and avoid storing redundant data in objects.\n\n<!-- Update here: /questions/what-are-proxies-in-javascript-used-for/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-proxies-in-javascript-used-for/en-US.mdx)\n\n<br>\n\n### Explain the concept of \"hoisting\" in JavaScript\n\n<!-- Update here: /questions/explain-hoisting/en-US.mdx -->\n\nHoisting is a JavaScript mechanism where variable and function declarations are moved (\"hoisted\") to the top of their containing scope during the compile phase.\n\n- **Variable declarations (`var`)**: Declarations are hoisted, but not initializations. The value of the variable is `undefined` if accessed before initialization.\n- **Variable declarations (`let` and `const`)**: Declarations are hoisted, but not initialized. Accessing them results in `ReferenceError` until the actual declaration is encountered.\n- **Function expressions (`var`)**: Declarations are hoisted, but not initializations. The value of the variable is `undefined` if accessed before initialization.\n- **Function declarations (`function`)**: Both declaration and definition are fully hoisted.\n- **Class declarations (`class`)**: Declarations are hoisted, but not initialized. Accessing them results in `ReferenceError` until the actual declaration is encountered.\n- **Import declarations (`import`)**: Declarations are hoisted, and side effects of importing the module are executed before the rest of the code.\n\nThe following behavior summarizes the result of accessing the variables before they are declared.\n\n| Declaration                    | Accessing before declaration |\n| ------------------------------ | ---------------------------- |\n| `var foo`                      | `undefined`                  |\n| `let foo`                      | `ReferenceError`             |\n| `const foo`                    | `ReferenceError`             |\n| `class Foo`                    | `ReferenceError`             |\n| `var foo = function() { ... }` | `undefined`                  |\n| `function foo() { ... }`       | Normal                       |\n| `import`                       | Normal                       |\n\n<!-- Update here: /questions/explain-hoisting/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-hoisting/en-US.mdx)\n\n<br>\n\n### Explain the difference in hoisting between `var`, `let`, and `const`\n\n<!-- Update here: /questions/explain-the-difference-in-hoisting-between-var-let-and-const/en-US.mdx -->\n\n`var` declarations are hoisted to the top of their scope and initialized with `undefined`, allowing them to be used before their declaration. `let` and `const` declarations are also hoisted but are not initialized, resulting in a `ReferenceError` if accessed before their declaration. `const` additionally requires an initial value at the time of declaration.\n\n<!-- Update here: /questions/explain-the-difference-in-hoisting-between-var-let-and-const/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-in-hoisting-between-var-let-and-const/en-US.mdx)\n\n<br>\n\n### How does hoisting affect function declarations and expressions?\n\n<!-- Update here: /questions/how-does-hoisting-affect-function-declarations-and-expressions/en-US.mdx -->\n\nHoisting in JavaScript means that function declarations are moved to the top of their containing scope during the compile phase, making them available throughout the entire scope. This allows you to call a function before it is defined in the code. However, function expressions are not hoisted in the same way. If you try to call a function expression before it is defined, you will get an error because the variable holding the function is hoisted but not its assignment.\n\n```js live\n// Function declaration\nconsole.log(foo()); // Works fine\nfunction foo() {\n  return 'Hello';\n}\n\n// Function expression\nconsole.log(bar()); // Throws TypeError: bar is not a function\nvar bar = function () {\n  return 'Hello';\n};\n```\n\n<!-- Update here: /questions/how-does-hoisting-affect-function-declarations-and-expressions/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-does-hoisting-affect-function-declarations-and-expressions/en-US.mdx)\n\n<br>\n\n### What are the potential issues caused by hoisting?\n\n<!-- Update here: /questions/what-are-the-potential-issues-caused-by-hoisting/en-US.mdx -->\n\nHoisting can lead to unexpected behavior in JavaScript because variable and function declarations are moved to the top of their containing scope during the compilation phase. This can result in `undefined` values for variables if they are used before their declaration and can cause confusion with function declarations and expressions. For example:\n\n```js live\nconsole.log(a); // undefined\nvar a = 5;\n\nconsole.log(b); // ReferenceError: Cannot access 'b' before initialization\nlet b = 10;\n```\n\n<!-- Update here: /questions/what-are-the-potential-issues-caused-by-hoisting/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-potential-issues-caused-by-hoisting/en-US.mdx)\n\n<br>\n\n### How can you avoid problems related to hoisting?\n\n<!-- Update here: /questions/how-can-you-avoid-problems-related-to-hoisting/en-US.mdx -->\n\nTo avoid problems related to hoisting, always declare variables at the top of their scope using `let` or `const` instead of `var`. This ensures that variables are block-scoped and not hoisted to the top of their containing function or global scope. Additionally, declare functions before they are called to avoid issues with function hoisting.\n\n```js live\n// Use let or const\nlet x = 10;\nconst y = 20;\nconsole.log(x, y); // Output: 10 20\n\n// Declare functions before calling them\nfunction myFunction() {\n  console.log('Hello, world!');\n}\nmyFunction(); // Output: 'Hello, world!'\n```\n\n<!-- Update here: /questions/how-can-you-avoid-problems-related-to-hoisting/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-avoid-problems-related-to-hoisting/en-US.mdx)\n\n<br>\n\n### What is the difference between `==` and `===` in JavaScript?\n\n<!-- Update here: /questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx -->\n\n`==` is the abstract equality operator while `===` is the strict equality operator. The `==` operator will compare for equality after doing any necessary type conversions. The `===` operator will not do type conversion, so if two values are not the same type `===` will simply return `false`.\n\n| Operator | `==` | `===` |\n| --- | --- | --- |\n| Name | (Loose) Equality operator | Strict equality operator |\n| Type coercion | Yes | No |\n| Compares value and type | No | Yes |\n\n<!-- Update here: /questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx)\n\n<br>\n\n### What language constructs do you use for iterating over object properties and array items in JavaScript?\n\n<!-- Update here: /questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx -->\n\nThere are multiple ways to iterate over object properties as well as arrays in JavaScript:\n\n**`for...in` loop**\n\nThe `for...in` loop iterates over all enumerable properties of an object, including inherited enumerable properties. So it is important to have a check if you only want to iterate over object's own properties\n\n```js live\nconst obj = {\n  a: 1,\n  b: 2,\n  c: 3,\n};\n\nfor (const key in obj) {\n  // To avoid iterating over inherited properties\n  if (Object.hasOwn(obj, key)) {\n    console.log(`${key}: ${obj[key]}`);\n  }\n}\n```\n\n**`Object.keys()`**\n\n`Object.keys()` returns an array of the object's own enumerable property names. You can then use a for...of loop or forEach to iterate over this array.\n\n```js live\nconst obj = {\n  a: 1,\n  b: 2,\n  c: 3,\n};\n\nObject.keys(obj).forEach((key) => {\n  console.log(`${key}: ${obj[key]}`);\n});\n```\n\nMost common ways to iterate over array are using `for` loop and `Array.prototype.forEach` method.\n\n**Using `for` loop**\n\n```js live\nlet array = [1, 2, 3, 4, 5, 6];\nfor (let index = 0; index < array.length; index++) {\n  console.log(array[index]);\n}\n```\n\n**Using `Array.prototype.forEach` method**\n\n```js live\nlet array = [1, 2, 3, 4, 5, 6];\narray.forEach((number, index) => {\n  console.log(`${number} at index ${index}`);\n});\n```\n\n**Using `for...of`**\n\nThis method is the newest and most convenient way to iterate over arrays. It automatically iterates over each element without requiring you to manage the index.\n\n```js live\nconst numbers = [1, 2, 3, 4, 5];\n\nfor (const number of numbers) {\n  console.log(number);\n}\n```\n\nThere are also other inbuilt methods available which are suitable for specific scenarios for example:\n\n- `Array.prototype.filter`: You can use the `filter` method to create a new array containing only the elements that satisfy a certain condition.\n- `Array.prototype.map`: You can use the `map` method to create a new array based on the existing one, transforming each element with a provided function.\n- `Array.prototype.reduce`: You can use the `reduce` method to combine all elements into a single value by repeatedly calling a function that takes two arguments: the accumulated value and the current element.\n\n<!-- Update here: /questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx)\n\n<br>\n\n### What is the purpose of the `break` and `continue` statements?\n\n<!-- Update here: /questions/what-is-the-purpose-of-the-break-and-continue-statements/en-US.mdx -->\n\nThe `break` statement is used to exit a loop or switch statement prematurely, while the `continue` statement skips the current iteration of a loop and proceeds to the next iteration. For example, in a `for` loop, `break` will stop the loop entirely, and `continue` will skip to the next iteration.\n\n```js live\nfor (let i = 0; i < 10; i++) {\n  if (i === 5) break; // exits the loop when i is 5\n  console.log(i);\n}\n\nfor (let i = 0; i < 10; i++) {\n  if (i === 5) continue; // skips the iteration when i is 5\n  console.log(i);\n}\n```\n\n<!-- Update here: /questions/what-is-the-purpose-of-the-break-and-continue-statements/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-purpose-of-the-break-and-continue-statements/en-US.mdx)\n\n<br>\n\n### What is the ternary operator and how is it used?\n\n<!-- Update here: /questions/what-is-the-ternary-operator-and-how-is-it-used/en-US.mdx -->\n\nThe ternary operator is a shorthand for an `if-else` statement in JavaScript. It takes three operands: a condition, a result for true, and a result for false. The syntax is `condition ? expr1 : expr2`. For example, `let result = (a > b) ? 'a is greater' : 'b is greater';` assigns `'a is greater'` to `result` if `a` is greater than `b`, otherwise it assigns `'b is greater'`.\n\n<!-- Update here: /questions/what-is-the-ternary-operator-and-how-is-it-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-ternary-operator-and-how-is-it-used/en-US.mdx)\n\n<br>\n\n### How do you access the index of an element in an array during iteration?\n\n<!-- Update here: /questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/en-US.mdx -->\n\nTo access the index of an element in an array during iteration, you can use methods like `forEach`, `map`, `for...of` with `entries`, or a traditional `for` loop. For example, using `forEach`:\n\n```js live\nconst array = ['a', 'b', 'c'];\narray.forEach((element, index) => {\n  console.log(index, element);\n});\n```\n\n<!-- Update here: /questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/en-US.mdx)\n\n<br>\n\n### What is the purpose of the `switch` statement?\n\n<!-- Update here: /questions/what-is-the-purpose-of-the-switch-statement/en-US.mdx -->\n\nThe `switch` statement is used to execute one block of code among many based on the value of an expression. It is an alternative to using multiple `if...else if` statements. The `switch` statement evaluates an expression, matches the expression's value to a `case` label, and executes the associated block of code. If no `case` matches, the `default` block is executed.\n\n```js\nswitch (expression) {\n  case value1:\n    // code to be executed if expression === value1\n    break;\n  case value2:\n    // code to be executed if expression === value2\n    break;\n  default:\n  // code to be executed if no case matches\n}\n```\n\n<!-- Update here: /questions/what-is-the-purpose-of-the-switch-statement/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-purpose-of-the-switch-statement/en-US.mdx)\n\n<br>\n\n### What are rest parameters and how are they used?\n\n<!-- Update here: /questions/what-are-rest-parameters-and-how-are-they-used/en-US.mdx -->\n\nRest parameters in JavaScript allow a function to accept an indefinite number of arguments as an array. They are denoted by three dots (`...`) followed by the name of the array. This feature is useful for functions that need to handle multiple arguments without knowing the exact number in advance.\n\n```js live\nfunction sum(...numbers) {\n  return numbers.reduce((acc, curr) => acc + curr, 0);\n}\n\nconsole.log(sum(1, 2, 3, 4)); // Output: 10\n```\n\n<!-- Update here: /questions/what-are-rest-parameters-and-how-are-they-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-rest-parameters-and-how-are-they-used/en-US.mdx)\n\n<br>\n\n### Explain the concept of the spread operator and its uses\n\n<!-- Update here: /questions/explain-the-concept-of-the-spread-operator-and-its-uses/en-US.mdx -->\n\nThe spread operator (`...`) in JavaScript allows you to expand elements of an iterable (like an array or object) into individual elements. It is commonly used for copying arrays or objects, merging arrays or objects, and passing elements of an array as arguments to a function.\n\n```js live\n// Copying an array\nconst arr1 = [1, 2, 3];\nconst arr2 = [...arr1];\nconsole.log(arr2); // Output: [1, 2, 3]\n\n// Merging arrays\nconst arr3 = [4, 5, 6];\nconst mergedArray = [...arr1, ...arr3];\nconsole.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]\n\n// Copying an object\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { ...obj1 };\nconsole.log(obj2); // Output: { a: 1, b: 2 }\n\n// Merging objects\nconst obj3 = { c: 3, d: 4 };\nconst mergedObject = { ...obj1, ...obj3 };\nconsole.log(mergedObject); // Output: { a: 1, b: 2, c: 3, d: 4 }\n\n// Passing array elements as function arguments\nconst sum = (x, y, z) => x + y + z;\nconst numbers = [1, 2, 3];\nconsole.log(sum(...numbers)); // Output: 6\n```\n\n<!-- Update here: /questions/explain-the-concept-of-the-spread-operator-and-its-uses/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-the-spread-operator-and-its-uses/en-US.mdx)\n\n<br>\n\n### What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?\n\n<!-- Update here: /questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx -->\n\n**Spread syntax** (`...`) allows an iterable (like an array or string) to be expanded into individual elements. This is often used as a convenient and modern way to create new arrays or objects by combining existing ones.\n\n| Operation      | Traditional                     | Spread                 |\n| -------------- | ------------------------------- | ---------------------- |\n| Array cloning  | `arr.slice()`                   | `[...arr]`             |\n| Array merging  | `arr1.concat(arr2)`             | `[...arr1, ...arr2]`   |\n| Object cloning | `Object.assign({}, obj)`        | `{ ...obj }`           |\n| Object merging | `Object.assign({}, obj1, obj2)` | `{ ...obj1, ...obj2 }` |\n\n**Rest syntax** is the opposite of what spread syntax does. It collects a variable number of arguments into an array. This is often used in function parameters to handle a dynamic number of arguments.\n\n```js live\n// Using rest syntax in a function\nfunction sum(...numbers) {\n  return numbers.reduce((total, num) => total + num, 0);\n}\n\nconsole.log(sum(1, 2, 3)); // Output: 6\n```\n\n<!-- Update here: /questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx)\n\n<br>\n\n### What are iterators and generators in JavaScript and what are they used for?\n\n<!-- Update here: /questions/what-are-iterators-and-generators-and-what-are-they-used-for/en-US.mdx -->\n\nIn JavaScript, iterators and generators are powerful tools for managing sequences of data and controlling the flow of execution in a more flexible way.\n\n**Iterators** are objects that define a sequence and potentially a return value upon its termination. It adheres to a specific interface:\n\n- An iterator object must implement a `next()` method.\n- The `next()` method returns an object with two properties:\n  - `value`: The next value in the sequence.\n  - `done`: A boolean that is `true` if the iterator has finished its sequence, otherwise `false`.\n\nHere's an example of an object implementing the iterator interface.\n\n```js live\nconst iterator = {\n  current: 0,\n  last: 5,\n  next() {\n    if (this.current <= this.last) {\n      return { value: this.current++, done: false };\n    } else {\n      return { value: undefined, done: true };\n    }\n  },\n};\n\nlet result = iterator.next();\nwhile (!result.done) {\n  console.log(result.value); // Logs 0, 1, 2, 3, 4, 5\n  result = iterator.next();\n}\n```\n\n**Generators** are a special functions that **can pause execution and resume at a later point**. It uses the `function*` syntax and the `yield` keyword to control the flow of execution. When you call a generator function, it doesn't execute completely like a regular function. Instead, it returns an iterator object. Calling the `next()` method on the returned iterator advances the generator to the next `yield` statement, and the value after `yield` becomes the return value of `next()`.\n\n```js live\nfunction* numberGenerator() {\n  let num = 0;\n  while (num <= 5) {\n    yield num++;\n  }\n}\n\nconst gen = numberGenerator();\nconsole.log(gen.next()); // { value: 0, done: false }\nconsole.log(gen.next()); // { value: 1, done: false }\nconsole.log(gen.next()); // { value: 2, done: false }\nconsole.log(gen.next()); // { value: 3, done: false }\nconsole.log(gen.next()); // { value: 4, done: false }\nconsole.log(gen.next()); // { value: 5, done: false }\nconsole.log(gen.next()); // { value: undefined, done: true }\n```\n\nGenerators are powerful for creating iterators on-demand, especially for infinite sequences or complex iteration logic. They can be used for:\n\n- Lazy evaluation – processing elements only when needed, improving memory efficiency for large datasets.\n- Implementing iterators for custom data structures.\n- Creating asynchronous iterators for handling data streams.\n\n<!-- Update here: /questions/what-are-iterators-and-generators-and-what-are-they-used-for/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-iterators-and-generators-and-what-are-they-used-for/en-US.mdx)\n\n<br>\n\n### Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}` in JavaScript\n\n<!-- Update here: /questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx -->\n\n`function foo() {}` a function declaration while the `var foo = function() {}` is a function expression. The key difference is that function declarations have its body hoisted but the bodies of function expressions are not (they have the same hoisting behavior as `var`-declared variables).\n\nIf you try to invoke a function expression before it is declared, you will get an `Uncaught TypeError: XXX is not a function` error.\n\nFunction declarations can be called in the enclosing scope even before they are declared.\n\n```js live\nfoo(); // 'FOOOOO'\nfunction foo() {\n  console.log('FOOOOO');\n}\n```\n\nFunction expressions if called before they are declared will result in an error.\n\n```js live\nfoo(); // Uncaught TypeError: foo is not a function\nvar foo = function () {\n  console.log('FOOOOO');\n};\n```\n\nAnother key difference is in the scope of the function name. Function expressions can be named by defining it after the `function` and before the parenthesis. However when using named function expressions, the function name is only accessible within the function itself. Trying to access it outside will result in an error or `undefined`.\n\n```js live\nconst myFunc = function namedFunc() {\n  console.log(namedFunc); // Works\n};\n\nmyFunc(); // Runs the function and logs the function reference\nconsole.log(namedFunc); // ReferenceError: namedFunc is not defined\n```\n\n**Note**: The examples uses `var` due to legacy reasons. Function expressions can be defined using `let` and `const` and the key difference is in the hoisting behavior of those keywords.\n\n<!-- Update here: /questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx)\n\n<br>\n\n### What is the difference between a parameter and an argument?\n\n<!-- Update here: /questions/what-is-the-difference-between-a-parameter-and-an-argument/en-US.mdx -->\n\nA parameter is a variable in the declaration of a function, while an argument is the actual value passed to the function when it is called. For example, in the function `function add(a, b) { return a + b; }`, `a` and `b` are parameters. When you call `add(2, 3)`, `2` and `3` are arguments.\n\n<!-- Update here: /questions/what-is-the-difference-between-a-parameter-and-an-argument/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-a-parameter-and-an-argument/en-US.mdx)\n\n<br>\n\n### Explain the concept of hoisting with regards to functions\n\n<!-- Update here: /questions/explain-the-concept-of-hoisting-with-regards-to-functions/en-US.mdx -->\n\nHoisting in JavaScript is a behavior where function declarations are moved to the top of their containing scope during the compile phase. This means you can call a function before it is defined in the code. However, this does not apply to function expressions or arrow functions, which are not hoisted in the same way.\n\n```js live\n// Function declaration\nhoistedFunction(); // Works fine\nfunction hoistedFunction() {\n  console.log('This function is hoisted');\n}\n\n// Function expression\nnonHoistedFunction(); // Throws an error\nvar nonHoistedFunction = function () {\n  console.log('This function is not hoisted');\n};\n```\n\n<!-- Update here: /questions/explain-the-concept-of-hoisting-with-regards-to-functions/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-hoisting-with-regards-to-functions/en-US.mdx)\n\n<br>\n\n### What's the difference between `.call` and `.apply` in JavaScript?\n\n<!-- Update here: /questions/whats-the-difference-between-call-and-apply/en-US.mdx -->\n\n`.call` and `.apply` are both used to invoke functions with a specific `this` context and arguments. The primary difference lies in how they accept arguments:\n\n- `.call(thisArg, arg1, arg2, ...)`: Takes arguments individually.\n- `.apply(thisArg, [argsArray])`: Takes arguments as an array.\n\nAssuming we have a function `add`, the function can be invoked using `.call` and `.apply` in the following manner:\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconsole.log(add.call(null, 1, 2)); // 3\nconsole.log(add.apply(null, [1, 2])); // 3\n```\n\n<!-- Update here: /questions/whats-the-difference-between-call-and-apply/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-the-difference-between-call-and-apply/en-US.mdx)\n\n<br>\n\n### Can you offer a use case for the new arrow => function syntax?\n\n<!-- Update here: /questions/can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions/en-US.mdx -->\n\nArrow functions provide a concise syntax for writing functions in JavaScript. They are particularly useful for maintaining the `this` context within methods and callbacks. For example, in an event handler or array method like `map`, arrow functions can simplify the code and avoid issues with `this` binding.\n\n```js live\nconst numbers = [1, 2, 3];\nconst doubled = numbers.map((n) => n * 2);\nconsole.log(doubled); // [2, 4, 6]\n```\n\n<!-- Update here: /questions/can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions/en-US.mdx)\n\n<br>\n\n### Difference between: `function Person(){}`, `const person = Person()`, and `const person = new Person()` in JavaScript?\n\n<!-- Update here: /questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx -->\n\n- `function Person(){}`: A function declaration in JavaScript. It can be used as a regular function or as a constructor.\n- `const person = Person()`: Calls `Person` as a regular function, not a constructor. If `Person` is intended to be a constructor, this will lead to unexpected behavior.\n- `const person = new Person()`: Creates a new instance of `Person`, correctly utilizing the constructor function to initialize the new object.\n\n| Aspect | `function Person(){}` | `const person = Person()` | `const person = new Person()` |\n| --- | --- | --- | --- |\n| Type | Function declaration | Function call | Constructor call |\n| Usage | Defines a function | Invokes `Person` as a regular function | Creates a new instance of `Person` |\n| Instance Creation | No instance created | No instance created | New instance created |\n| Common Mistake | N/A | Misusing as constructor leading to `undefined` | None (when used correctly) |\n\n<!-- Update here: /questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx)\n\n<br>\n\n### What is the definition of a higher-order function in JavaScript?\n\n<!-- Update here: /questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx -->\n\nA higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a result.\n\nHigher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is `Array.prototype.map()`, which takes an array and a function as arguments. `Array.prototype.map()` then uses this function to transform each item in the array, returning a new array with the transformed data. Other popular examples in JavaScript are `Array.prototype.forEach()`, `Array.prototype.filter()`, and `Array.prototype.reduce()`. A higher-order function doesn't just need to be manipulating arrays as there are many use cases for returning a function from another function. `Function.prototype.bind()` is an example that returns another function.\n\nImagine a scenario where we have an array of names that we need to transform to uppercase. The imperative way will be as such:\n\n```js live\nconst names = ['irish', 'daisy', 'anna'];\n\nfunction transformNamesToUppercase(names) {\n  const results = [];\n  for (let i = 0; i < names.length; i++) {\n    results.push(names[i].toUpperCase());\n  }\n  return results;\n}\n\nconsole.log(transformNamesToUppercase(names)); // ['IRISH', 'DAISY', 'ANNA']\n```\n\nUsing `Array.prototype.map(transformerFn)` makes the code shorter and more declarative.\n\n```js live\nconst names = ['irish', 'daisy', 'anna'];\n\nfunction transformNamesToUppercase(names) {\n  return names.map((name) => name.toUpperCase());\n}\n\nconsole.log(transformNamesToUppercase(names)); // ['IRISH', 'DAISY', 'ANNA']\n```\n\n<!-- Update here: /questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx)\n\n<br>\n\n### What are callback functions and how are they used?\n\n<!-- Update here: /questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx -->\n\nA callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. They are commonly used for asynchronous operations like handling events, making API calls, or reading files. For example:\n\n```js live\nfunction fetchData(callback) {\n  // assume an asynchronous operation to fetch data\n  const data = { name: 'John Doe' };\n  callback(data);\n}\n\nfunction handleData(data) {\n  console.log(data);\n}\n\nfetchData(handleData);\n```\n\n<!-- Update here: /questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx)\n\n<br>\n\n### What's a typical use case for anonymous functions in JavaScript?\n\n<!-- Update here: /questions/whats-a-typical-use-case-for-anonymous-functions/en-US.mdx -->\n\nAnonymous function in Javascript is a function that does not have any name associated with it. They are typically used as arguments to other functions or assigned to variables.\n\n```js live\nconst arr = [-1, 0, 5, 6];\n\n// The filter method is passed an anonymous function.\narr.filter((x) => x > 1); // [5, 6]\n```\n\nThey are often used as arguments to other functions, known as higher-order functions, which can take functions as input and return a function as output. Anonymous functions can access variables from the outer scope, a concept known as closures, allowing them to \"close over\" and remember the environment in which they were created.\n\n```js live\n// Encapsulating Code\n(function () {\n  // Some code here.\n})();\n\n// Callbacks\nsetTimeout(function () {\n  console.log('Hello world!');\n}, 1000);\n\n// Functional programming constructs\nconst arr = [1, 2, 3];\nconst double = arr.map(function (el) {\n  return el * 2;\n});\nconsole.log(double); // [2, 4, 6]\n```\n\n<!-- Update here: /questions/whats-a-typical-use-case-for-anonymous-functions/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-a-typical-use-case-for-anonymous-functions/en-US.mdx)\n\n<br>\n\n### What is recursion and how is it used in JavaScript?\n\n<!-- Update here: /questions/what-is-recursion-and-how-is-it-used-in-javascript/en-US.mdx -->\n\nRecursion is a programming technique where a function calls itself to solve a problem. In JavaScript, recursion is used to solve problems that can be broken down into smaller, similar sub-problems. A base case is essential to stop the recursive calls and prevent infinite loops. For example, calculating the factorial of a number can be done using recursion:\n\n```js live\nfunction factorial(n) {\n  if (n === 0) {\n    return 1;\n  }\n  return n * factorial(n - 1);\n}\n\nconsole.log(factorial(4)); // Output: 24\n```\n\n<!-- Update here: /questions/what-is-recursion-and-how-is-it-used-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-recursion-and-how-is-it-used-in-javascript/en-US.mdx)\n\n<br>\n\n### What are default parameters and how are they used?\n\n<!-- Update here: /questions/what-are-default-parameters-and-how-are-they-used/en-US.mdx -->\n\nDefault parameters in JavaScript allow you to set default values for function parameters if no value or `undefined` is passed. This helps avoid `undefined` values and makes your code more robust. You can define default parameters by assigning a value to the parameter in the function definition.\n\n```js live\nfunction greet(name = 'Guest') {\n  console.log(`Hello, ${name}!`);\n}\n\ngreet(); // Output: Hello, Guest!\ngreet('Alice'); // Output: Hello, Alice!\n```\n\n<!-- Update here: /questions/what-are-default-parameters-and-how-are-they-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-default-parameters-and-how-are-they-used/en-US.mdx)\n\n<br>\n\n### Explain why the following doesn't work as an IIFE: `function foo(){}();`. What needs to be changed to properly make it an IIFE?\n\n<!-- Update here: /questions/explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife/en-US.mdx -->\n\nThe code `function foo(){}();` doesn't work as an Immediately Invoked Function Expression (IIFE) because the JavaScript parser treats `function foo(){}` as a function declaration, not an expression. To make it an IIFE, you need to wrap the function in parentheses to turn it into a function expression: `(function foo(){})();`.\n\n<!-- Update here: /questions/explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife/en-US.mdx)\n\n<br>\n\n### What are the various ways to create objects in JavaScript?\n\n<!-- Update here: /questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx -->\n\nCreating objects in JavaScript offers several methods:\n\n- **Object literals (`{}`)**: Simplest and most popular approach. Define key-value pairs within curly braces.\n- **`Object()` constructor**: Use `new Object()` with dot notation to add properties.\n- **`Object.create()`**: Create new objects using existing objects as prototypes, inheriting properties and methods.\n- **Constructor functions**: Define blueprints for objects using functions, creating instances with `new`.\n- **ES2015 classes**: Structured syntax similar to other languages, using `class` and `constructor` keywords.\n\n<!-- Update here: /questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx)\n\n<br>\n\n### Explain the difference between dot notation and bracket notation for accessing object properties\n\n<!-- Update here: /questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/en-US.mdx -->\n\nDot notation and bracket notation are two ways to access properties of an object in JavaScript. Dot notation is more concise and readable but can only be used with valid JavaScript identifiers. Bracket notation is more flexible and can be used with property names that are not valid identifiers, such as those containing spaces or special characters.\n\n```js live\nconst obj = { name: 'Alice', 'favorite color': 'blue' };\n\n// Dot notation\nconsole.log(obj.name); // Alice\n\n// Bracket notation\nconsole.log(obj['favorite color']); // blue\n```\n\n<!-- Update here: /questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/en-US.mdx)\n\n<br>\n\n### What are the different methods for iterating over an array?\n\n<!-- Update here: /questions/what-are-the-different-methods-for-iterating-over-an-array/en-US.mdx -->\n\nThere are several methods to iterate over an array in JavaScript. The most common ones include `for` loops, `forEach`, `map`, `filter`, `reduce`, and `for...of`. Each method has its own use case. For example, `for` loops are versatile and can be used for any kind of iteration, while `forEach` is specifically for executing a function on each array element. `map` is used for transforming arrays, `filter` for filtering elements, `reduce` for accumulating values, and `for...of` for iterating over iterable objects.\n\n<!-- Update here: /questions/what-are-the-different-methods-for-iterating-over-an-array/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-different-methods-for-iterating-over-an-array/en-US.mdx)\n\n<br>\n\n### How do you add, remove, and update elements in an array?\n\n<!-- Update here: /questions/how-do-you-add-remove-and-update-elements-in-an-array/en-US.mdx -->\n\nTo add elements to an array, you can use methods like `push`, `unshift`, or `splice`. To remove elements, you can use `pop`, `shift`, or `splice`. To update elements, you can directly access the array index and assign a new value.\n\n```js live\nlet arr = [1, 2, 3];\n\n// Add elements\narr.push(4); // [1, 2, 3, 4]\narr.unshift(0); // [0, 1, 2, 3, 4]\narr.splice(2, 0, 1.5); // [0, 1, 1.5, 2, 3, 4]\n\n// Remove elements\narr.pop(); // [0, 1, 1.5, 2, 3]\narr.shift(); // [1, 1.5, 2, 3]\narr.splice(1, 1); // [1, 2, 3]\n\n// Update elements\narr[1] = 5; // [1, 5, 3]\nconsole.log(arr); // Final state: [1, 5, 3]\n```\n\n**Note**: If you try to `console.log(arr)` after each operation in some environments (like Chrome DevTools), you may only see the final state of `arr`. This happens because the console sometimes keeps a live reference to the array instead of logging its state at the exact moment. To see intermediate states properly, store snapshots using `console.log([...arr])` or print values immediately after each operation.\n\n<!-- Update here: /questions/how-do-you-add-remove-and-update-elements-in-an-array/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-add-remove-and-update-elements-in-an-array/en-US.mdx)\n\n<br>\n\n### What are the different ways to copy an object or an array?\n\n<!-- Update here: /questions/what-are-the-different-ways-to-copy-an-object-or-an-array/en-US.mdx -->\n\nTo copy an object or an array in JavaScript, you can use several methods. For shallow copies, you can use the spread operator (`...`) or `Object.assign()`. For deep copies, you can use `JSON.parse(JSON.stringify())` or libraries like Lodash's `_.cloneDeep()`.\n\n```js live\n// Shallow copy of an array\nconst originalArray = [1, 2, 3];\nconst shallowCopyArray = [...originalArray];\nconsole.log(shallowCopyArray); // [1, 2, 3]\n\n// Shallow copy of an object\nconst originalObject = { a: 1, b: 2 };\nconst shallowCopyObject = { ...originalObject };\nconsole.log(shallowCopyObject); // { a: 1, b: 2 };\n\n// Deep copy using JSON methods\nconst deepCopyObject = JSON.parse(JSON.stringify(originalObject));\nconsole.log(deepCopyObject); // { a: 1, b: 2 };\n```\n\n<!-- Update here: /questions/what-are-the-different-ways-to-copy-an-object-or-an-array/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-different-ways-to-copy-an-object-or-an-array/en-US.mdx)\n\n<br>\n\n### Explain the difference between shallow copy and deep copy\n\n<!-- Update here: /questions/explain-the-difference-between-shallow-copy-and-deep-copy/en-US.mdx -->\n\nA shallow copy duplicates the top-level properties of an object, but nested objects are still referenced. A deep copy duplicates all levels of an object, creating entirely new instances of nested objects. For example, using `Object.assign()` creates a shallow copy, while using libraries like `Lodash` or `structuredClone()` in modern JavaScript can create deep copies.\n\n```js live\n// Shallow copy example\nlet obj1 = { a: 1, b: { c: 2 } };\nlet shallowCopy = Object.assign({}, obj1);\nshallowCopy.b.c = 3;\nconsole.log(shallowCopy.b.c); // Output: 3\nconsole.log(obj1.b.c); // Output: 3 (original nested object changed too!)\n\n// Deep copy example\nlet obj2 = { a: 1, b: { c: 2 } };\nlet deepCopy = JSON.parse(JSON.stringify(obj2));\ndeepCopy.b.c = 4;\nconsole.log(deepCopy.b.c); // Output: 4\nconsole.log(obj2.b.c); // Output: 2 (original nested object remains unchanged)\n```\n\n<!-- Update here: /questions/explain-the-difference-between-shallow-copy-and-deep-copy/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-shallow-copy-and-deep-copy/en-US.mdx)\n\n<br>\n\n### What are the advantages of using the spread operator with arrays and objects?\n\n<!-- Update here: /questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/en-US.mdx -->\n\nThe spread operator (`...`) in JavaScript allows you to easily copy arrays and objects, merge them, and add new elements or properties. It simplifies syntax and improves readability. For arrays, it can be used to concatenate or clone arrays. For objects, it can be used to merge objects or add new properties.\n\n```js live\n// Arrays\nconst arr1 = [1, 2, 3];\nconst arr2 = [...arr1, 4, 5];\nconsole.log(arr2); // [1, 2, 3, 4, 5]\n\n// Objects\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { ...obj1, c: 3 };\nconsole.log(obj2); // { a: 1, b: 2, c: 3 }\n```\n\n<!-- Update here: /questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/en-US.mdx)\n\n<br>\n\n### How do you check if an object has a specific property?\n\n<!-- Update here: /questions/how-do-you-check-if-an-object-has-a-specific-property/en-US.mdx -->\n\nTo check if an object has a specific property, you can use the `in` operator or the `hasOwnProperty` method. The `in` operator checks for both own and inherited properties, while `hasOwnProperty` checks only for own properties.\n\n```js live\nconst obj = { key: 'value' };\n\n// Using the `in` operator\nif ('key' in obj) {\n  console.log('Property exists');\n}\n\n// Using `hasOwnProperty`\nif (obj.hasOwnProperty('key')) {\n  console.log('Property exists');\n}\n```\n\n<!-- Update here: /questions/how-do-you-check-if-an-object-has-a-specific-property/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-check-if-an-object-has-a-specific-property/en-US.mdx)\n\n<br>\n\n### Explain the difference between mutable and immutable objects in JavaScript\n\n<!-- Update here: /questions/explain-the-difference-between-mutable-and-immutable-objects/en-US.mdx -->\n\n**Mutable objects** allow for modification of properties and values after creation, which is the default behavior for most objects.\n\n```js live\nconst mutableObject = {\n  name: 'John',\n  age: 30,\n};\n\n// Modify the object\nmutableObject.name = 'Jane';\n\n// The object has been modified\nconsole.log(mutableObject); // Output: { name: 'Jane', age: 30 }\n```\n\n**Immutable objects** cannot be directly modified after creation. Its content cannot be changed without creating an entirely new value.\n\n```js live\nconst immutableObject = Object.freeze({\n  name: 'John',\n  age: 30,\n});\n\n// Attempt to modify the object\nimmutableObject.name = 'Jane';\n\n// The object remains unchanged\nconsole.log(immutableObject); // Output: { name: 'John', age: 30 }\n```\n\nThe key difference between mutable and immutable objects is modifiability. Immutable objects cannot be modified after they are created, while mutable objects can be.\n\n<!-- Update here: /questions/explain-the-difference-between-mutable-and-immutable-objects/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-mutable-and-immutable-objects/en-US.mdx)\n\n<br>\n\n### Explain the concept of destructuring assignment for objects and arrays\n\n<!-- Update here: /questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/en-US.mdx -->\n\nDestructuring assignment is a syntax in JavaScript that allows you to unpack values from arrays or properties from objects into distinct variables. For arrays, you use square brackets, and for objects, you use curly braces. For example:\n\n```js live\n// Array destructuring\nconst [a, b] = [1, 2];\n\n// Object destructuring\nconst { name, age } = { name: 'John', age: 30 };\n```\n\n<!-- Update here: /questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/en-US.mdx)\n\n<br>\n\n### What is `Object.freeze()` for?\n\n<!-- Update here: /questions/what-is-objectfreeze-for/en-US.mdx -->\n\n`Object.freeze()` is used to make an object immutable. Once an object is frozen, you cannot add, remove, or modify its properties. This is useful for creating constants or ensuring that an object remains unchanged throughout the program.\n\n```js live\nconst obj = { name: 'John' };\nObject.freeze(obj);\nobj.name = 'Doe'; // This will not change the name property\n\nconsole.log(obj); // { name: 'John' }\n```\n\n<!-- Update here: /questions/what-is-objectfreeze-for/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-objectfreeze-for/en-US.mdx)\n\n<br>\n\n### What is `Object.seal()` for?\n\n<!-- Update here: /questions/what-is-objectseal-for/en-US.mdx -->\n\n`Object.seal()` is used to prevent new properties from being added to an object and to mark all existing properties as non-configurable. This means you can still modify the values of existing properties, but you cannot delete them or add new ones. Doing so will throw errors in strict mode but fail silently in non-strict mode. In the following examples, you can uncomment the 'use strict' comment to see this.\n\n```js live\n// 'use strict'\n\nconst obj = { name: 'John' };\nObject.seal(obj);\n\nobj.name = 'Jane'; // Allowed\nobj.age = 30; // Not allowed, throws an error in strict mode\ndelete obj.name; // Not allowed, throws an error in strict mode\n\nconsole.log(obj); // { name: 'Jane } (unchanged)\n```\n\n<!-- Update here: /questions/what-is-objectseal-for/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-objectseal-for/en-US.mdx)\n\n<br>\n\n### What is `Object.preventExtensions()` for?\n\n<!-- Update here: /questions/what-is-objectpreventextensions-for/en-US.mdx -->\n\n`Object.preventExtensions()` is a method in JavaScript that prevents new properties from being added to an object. However, it does not affect the deletion or modification of existing properties. This method is useful when you want to ensure that an object remains in a certain shape and no additional properties can be added to it.\n\n```js live\nconst obj = { name: 'John' };\nObject.preventExtensions(obj);\n\nobj.age = 30; // This will not work, as the object is not extensible\nconsole.log(obj.age); // undefined\n```\n\n<!-- Update here: /questions/what-is-objectpreventextensions-for/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-objectpreventextensions-for/en-US.mdx)\n\n<br>\n\n### What are JavaScript object getters and setters for?\n\n<!-- Update here: /questions/what-are-javascript-object-getters-and-setters-for/en-US.mdx -->\n\nJavaScript object getters and setters are used to control access to an object's properties. They provide a way to encapsulate the implementation details of a property and define custom behavior when getting or setting its value.\n\nGetters and setters are defined using the `get` and `set` keywords, respectively, followed by a function that is executed when the property is accessed or assigned a new value.\n\nHere's a code example demonstrating the use of getters and setters:\n\n```js live\nconst person = {\n  _name: 'John Doe', // Private property\n\n  get name() {\n    // Getter\n    return this._name;\n  },\n  set name(newName) {\n    // Setter\n    if (newName.trim().length > 0) {\n      this._name = newName;\n    } else {\n      console.log('Invalid name');\n    }\n  },\n};\n\n// Accessing the name property using the getter\nconsole.log(person.name); // Output: 'John Doe'\n\n// Setting the name property using the setter\nperson.name = 'Jane Smith'; // Setter is called\nconsole.log(person.name); // Output: 'Jane Smith'\n\nperson.name = ''; // Setter is called, but the value is not set due to validation\nconsole.log(person.name); // Output: 'Jane Smith'\n```\n\n<!-- Update here: /questions/what-are-javascript-object-getters-and-setters-for/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-object-getters-and-setters-for/en-US.mdx)\n\n<br>\n\n### What are JavaScript object property flags and descriptors?\n\n<!-- Update here: /questions/what-are-javascript-object-property-flags-and-descriptors/en-US.mdx -->\n\nIn JavaScript, property flags and descriptors manage the behavior and attributes of object properties.\n\n**Property flags**\n\nProperty flags are used to specify the behavior of a property on an object. Here are the available flags:\n\n- `writable`: Specifies whether the property can be written to. Defaults to `true`.\n- `enumerable`: Specifies whether the property is enumerable. Defaults to `true`.\n- `configurable`: Specifies whether the property can be deleted or its attributes changed. Default is `true`.\n\n**Property descriptors**\n\nThese provide detailed information about an object's property, including its value and flags. They are retrieved using `Object.getOwnPropertyDescriptor()` and set using `Object.defineProperty()`.\n\nThe use cases of property descriptors are as follows:\n\n- Making a property non-writable by setting `writable: false` to ensure data consistency.\n- Hiding a property from enumeration by setting `enumerable: false`.\n- Preventing property deletion and modification by setting `configurable: false`.\n- Freezing or sealing objects to prevent modifications globally.\n\n<!-- Update here: /questions/what-are-javascript-object-property-flags-and-descriptors/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-object-property-flags-and-descriptors/en-US.mdx)\n\n<br>\n\n### How do you reliably determine whether an object is empty?\n\n<!-- Update here: /questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.mdx -->\n\nTo reliably determine whether an object is empty, you can use `Object.keys()` to check if the object has any enumerable properties. If the length of the array returned by `Object.keys()` is zero, the object is empty.\n\n```js live\nconst isEmpty = (obj) => Object.keys(obj).length === 0;\n\nconst obj = {};\nconsole.log(isEmpty(obj)); // true\n```\n\n<!-- Update here: /questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.mdx)\n\n<br>\n\n### What is the event loop in JavaScript runtimes?\n\n<!-- Update here: /questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.mdx -->\n\nThe event loop is a concept within the JavaScript runtime environment regarding how asynchronous operations are executed within JavaScript engines. It works as such:\n\n1. The JavaScript engine starts executing scripts, placing synchronous operations on the call stack.\n2. When an asynchronous operation is encountered (e.g., `setTimeout()`, HTTP request), it is offloaded to the respective Web API or Node.js API to handle the operation in the background.\n3. Once the asynchronous operation completes, its callback function is placed in the respective queues – task queues (also known as macrotask queues / callback queues) or microtask queues. We will refer to \"task queue\" as \"macrotask queue\" from here on to better differentiate from the microtask queue.\n4. The event loop continuously monitors the call stack and executes items on the call stack. If/when the call stack is empty:\n   1. Microtask queue is processed. Microtasks include promise callbacks (`then`, `catch`, `finally`), `MutationObserver` callbacks, and calls to `queueMicrotask()`. The event loop takes the first callback from the microtask queue and pushes it to the call stack for execution. This repeats until the microtask queue is empty.\n   2. Macrotask queue is processed. Macrotasks include web APIs like `setTimeout()`, HTTP requests, user interface event handlers like clicks, scrolls, etc. The event loop dequeues the first callback from the macrotask queue and pushes it onto the call stack for execution. However, after a macrotask queue callback is processed, the event loop does not proceed with the next macrotask yet! The event loop first checks the microtask queue. Checking the microtask queue is necessary as microtasks have higher priority than macrotask queue callbacks. The macrotask queue callback that was just executed could have added more microtasks!\n      1. If the microtask queue is non-empty, process them as per the previous step.\n      2. If the microtask queue is empty, the next macrotask queue callback is processed. This repeats until the macrotask queue is empty.\n5. This process continues indefinitely, allowing the JavaScript engine to handle both synchronous and asynchronous operations efficiently without blocking the call stack.\n\nThe unfortunate truth is that it is extremely hard to explain the event loop well using only text. We recommend checking out one of the following excellent videos explaining the event loop:\n\n- [JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue](https://www.youtube.com/watch?v=eiC58R16hb8) (2024): Lydia Hallie is a popular educator on JavaScript and this is the best recent video explaining the event loop. There's also an [accompanying blog post](https://www.lydiahallie.com/blog/event-loop) for those who prefer detailed text-based explanations.\n- [In the Loop](https://www.youtube.com/watch?v=cCOL7MC4Pl0) (2018): Jake Archibald previously from the Chrome team provides a visual demonstration of the event loop during JSConf 2018, accounting for different types of tasks.\n- [What the heck is the event loop anyway?](https://www.youtube.com/watch?v=8aGhZQkoFbQ) (2014): Philip Robert's gave this epic talk at JSConf 2014 and it is one of the most viewed JavaScript videos on YouTube.\n\nWe recommend watching [Lydia's video](https://www.youtube.com/watch?v=eiC58R16hb8) as it is the most modern and concise explanation standing at only 13 minutes long whereas the other videos are at least 30 minutes long. Her video is sufficient for the purpose of interviews.\n\n<!-- Update here: /questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.mdx)\n\n<br>\n\n### Explain the difference between synchronous and asynchronous functions in JavaScript\n\n<!-- Update here: /questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx -->\n\nSynchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. As a result, programs containing only synchronous code are evaluated exactly in order of the statements. The execution of the program is paused if one of the statements take a very long time.\n\n```js live\nfunction sum(a, b) {\n  console.log('Inside sum function');\n  return a + b;\n}\n\nconst result = sum(2, 3); // The program waits for sum() to complete before assigning the result\nconsole.log('Result: ', result); // Output: 5\n```\n\nAsynchronous functions usually accept a callback as a parameter and execution continue on to the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John', age: 30 };\n    callback(data); // Calling the callback function with data\n  }, 2000); // Simulating a 2-second delay\n}\n\nconsole.log('Fetching data...');\n\nfetchData((data) => {\n  console.log(data); // Output: { name: 'John', age: 30 } (after 2 seconds)\n});\n\nconsole.log('Call made to fetch data'); // This will print before the data is fetched\n```\n\n<!-- Update here: /questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx)\n\n<br>\n\n### Explain the concept of a callback function in asynchronous operations\n\n<!-- Update here: /questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/en-US.mdx -->\n\nA callback function is a function passed as an argument to another function, which is then invoked inside the outer function to complete some kind of routine or action. In asynchronous operations, callbacks are used to handle tasks that take time to complete, such as network requests or file I/O, without blocking the execution of the rest of the code. For example:\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John', age: 30 };\n    callback(data);\n  }, 1000);\n}\n\nfetchData((data) => {\n  console.log(data);\n});\n```\n\n<!-- Update here: /questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/en-US.mdx)\n\n<br>\n\n### What are Promises and how do they work?\n\n<!-- Update here: /questions/what-are-promises-and-how-do-they-work/en-US.mdx -->\n\nPromises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They have three states: `pending`, `fulfilled`, and `rejected`. You can handle the results of a promise using the `.then()` method for success and the `.catch()` method for errors.\n\n```js live\nlet promise = new Promise((resolve, reject) => {\n  // asynchronous operation\n  const success = true;\n  if (success) {\n    resolve('Success!');\n  } else {\n    reject('Error!');\n  }\n});\n\npromise\n  .then((result) => {\n    console.log(result); // 'Success!' (this will print)\n  })\n  .catch((error) => {\n    console.error(error); // 'Error!'\n  });\n```\n\n<!-- Update here: /questions/what-are-promises-and-how-do-they-work/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-promises-and-how-do-they-work/en-US.mdx)\n\n<br>\n\n### Explain the different states of a Promise\n\n<!-- Update here: /questions/explain-the-different-states-of-a-promise/en-US.mdx -->\n\nA `Promise` in JavaScript can be in one of three states: `pending`, `fulfilled`, or `rejected`. When a `Promise` is created, it starts in the `pending` state. If the operation completes successfully, the `Promise` transitions to the `fulfilled` state, and if it fails, it transitions to the `rejected` state. Here's a quick example:\n\n```js\nlet promise = new Promise((resolve, reject) => {\n  // some asynchronous operation\n  if (success) {\n    resolve('Success!');\n  } else {\n    reject('Error!');\n  }\n});\n```\n\n<!-- Update here: /questions/explain-the-different-states-of-a-promise/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-different-states-of-a-promise/en-US.mdx)\n\n<br>\n\n### What are the pros and cons of using Promises instead of callbacks in JavaScript?\n\n<!-- Update here: /questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/en-US.mdx -->\n\nPromises offer a cleaner alternative to callbacks, helping to avoid callback hell and making asynchronous code more readable. They facilitate writing sequential and parallel asynchronous operations with ease. However, using promises may introduce slightly more complex code.\n\n<!-- Update here: /questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/en-US.mdx)\n\n<br>\n\n### What is the use of `Promise.all()`\n\n<!-- Update here: /questions/what-is-the-use-of-promiseall/en-US.mdx -->\n\n`Promise.all()` is a method in JavaScript that takes an array of promises and returns a single promise. This returned promise resolves when all the input promises have resolved, or it rejects if any of the input promises reject. It is useful for running multiple asynchronous operations in parallel and waiting for all of them to complete.\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = 42;\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.all([promise1, promise2, promise3]).then((values) => {\n  console.log(values); // [3, 42, 'foo']\n});\n```\n\n<!-- Update here: /questions/what-is-the-use-of-promiseall/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-use-of-promiseall/en-US.mdx)\n\n<br>\n\n### How is `Promise.all()` different from `Promise.allSettled()`?\n\n<!-- Update here: /questions/how-is-promiseall-different-from-promiseallsettled/en-US.mdx -->\n\n`Promise.all()` and `Promise.allSettled()` are both methods for handling multiple promises in JavaScript, but they behave differently. `Promise.all()` waits for all promises to resolve and fails fast if any promise rejects, returning a single rejected promise. `Promise.allSettled()`, on the other hand, waits for all promises to settle (either resolve or reject) and returns an array of objects describing the outcome of each promise.\n\n<!-- Update here: /questions/how-is-promiseall-different-from-promiseallsettled/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-is-promiseall-different-from-promiseallsettled/en-US.mdx)\n\n<br>\n\n### What is async/await and how does it simplify asynchronous code?\n\n<!-- Update here: /questions/what-is-asyncawait-and-how-does-it-simplify-asynchronous-code/en-US.mdx -->\n\n`async/await` is a modern syntax in JavaScript that simplifies working with promises. By using the `async` keyword before a function, you can use the `await` keyword inside that function to pause execution until a promise is resolved. This makes asynchronous code look and behave more like synchronous code, making it easier to read and maintain.\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/posts/1',\n    );\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\nfetchData();\n```\n\n<!-- Update here: /questions/what-is-asyncawait-and-how-does-it-simplify-asynchronous-code/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-asyncawait-and-how-does-it-simplify-asynchronous-code/en-US.mdx)\n\n<br>\n\n### How do you handle errors in asynchronous operations?\n\n<!-- Update here: /questions/how-do-you-handle-errors-in-asynchronous-operations/en-US.mdx -->\n\nTo handle errors in asynchronous operations, you can use `try...catch` blocks with `async/await` syntax or `.catch()` method with Promises. For example, with `async/await`, you can wrap your code in a `try...catch` block to catch any errors:\n\n```js live\nasync function fetchData() {\n  try {\n    // Invalid URl\n    const response = await fetch('https://api.example.com/data');\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\n\nfetchData(); // Error fetching data: ....\n```\n\nWith Promises, you can use the `.catch()` method:\n\n```js live\nfetch('https://api.example.com/data') // Invalid URl\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error fetching data:', error));\n```\n\n<!-- Update here: /questions/how-do-you-handle-errors-in-asynchronous-operations/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-handle-errors-in-asynchronous-operations/en-US.mdx)\n\n<br>\n\n### Explain the concept of a microtask queue\n\n<!-- Update here: /questions/explain-the-concept-of-a-microtask-queue/en-US.mdx -->\n\nThe microtask queue is a queue of tasks that need to be executed after the currently executing script and before any other task. Microtasks are typically used for tasks that need to be executed immediately after the current operation, such as promise callbacks. The microtask queue is processed before the macrotask queue, ensuring that microtasks are executed as soon as possible.\n\n<!-- Update here: /questions/explain-the-concept-of-a-microtask-queue/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-a-microtask-queue/en-US.mdx)\n\n<br>\n\n### What is the difference between `setTimeout()`, `setImmediate()`, and `process.nextTick()`?\n\n<!-- Update here: /questions/what-is-the-difference-between-settimeout-setimmediate-and-processnexttick/en-US.mdx -->\n\n`setTimeout()` schedules a callback to run after a minimum delay. `setImmediate()` schedules a callback to run after the current event loop completes. `process.nextTick()` schedules a callback to run before the next event loop iteration begins.\n\n```js\nsetTimeout(() => console.log('setTimeout'), 0);\nsetImmediate(() => console.log('setImmediate'));\nprocess.nextTick(() => console.log('nextTick'));\n```\n\nIn this example, `process.nextTick()` will execute first, followed by either `setTimeout()` or `setImmediate()` depending on the environment.\n\n<!-- Update here: /questions/what-is-the-difference-between-settimeout-setimmediate-and-processnexttick/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-settimeout-setimmediate-and-processnexttick/en-US.mdx)\n\n<br>\n\n### Explain how prototypal inheritance works in JavaScript\n\n<!-- Update here: /questions/explain-how-prototypal-inheritance-works/en-US.mdx -->\n\nPrototypical inheritance in JavaScript is a way for objects to inherit properties and methods from other objects. Every JavaScript object has a special hidden property called `[[Prototype]]` (commonly accessed via `__proto__` or using `Object.getPrototypeOf()`) that is a reference to another object, which is called the object's \"prototype\".\n\nWhen a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's `__proto__`, and the `__proto__`'s `__proto__` and so on, until it finds the property defined on one of the `__proto__`s or until it reaches the end of the prototype chain.\n\nThis behavior simulates classical inheritance, but it is really more of [delegation than inheritance](https://davidwalsh.name/javascript-objects).\n\nHere's an example of prototypal inheritance:\n\n```js live\n// Parent object constructor.\nfunction Animal(name) {\n  this.name = name;\n}\n\n// Add a method to the parent object's prototype.\nAnimal.prototype.makeSound = function () {\n  console.log('The ' + this.constructor.name + ' makes a sound.');\n};\n\n// Child object constructor.\nfunction Dog(name) {\n  Animal.call(this, name); // Call the parent constructor.\n}\n\n// Set the child object's prototype to be the parent's prototype.\nObject.setPrototypeOf(Dog.prototype, Animal.prototype);\n\n// Add a method to the child object's prototype.\nDog.prototype.bark = function () {\n  console.log('Woof!');\n};\n\n// Create a new instance of Dog.\nconst bolt = new Dog('Bolt');\n\n// Call methods on the child object.\nconsole.log(bolt.name); // \"Bolt\"\nbolt.makeSound(); // \"The Dog makes a sound.\"\nbolt.bark(); // \"Woof!\"\n```\n\nThings to note are:\n\n- `.makeSound` is not defined on `Dog`, so the JavaScript engine goes up the prototype chain and finds `.makeSound` on the inherited `Animal`.\n- Using `Object.create()` to build the inheritance chain is no longer recommended. Use `Object.setPrototypeOf()` instead.\n\n<!-- Update here: /questions/explain-how-prototypal-inheritance-works/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-how-prototypal-inheritance-works/en-US.mdx)\n\n<br>\n\n### What is the prototype chain and how does it work?\n\n<!-- Update here: /questions/what-is-the-prototype-chain-and-how-does-it-work/en-US.mdx -->\n\nThe prototype chain is a mechanism in JavaScript that allows objects to inherit properties and methods from other objects. When you try to access a property on an object, JavaScript will first look for the property on the object itself. If it doesn't find it, it will look at the object's prototype, and then the prototype's prototype, and so on, until it either finds the property or reaches the end of the chain, which is `null`.\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nPerson.prototype.greet = function () {\n  console.log(`Hello, my name is ${this.name}`);\n};\n\nconst alice = new Person('Alice');\nalice.greet(); // \"Hello, my name is Alice\"\n```\n\nIn this example, `alice` inherits the `greet` method from `Person.prototype`.\n\n<!-- Update here: /questions/what-is-the-prototype-chain-and-how-does-it-work/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-prototype-chain-and-how-does-it-work/en-US.mdx)\n\n<br>\n\n### Explain the difference between classical inheritance and prototypal inheritance\n\n<!-- Update here: /questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/en-US.mdx -->\n\nClassical inheritance is a model where classes inherit from other classes, typically seen in languages like Java and C++. Prototypal inheritance, used in JavaScript, involves objects inheriting directly from other objects. In classical inheritance, you define a class and create instances from it. In prototypal inheritance, you create an object and use it as a prototype for other objects.\n\n<!-- Update here: /questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/en-US.mdx)\n\n<br>\n\n### Explain the concept of inheritance in ES2015 classes\n\n<!-- Update here: /questions/explain-the-concept-of-inheritance-in-es2015-classes/en-US.mdx -->\n\nInheritance in ES2015 classes allows one class to extend another, enabling the child class to inherit properties and methods from the parent class. This is done using the `extends` keyword. The `super` keyword is used to call the constructor and methods of the parent class. Here's a quick example:\n\n```js live\nclass Animal {\n  constructor(name) {\n    this.name = name;\n  }\n\n  speak() {\n    console.log(`${this.name} makes a noise.`);\n  }\n}\n\nclass Dog extends Animal {\n  constructor(name, breed) {\n    super(name);\n    this.breed = breed;\n  }\n\n  speak() {\n    console.log(`${this.name} barks.`);\n  }\n}\n\nconst dog = new Dog('Rex', 'German Shepherd');\ndog.speak(); // Rex barks.\n```\n\n<!-- Update here: /questions/explain-the-concept-of-inheritance-in-es2015-classes/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-inheritance-in-es2015-classes/en-US.mdx)\n\n<br>\n\n### What is the purpose of the `new` keyword?\n\n<!-- Update here: /questions/what-is-the-purpose-of-the-new-keyword/en-US.mdx -->\n\nThe `new` keyword in JavaScript is used to create an instance of a user-defined object type or one of the built-in object types that has a constructor function. When you use `new`, it does four things: it creates a new object, sets the prototype, binds `this` to the new object, and returns the new object.\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person1 = new Person('Alice');\nconsole.log(person1.name); // Alice\n```\n\n<!-- Update here: /questions/what-is-the-purpose-of-the-new-keyword/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-purpose-of-the-new-keyword/en-US.mdx)\n\n<br>\n\n### How do you create a constructor function?\n\n<!-- Update here: /questions/how-do-you-create-a-constructor-function/en-US.mdx -->\n\nTo create a constructor function in JavaScript, define a regular function with a capitalized name to indicate it's a constructor. Use the `this` keyword to set properties and methods. When creating an instance, use the `new` keyword.\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\nconst john = new Person('John', 30);\nconsole.log(john.age); // 30\n```\n\n<!-- Update here: /questions/how-do-you-create-a-constructor-function/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-create-a-constructor-function/en-US.mdx)\n\n<br>\n\n### What are the differences between JavaScript ES2015 classes and ES5 function constructors?\n\n<!-- Update here: /questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx -->\n\nES2015 introduces a new way of creating classes, which provides a more intuitive and concise way to define and work with objects and inheritance compared to the ES5 function constructor syntax. Here's an example of each:\n\n```js\n// ES5 function constructor\nfunction Person(name) {\n  this.name = name;\n}\n\n// ES2015 Class\nclass Person {\n  constructor(name) {\n    this.name = name;\n  }\n}\n```\n\nFor simple constructors, they look pretty similar. The main difference in the constructor comes when using inheritance. If we want to create a `Student` class that subclasses `Person` and add a `studentId` field, this is what we have to do.\n\n```js live\n// ES5 inheritance\n// Superclass\nfunction Person1(name) {\n  this.name = name;\n}\n\n// Subclass\nfunction Student1(name, studentId) {\n  // Call constructor of superclass to initialize superclass-derived members.\n  Person1.call(this, name);\n\n  // Initialize subclass's own members.\n  this.studentId = studentId;\n}\nStudent1.prototype = Object.create(Person1.prototype);\nStudent1.prototype.constructor = Student1;\n\nconst student1 = new Student1('John', 1234);\nconsole.log(student1.name, student1.studentId); // \"John\" 1234\n\n// ES2015 inheritance\n// Superclass\nclass Person2 {\n  constructor(name) {\n    this.name = name;\n  }\n}\n\n// Subclass\nclass Student2 extends Person2 {\n  constructor(name, studentId) {\n    super(name);\n    this.studentId = studentId;\n  }\n}\n\nconst student2 = new Student2('Alice', 5678);\nconsole.log(student2.name, student2.studentId); // \"Alice\" 5678\n```\n\nIt's much more verbose to use inheritance in ES5 and the ES2015 version is easier to understand and remember.\n\n**Comparison of ES5 function constructors vs ES2015 classes**\n\n| Feature | ES5 Function Constructor | ES2015 Class |\n| --- | --- | --- |\n| Syntax | Uses function constructors and prototypes | Uses `class` keyword |\n| Constructor | Function with properties assigned using `this` | `constructor` method inside the class |\n| Method Definition | Defined on the prototype | Defined inside the class body |\n| Static Methods | Added directly to the constructor function | Defined using the `static` keyword |\n| Inheritance | Uses `Object.create()` and manually sets prototype chain | Uses `extends` keyword and `super` function |\n| Readability | Less intuitive and more verbose | More concise and intuitive |\n\n<!-- Update here: /questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx)\n\n<br>\n\n### What advantage is there for using the JavaScript arrow syntax for a method in a constructor?\n\n<!-- Update here: /questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx -->\n\nThe main advantage of using an arrow function as a method inside a constructor is that the value of `this` gets set at the time of the function creation and can't change after that. When the constructor is used to create a new object, `this` will always refer to that object.\n\nFor example, let's say we have a `Person` constructor that takes a first name as an argument has two methods to `console.log()` that name, one as a regular function and one as an arrow function:\n\n```js live\nconst Person = function (name) {\n  this.firstName = name;\n  this.sayName1 = function () {\n    console.log(this.firstName);\n  };\n  this.sayName2 = () => {\n    console.log(this.firstName);\n  };\n};\n\nconst john = new Person('John');\nconst dave = new Person('Dave');\n\njohn.sayName1(); // John\njohn.sayName2(); // John\n\n// The regular function can have its `this` value changed, but the arrow function cannot\njohn.sayName1.call(dave); // Dave (because `this` is now the dave object)\njohn.sayName2.call(dave); // John\n\njohn.sayName1.apply(dave); // Dave (because `this` is now the dave object)\njohn.sayName2.apply(dave); // John\n\njohn.sayName1.bind(dave)(); // Dave (because `this` is now the dave object)\njohn.sayName2.bind(dave)(); // John\n\nconst sayNameFromWindow1 = john.sayName1;\nsayNameFromWindow1(); // undefined (because `this` is now the window object)\n\nconst sayNameFromWindow2 = john.sayName2;\nsayNameFromWindow2(); // John\n```\n\nThe main takeaway here is that `this` can be changed for a normal function, but `this` always stays the same for an arrow function. So even if you are passing around your arrow function to different parts of your application, you wouldn't have to worry about the value of `this` changing.\n\n<!-- Update here: /questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx)\n\n<br>\n\n### Why might you want to create static class members in JavaScript?\n\n<!-- Update here: /questions/why-you-might-want-to-create-static-class-members/en-US.mdx -->\n\nStatic class members (properties/methods) has a `static` keyword prepended. Such members cannot be directly accessed on instances of the class. Instead, they're accessed on the class itself.\n\n```js live\nclass Car {\n  static noOfWheels = 4;\n  static compare() {\n    return 'Static method has been called.';\n  }\n}\n\nconsole.log(Car.noOfWheels); // 4\n```\n\nStatic members are useful under the following scenarios:\n\n- **Namespace organization**: Static properties can be used to define constants or configuration values that are specific to a class. This helps organize related data within the class namespace and prevents naming conflicts with other variables. Examples include `Math.PI`, `Math.SQRT2`.\n- **Helper functions**: Static methods can be used as helper functions that operate on the class itself or its instances. This can improve code readability and maintainability by separating utility logic from the core functionality of the class. Examples of frequently used static methods include `Object.assign()`, `Math.max()`.\n- **Singleton pattern**: In some rare cases, static properties and methods can be used to implement a singleton pattern, where only one instance of a class ever exists. However, this pattern can be tricky to manage and is generally discouraged in favor of more modern dependency injection techniques.\n\n<!-- Update here: /questions/why-you-might-want-to-create-static-class-members/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-you-might-want-to-create-static-class-members/en-US.mdx)\n\n<br>\n\n### What is a closure in JavaScript, and how/why would you use one?\n\n<!-- Update here: /questions/what-is-a-closure-and-how-why-would-you-use-one/en-US.mdx -->\n\nIn the book [\"You Don't Know JS\"](https://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/scope-closures) (YDKJS) by Kyle Simpson, a closure is defined as follows:\n\n> Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope\n\nIn simple terms, functions have access to variables that were in their scope at the time of their creation. This is what we call the function's lexical scope. A closure is a function that retains access to these variables even after the outer function has finished executing. This is like the function has a memory of its original environment.\n\n```js live\nfunction outerFunction() {\n  const outerVar = 'I am outside of innerFunction';\n\n  function innerFunction() {\n    console.log(outerVar); // `innerFunction` can still access `outerVar`.\n  }\n\n  return innerFunction;\n}\n\nconst inner = outerFunction(); // `inner` now holds a reference to `innerFunction`.\n\ninner(); // \"I am outside of innerFunction\"\n// Even though `outerFunction` has completed execution, `inner` still has access to variables defined inside `outerFunction`.\n```\n\nKey points to remember:\n\n- Closure occurs when an inner function has access to variables in its outer (lexical) scope, even when the outer function has finished executing.\n- Closure allows a function to **remember** the environment in which it was created, even if that environment is no longer present.\n- Closures are used extensively in JavaScript, such as in callbacks, event handlers, and asynchronous functions.\n\n<!-- Update here: /questions/what-is-a-closure-and-how-why-would-you-use-one/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-a-closure-and-how-why-would-you-use-one/en-US.mdx)\n\n<br>\n\n### Explain the concept of lexical scoping\n\n<!-- Update here: /questions/explain-the-concept-of-lexical-scoping/en-US.mdx -->\n\nLexical scoping means that the scope of a variable is determined by its location within the source code, and nested functions have access to variables declared in their outer scope. For example:\n\n```js live\nfunction outerFunction() {\n  let outerVariable = 'I am outside!';\n\n  function innerFunction() {\n    console.log(outerVariable); // 'I am outside!'\n  }\n\n  innerFunction();\n}\n\nouterFunction();\n```\n\nIn this example, `innerFunction` can access `outerVariable` because of lexical scoping.\n\n<!-- Update here: /questions/explain-the-concept-of-lexical-scoping/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-lexical-scoping/en-US.mdx)\n\n<br>\n\n### Explain the concept of scope in JavaScript\n\n<!-- Update here: /questions/explain-the-concept-of-scope-in-javascript/en-US.mdx -->\n\nIn JavaScript, scope determines the accessibility of variables and functions at different parts of the code. There are three main types of scope: global scope, function scope, and block scope. Global scope means the variable is accessible everywhere in the code. Function scope means the variable is accessible only within the function it is declared. Block scope, introduced with ES6, means the variable is accessible only within the block (e.g., within curly braces `{}`) it is declared.\n\n```js live\nvar globalVar = 'I am a global var';\n\nfunction myFunction() {\n  var functionVar = 'I am a function-scoped var';\n\n  if (true) {\n    let blockVar = 'I am a block-scoped var';\n\n    console.log('Inside block:');\n    console.log(globalVar); // Accessible\n    console.log(functionVar); // Accessible\n    console.log(blockVar); // Accessible\n  }\n\n  console.log('Inside function:');\n  console.log(globalVar); // Accessible\n  console.log(functionVar); // Accessible\n  // console.log(blockVar); // Uncaught ReferenceError\n}\n\nmyFunction();\n\nconsole.log('In global scope:');\nconsole.log(globalVar); // Accessible\n// console.log(functionVar); // Uncaught ReferenceError\n// console.log(blockVar); // Uncaught ReferenceError\n```\n\n<!-- Update here: /questions/explain-the-concept-of-scope-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-scope-in-javascript/en-US.mdx)\n\n<br>\n\n### How can closures be used to create private variables?\n\n<!-- Update here: /questions/how-can-closures-be-used-to-create-private-variables/en-US.mdx -->\n\nClosures in JavaScript can be used to create private variables by defining a function within another function. The inner function has access to the outer function's variables, but those variables are not accessible from outside the outer function. This allows you to encapsulate and protect the variables from being accessed or modified directly.\n\n```js live\nfunction createCounter() {\n  let count = 0; // private variable\n\n  return {\n    increment: function () {\n      count++;\n      return count;\n    },\n    decrement: function () {\n      count--;\n      return count;\n    },\n    getCount: function () {\n      return count;\n    },\n  };\n}\n\nconst counter = createCounter();\nconsole.log(counter.increment()); // 1\nconsole.log(counter.getCount()); // 1\nconsole.log(counter.count); // undefined\n```\n\n<!-- Update here: /questions/how-can-closures-be-used-to-create-private-variables/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-closures-be-used-to-create-private-variables/en-US.mdx)\n\n<br>\n\n### What are the potential pitfalls of using closures?\n\n<!-- Update here: /questions/what-are-the-potential-pitfalls-of-using-closures/en-US.mdx -->\n\nClosures can lead to memory leaks if not managed properly, especially when they capture variables that are no longer needed. They can also make debugging more difficult due to the complexity of the scope chain. Additionally, closures can cause performance issues if they are overused or used inappropriately, as they keep references to variables in their scope, which can prevent garbage collection.\n\n<!-- Update here: /questions/what-are-the-potential-pitfalls-of-using-closures/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-potential-pitfalls-of-using-closures/en-US.mdx)\n\n<br>\n\n### Explain the difference between global scope, function scope, and block scope\n\n<!-- Update here: /questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx -->\n\nGlobal scope means variables are accessible from anywhere in the code. Function scope means variables are accessible only within the function they are declared in. Block scope means variables are accessible only within the block (e.g., within `{}`) they are declared in.\n\n```js live\nvar globalVar = \"I'm global\"; // Global scope\n\nfunction myFunction() {\n  var functionVar = \"I'm in a function\"; // Function scope\n  if (true) {\n    let blockVar = \"I'm in a block\"; // Block scope\n    console.log(blockVar); // Accessible here\n  }\n  // console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined\n}\n// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined\nmyFunction();\n```\n\n<!-- Update here: /questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx)\n\n<br>\n\n### Explain how `this` works in JavaScript\n\n<!-- Update here: /questions/explain-how-this-works-in-javascript/en-US.mdx -->\n\nThere's no simple explanation for `this`; it is one of the most confusing concepts in JavaScript because it's behavior differs from many other programming languages. The one-liner explanation of the `this` keyword is that it is a dynamic reference to the context in which a function is executed.\n\nA longer explanation is that `this` follows these rules:\n\n1. If the `new` keyword is used when calling the function, meaning the function was used as a function constructor, the `this` inside the function is the newly-created object instance.\n2. If `this` is used in a `class` `constructor`, the `this` inside the `constructor` is the newly-created object instance.\n3. If `apply()`, `call()`, or `bind()` is used to call/create a function, `this` inside the function is the object that is passed in as the argument.\n4. If a function is called as a method (e.g. `obj.method()`) — `this` is the object that the function is a property of.\n5. If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, `this` is the global object. In the browser, the global object is the `window` object. If in strict mode (`'use strict';`), `this` will be `undefined` instead of the global object.\n6. If multiple of the above rules apply, the rule that is higher wins and will set the `this` value.\n7. If the function is an ES2015 arrow function, it ignores all the rules above and receives the `this` value of its surrounding scope at the time it is created.\n\nFor an in-depth explanation, do check out [Arnav Aggrawal's article on Medium](https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3).\n\n<!-- Update here: /questions/explain-how-this-works-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-how-this-works-in-javascript/en-US.mdx)\n\n<br>\n\n### Explain `Function.prototype.bind` in JavaScript\n\n<!-- Update here: /questions/explain-function-prototype-bind/en-US.mdx -->\n\n`Function.prototype.bind` is a method in JavaScript that allows you to create a new function with a specific `this` value and optional initial arguments. It's primary purpose is to:\n\n- **Binding `this` value to preserve context**: The primary purpose of `bind` is to bind the `this` value of a function to a specific object. When you call `func.bind(thisArg)`, it creates a new function with the same body as `func`, but with `this` permanently bound to `thisArg`.\n- **Partial application of arguments**: `bind` also allows you to pre-specify arguments for the new function. Any arguments passed to `bind` after `thisArg` will be prepended to the arguments list when the new function is called.\n- **Method borrowing**: `bind` allows you to borrow methods from one object and apply them to another object, even if they were not originally designed to work with that object.\n\nThe `bind` method is particularly useful in scenarios where you need to ensure that a function is called with a specific `this` context, such as in event handlers, callbacks, or method borrowing.\n\n<!-- Update here: /questions/explain-function-prototype-bind/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-function-prototype-bind/en-US.mdx)\n\n<br>\n\n### Explain the different ways the `this` keyword can be bound\n\n<!-- Update here: /questions/explain-the-different-ways-the-this-keyword-can-be-bound/en-US.mdx -->\n\nThe `this` keyword in JavaScript can be bound in several ways:\n\n- Default binding: In non-strict mode, `this` refers to the global object (window in browsers). In strict mode, `this` is `undefined`.\n- Implicit binding: When a function is called as a method of an object, `this` refers to the object.\n- Explicit binding: Using `call`, `apply`, or `bind` methods to explicitly set `this`.\n- New binding: When a function is used as a constructor with the `new` keyword, `this` refers to the newly created object.\n- Arrow functions: Arrow functions do not have their own `this` and inherit `this` from the surrounding lexical context.\n\n<!-- Update here: /questions/explain-the-different-ways-the-this-keyword-can-be-bound/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-different-ways-the-this-keyword-can-be-bound/en-US.mdx)\n\n<br>\n\n### What are the common pitfalls of using the `this` keyword?\n\n<!-- Update here: /questions/what-are-the-common-pitfalls-of-using-the-this-keyword/en-US.mdx -->\n\nThe `this` keyword in JavaScript can be tricky because its value depends on how a function is called. Common pitfalls include losing the context of `this` when passing methods as callbacks, using `this` in nested functions, and misunderstanding `this` in arrow functions. To avoid these issues, you can use `.bind()`, arrow functions, or store the context in a variable.\n\n<!-- Update here: /questions/what-are-the-common-pitfalls-of-using-the-this-keyword/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-common-pitfalls-of-using-the-this-keyword/en-US.mdx)\n\n<br>\n\n### Explain the concept of `this` binding in event handlers\n\n<!-- Update here: /questions/explain-the-concept-of-this-binding-in-event-handlers/en-US.mdx -->\n\nIn JavaScript, the `this` keyword refers to the object that is currently executing the code. In event handlers, `this` typically refers to the element that triggered the event. However, the value of `this` can change depending on how the event handler is defined and called. To ensure `this` refers to the desired object, you can use methods like `bind()`, arrow functions, or assign the context explicitly.\n\n<!-- Update here: /questions/explain-the-concept-of-this-binding-in-event-handlers/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-this-binding-in-event-handlers/en-US.mdx)\n\n<br>\n\n### What is the DOM and how is it structured?\n\n<!-- Update here: /questions/what-is-the-dom-and-how-is-it-structured/en-US.mdx -->\n\nThe DOM, or Document Object Model, is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM is structured as a tree of objects, where each node represents part of the document, such as elements, attributes, and text.\n\n<!-- Update here: /questions/what-is-the-dom-and-how-is-it-structured/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-dom-and-how-is-it-structured/en-US.mdx)\n\n<br>\n\n### What's the difference between an \"attribute\" and a \"property\" in the DOM?\n\n<!-- Update here: /questions/whats-the-difference-between-an-attribute-and-a-property/en-US.mdx -->\n\nAttributes are defined in the HTML and provide initial values for properties. Properties are part of the DOM and represent the current state of an element. For example, the `value` attribute of an `<input>` element sets its initial value, while the `value` property reflects the current value as the user interacts with it.\n\n<!-- Update here: /questions/whats-the-difference-between-an-attribute-and-a-property/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/whats-the-difference-between-an-attribute-and-a-property/en-US.mdx)\n\n<br>\n\n### Explain the difference between `document.querySelector()` and `document.getElementById()`\n\n<!-- Update here: /questions/explain-the-difference-between-documentqueryselector-and-documentgetelementbyid/en-US.mdx -->\n\n`document.querySelector()` and `document.getElementById()` are both methods used to select elements from the DOM, but they have key differences. `document.querySelector()` can select any element using a CSS selector and returns the first match, while `document.getElementById()` selects an element by its ID and returns the element with that specific ID.\n\n```js\n// Using document.querySelector()\nconst element = document.querySelector('.my-class');\n\n// Using document.getElementById()\nconst elementById = document.getElementById('my-id');\n```\n\n<!-- Update here: /questions/explain-the-difference-between-documentqueryselector-and-documentgetelementbyid/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-documentqueryselector-and-documentgetelementbyid/en-US.mdx)\n\n<br>\n\n### How do you add, remove, and modify HTML elements using JavaScript?\n\n<!-- Update here: /questions/how-do-you-add-remove-and-modify-html-elements-using-javascript/en-US.mdx -->\n\nTo add, remove, and modify HTML elements using JavaScript, you can use methods like `createElement`, `appendChild`, `removeChild`, and properties like `innerHTML` and `textContent`. For example, to add an element, you can create it using `document.createElement` and then append it to a parent element using `appendChild`. To remove an element, you can use `removeChild` on its parent. To modify an element, you can change its `innerHTML` or `textContent`.\n\n```js\n// Adding an element\nconst newElement = document.createElement('div');\nnewElement.textContent = 'Hello, World!';\ndocument.body.appendChild(newElement);\n\n// Removing an element\nconst elementToRemove = document.getElementById('elementId');\nelementToRemove.parentNode.removeChild(elementToRemove);\n\n// Modifying an element\nconst elementToModify = document.getElementById('elementId');\nelementToModify.innerHTML = 'New Content';\n```\n\n<!-- Update here: /questions/how-do-you-add-remove-and-modify-html-elements-using-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-add-remove-and-modify-html-elements-using-javascript/en-US.mdx)\n\n<br>\n\n### What are event listeners and how are they used?\n\n<!-- Update here: /questions/what-are-event-listeners-and-how-are-they-used/en-US.mdx -->\n\nEvent listeners are functions that wait for specific events to occur on elements, such as clicks or key presses. They are used to execute code in response to these events. You can add an event listener to an element using the `addEventListener` method. For example:\n\n```js\ndocument.getElementById('myButton').addEventListener('click', function () {\n  alert('Button was clicked!');\n});\n```\n\n<!-- Update here: /questions/what-are-event-listeners-and-how-are-they-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-event-listeners-and-how-are-they-used/en-US.mdx)\n\n<br>\n\n### Explain the event phases in a browser\n\n<!-- Update here: /questions/explain-the-event-phases-in-a-browser/en-US.mdx -->\n\nIn a browser, events go through three phases: capturing, target, and bubbling. During the capturing phase, the event travels from the root to the target element. In the target phase, the event reaches the target element. Finally, in the bubbling phase, the event travels back up from the target element to the root. You can control event handling using `addEventListener` with the `capture` option.\n\n<!-- Update here: /questions/explain-the-event-phases-in-a-browser/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-event-phases-in-a-browser/en-US.mdx)\n\n<br>\n\n### Describe event bubbling in JavaScript and browsers\n\n<!-- Update here: /questions/describe-event-bubbling/en-US.mdx -->\n\nEvent bubbling is a DOM event propagation mechanism where an event (e.g. a click), starts at the target element and bubbles up to the root of the document. This allows ancestor elements to also respond to the event.\n\nEvent bubbling is essential for event delegation, where a single event handler manages events for multiple child elements, enhancing performance and code simplicity. While convenient, failing to manage event propagation properly can lead to unintended behavior, such as multiple handlers firing for a single event.\n\n<!-- Update here: /questions/describe-event-bubbling/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-event-bubbling/en-US.mdx)\n\n<br>\n\n### Describe event capturing in JavaScript and browsers\n\n<!-- Update here: /questions/describe-event-capturing/en-US.mdx -->\n\nEvent capturing is a lesser-used counterpart to [event bubbling](https://www.greatfrontend.com/questions/quiz/describe-event-bubbling) in the DOM event propagation mechanism. It follows the opposite order, where an event triggers first on the ancestor element and then travels down to the target element.\n\nEvent capturing is rarely used as compared to event bubbling, but it can be used in specific scenarios where you need to intercept events at a higher level before they reach the target element. It is disabled by default but can be enabled through an option on `addEventListener()`.\n\n<!-- Update here: /questions/describe-event-capturing/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-event-capturing/en-US.mdx)\n\n<br>\n\n### Explain event delegation in JavaScript\n\n<!-- Update here: /questions/explain-event-delegation/en-US.mdx -->\n\nEvent delegation is a technique in JavaScript where a single event listener is attached to a parent element instead of attaching event listeners to multiple child elements. When an event occurs on a child element, the event bubbles up the DOM tree, and the parent element's event listener handles the event based on the target element.\n\nEvent delegation provides the following benefits:\n\n- **Improved performance**: Attaching a single event listener is more efficient than attaching multiple event listeners to individual elements, especially for large or dynamic lists. This reduces memory usage and improves overall performance.\n- **Simplified event handling**: With event delegation, you only need to write the event handling logic once in the parent element's event listener. This makes the code more maintainable and easier to update.\n- **Dynamic element support**: Event delegation automatically handles events for dynamically added or removed elements within the parent element. There's no need to manually attach or remove event listeners when the DOM structure changes\n\nHowever, do note that:\n\n- It is important to identify the target element that triggered the event.\n- Not all events can be delegated because they are not bubbled. Non-bubbling events include: `focus`, `blur`, `scroll`, `mouseenter`, `mouseleave`, `resize`, etc.\n\n<!-- Update here: /questions/explain-event-delegation/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-event-delegation/en-US.mdx)\n\n<br>\n\n### How do you prevent the default behavior of an event?\n\n<!-- Update here: /questions/how-do-you-prevent-the-default-behavior-of-an-event/en-US.mdx -->\n\nTo prevent the default behavior of an event in JavaScript, you can use the `preventDefault` method on the event object. For example, if you want to prevent a form from submitting, you can do the following:\n\n```js\ndocument.querySelector('form').addEventListener('submit', function (event) {\n  event.preventDefault();\n});\n```\n\nThis method stops the default action associated with the event from occurring.\n\n<!-- Update here: /questions/how-do-you-prevent-the-default-behavior-of-an-event/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-prevent-the-default-behavior-of-an-event/en-US.mdx)\n\n<br>\n\n### What is the difference between `event.preventDefault()` and `event.stopPropagation()`?\n\n<!-- Update here: /questions/what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation/en-US.mdx -->\n\n`event.preventDefault()` is used to prevent the default action that belongs to the event, such as preventing a form from submitting. `event.stopPropagation()` is used to stop the event from bubbling up to parent elements, preventing any parent event handlers from being executed.\n\n<!-- Update here: /questions/what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation/en-US.mdx)\n\n<br>\n\n### What is the difference between `mouseenter` and `mouseover` event in JavaScript and browsers?\n\n<!-- Update here: /questions/what-is-the-difference-between-mouseenter-and-mouseover-event/en-US.mdx -->\n\nThe main difference lies in the bubbling behavior of `mouseenter` and `mouseover` events. `mouseenter` does not bubble while `mouseover` bubbles.\n\n`mouseenter` events do not bubble. The `mouseenter` event is triggered only when the mouse pointer enters the element itself, not its descendants. If a parent element has child elements, and the mouse pointer enters child elements, the `mouseenter` event will not be triggered on the parent element again, it's only triggered once upon entry of parent element without regard for its contents. If both parent and child have `mouseenter` listeners attached and the mouse pointer moves from the parent element to the child element, `mouseenter` will only fire for the child.\n\n`mouseover` events bubble up the DOM tree. The `mouseover` event is triggered when the mouse pointer enters the element or one of its descendants. If a parent element has child elements, and the mouse pointer enters child elements, the `mouseover` event will be triggered on the parent element again as well. If the parent element has multiple child elements, this can result in multiple event callbacks fired. If there are child elements, and the mouse pointer moves from the parent element to the child element, `mouseover` will fire for both the parent and the child.\n\n| Property | `mouseenter` | `mouseover` |\n| --- | --- | --- |\n| Bubbling | No | Yes |\n| Trigger | Only when entering itself | When entering itself and when entering descendants |\n\n<!-- Update here: /questions/what-is-the-difference-between-mouseenter-and-mouseover-event/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-mouseenter-and-mouseover-event/en-US.mdx)\n\n<br>\n\n### What is the difference between `innerHTML` and `textContent`?\n\n<!-- Update here: /questions/what-is-the-difference-between-innerhtml-and-textcontent/en-US.mdx -->\n\n`innerHTML` and `textContent` are both properties used to get or set the content of an HTML element, but they serve different purposes. `innerHTML` returns or sets the HTML markup contained within the element, which means it can parse and render HTML tags. On the other hand, `textContent` returns or sets the text content of the element, ignoring any HTML tags and rendering them as plain text.\n\n```js\n// Example of innerHTML\nelement.innerHTML = '<strong>Bold Text</strong>'; // Renders as bold text\n\n// Example of textContent\nelement.textContent = '<strong>Bold Text</strong>'; // Renders as plain text: <strong>Bold Text</strong>\n```\n\n<!-- Update here: /questions/what-is-the-difference-between-innerhtml-and-textcontent/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-innerhtml-and-textcontent/en-US.mdx)\n\n<br>\n\n### How do you manipulate CSS styles using JavaScript?\n\n<!-- Update here: /questions/how-do-you-manipulate-css-styles-using-javascript/en-US.mdx -->\n\nYou can manipulate CSS styles using JavaScript by accessing the `style` property of an HTML element. For example, to change the background color of a `div` element with the id `myDiv`, you can use:\n\n```js\ndocument.getElementById('myDiv').style.backgroundColor = 'blue';\n```\n\nYou can also add, remove, or toggle CSS classes using the `classList` property:\n\n```js\ndocument.getElementById('myDiv').classList.add('newClass');\ndocument.getElementById('myDiv').classList.remove('oldClass');\ndocument.getElementById('myDiv').classList.toggle('toggleClass');\n```\n\n<!-- Update here: /questions/how-do-you-manipulate-css-styles-using-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-manipulate-css-styles-using-javascript/en-US.mdx)\n\n<br>\n\n### Describe the difference between `<script>`, `<script async>` and `<script defer>`\n\n<!-- Update here: /questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx -->\n\nAll of these ways (`<script>`, `<script async>`, and `<script defer>`) are used to load and execute JavaScript files in an HTML document, but they differ in how the browser handles loading and execution of the script:\n\n- `<script>` is the default way of including JavaScript. The browser blocks HTML parsing while the script is being downloaded and executed. The browser will not continue rendering the page until the script has finished executing.\n- `<script async>` downloads the script asynchronously, in parallel with parsing the HTML. Executes the script as soon as it is available, potentially interrupting the HTML parsing. `<script async>` do not wait for each other and execute in no particular order.\n- `<script defer>` downloads the script asynchronously, in parallel with parsing the HTML. However, the execution of the script is deferred until HTML parsing is complete, in the order they appear in the HTML.\n\nHere's a table summarizing the 3 ways of loading `<script>`s in a HTML document.\n\n| Feature | `<script>` | `<script async>` | `<script defer>` |\n| --- | --- | --- | --- |\n| Parsing behavior | Blocks HTML parsing | Runs parallel to parsing | Runs parallel to parsing |\n| Execution order | In order of appearance | Not guaranteed | In order of appearance |\n| DOM dependency | No | No | Yes (waits for DOM) |\n\n<!-- Update here: /questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx)\n\n<br>\n\n### What is the difference between the Window object and the Document object?\n\n<!-- Update here: /questions/what-is-the-difference-between-the-window-object-and-the-document-object/en-US.mdx -->\n\nThe `Window` object represents the browser window and provides methods to control it, such as opening new windows or accessing the browser history. The `Document` object represents the content of the web page loaded in the window and provides methods to manipulate the DOM, such as selecting elements or modifying their content.\n\n<!-- Update here: /questions/what-is-the-difference-between-the-window-object-and-the-document-object/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-the-window-object-and-the-document-object/en-US.mdx)\n\n<br>\n\n### Describe the difference between a cookie, `sessionStorage` and `localStorage` in browsers\n\n<!-- Update here: /questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.mdx -->\n\nAll of the following are mechanisms of storing data on the client, the user's browser in this case. `localStorage` and `sessionStorage` both implement the [Web Storage API interface](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API).\n\n- **Cookies**: Suitable for server-client communication, small storage capacity, can be persistent or session-based, domain-specific. Sent to the server on every request.\n- **`localStorage`**: Suitable for long-term storage, data persists even after the browser is closed, accessible across all tabs and windows of the same origin, highest storage capacity among the three.\n- **`sessionStorage`**: Suitable for temporary data within a single page session, data is cleared when the tab or window is closed, has a higher storage capacity compared to cookies.\n\nHere's a table summarizing the 3 client storage mechanisms.\n\n| Property | Cookie | `localStorage` | `sessionStorage` |\n| --- | --- | --- | --- |\n| Initiator | Client or server. Server can use `Set-Cookie` header | Client | Client |\n| Lifespan | As specified | Until deleted | Until tab is closed |\n| Persistent across browser sessions | If a future expiry date is set | Yes | No |\n| Sent to server with every HTTP request | Yes, sent via `Cookie` header | No | No |\n| Total capacity (per domain) | 4kb | 5MB | 5MB |\n| Access | Across windows/tabs | Across windows/tabs | Same tab |\n| Security | JavaScript cannot access `HttpOnly` cookies | None | None |\n\n<!-- Update here: /questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.mdx)\n\n<br>\n\n### How do you make an HTTP request using the Fetch API?\n\n<!-- Update here: /questions/how-do-you-make-an-http-request-using-the-fetch-api/en-US.mdx -->\n\nTo make an HTTP request using the Fetch API, you can use the `fetch` function, which returns a promise. You can handle the response using `.then()` and `.catch()` for error handling. Here's a basic example of a GET request:\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\nFor a POST request, you can pass an options object as the second argument to `fetch`:\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/posts', {\n  method: 'POST',\n  body: JSON.stringify({\n    title: 'foo',\n    body: 'bar',\n    userId: 1,\n  }),\n  headers: {\n    'Content-Type': 'application/json; charset=UTF-8',\n  },\n})\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\n<!-- Update here: /questions/how-do-you-make-an-http-request-using-the-fetch-api/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-make-an-http-request-using-the-fetch-api/en-US.mdx)\n\n<br>\n\n### What are the different ways to make an API call in JavaScript?\n\n<!-- Update here: /questions/what-are-the-different-ways-to-make-an-api-call-in-javascript/en-US.mdx -->\n\nIn JavaScript, you can make API calls using several methods. The most common ones are `XMLHttpRequest`, `fetch`, and third-party libraries like `Axios`. `XMLHttpRequest` is the traditional way but is more verbose. `fetch` is modern and returns promises, making it easier to work with. `Axios` is a popular third-party library that simplifies API calls and provides additional features.\n\n<!-- Update here: /questions/what-are-the-different-ways-to-make-an-api-call-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-different-ways-to-make-an-api-call-in-javascript/en-US.mdx)\n\n<br>\n\n### Explain AJAX in as much detail as possible\n\n<!-- Update here: /questions/explain-ajax-in-as-much-detail-as-possible/en-US.mdx -->\n\nAJAX (Asynchronous JavaScript and XML) facilitates asynchronous communication between the client and server, enabling dynamic updates to web pages without reloading. It uses techniques like `XMLHttpRequest` or the `fetch()` API to send and receive data in the background. In modern web applications, the `fetch()` API is more commonly used to implement AJAX.\n\n**Using `XMLHttpRequest`**\n\n```js live\nlet xhr = new XMLHttpRequest();\nxhr.onreadystatechange = function () {\n  if (xhr.readyState === XMLHttpRequest.DONE) {\n    if (xhr.status === 200) {\n      console.log(xhr.responseText);\n    } else {\n      console.error('Request failed: ' + xhr.status);\n    }\n  }\n};\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.send();\n```\n\n**Using `fetch()`**\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Fetch error:', error));\n```\n\n<!-- Update here: /questions/explain-ajax-in-as-much-detail-as-possible/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-ajax-in-as-much-detail-as-possible/en-US.mdx)\n\n<br>\n\n### What are the advantages and disadvantages of using AJAX?\n\n<!-- Update here: /questions/what-are-the-advantages-and-disadvantages-of-using-ajax/en-US.mdx -->\n\nAJAX (Asynchronous JavaScript and XML) is a technique in JavaScript that allows web pages to send and retrieve data asynchronously from servers without refreshing or reloading the entire page.\n\n**Advantages**\n\n- **Smoother user experience**: Updates happen without full page reloads, like in mail and chat applications.\n- **Lighter server Load**: Only necessary data is fetched via AJAX, reducing server load and improving perceived performance of webpages.\n- **Maintains client state**: User interactions and any client states are persisted within the page.\n\n**Disadvantages**\n\n- **Reliance on JavaScript**: If disabled, Ajax functionality breaks.\n- **Bookmarking issues**: Dynamic content makes bookmarking specific page states difficult.\n- **SEO Challenges**: Search engines may struggle to index dynamic content.\n- **Performance Concerns**: Processing Ajax data on low-end devices can be slow.\n\n<!-- Update here: /questions/what-are-the-advantages-and-disadvantages-of-using-ajax/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-advantages-and-disadvantages-of-using-ajax/en-US.mdx)\n\n<br>\n\n### What are the differences between `XMLHttpRequest` and `fetch()` in JavaScript and browsers?\n\n<!-- Update here: /questions/what-are-the-differences-between-xmlhttprequest-and-fetch/en-US.mdx -->\n\n`XMLHttpRequest` (XHR) and `fetch()` API are both used for asynchronous HTTP requests in JavaScript (AJAX). `fetch()` offers a cleaner syntax, promise-based approach, and more modern feature set compared to XHR. However, there are some differences:\n\n- `XMLHttpRequest` event callbacks, while `fetch()` utilizes promise chaining.\n- `fetch()` provides more flexibility in headers and request bodies.\n- `fetch()` support cleaner error handling with `catch()`.\n- Handling caching with `XMLHttpRequest` is difficult but caching is supported by `fetch()` by default in the `options.cache` object (`cache` value of second parameter) to `fetch()` or `Request()`.\n- `fetch()` requires an `AbortController` for cancelation, while for `XMLHttpRequest`, it provides `abort()` property.\n- `XMLHttpRequest` has good support for progress tracking, which `fetch()` lacks.\n- `XMLHttpRequest` is only available in the browser and not natively supported in Node.js environments. On the other hand `fetch()` is part of the JavaScript language and is supported on all modern JavaScript runtimes.\n\nThese days `fetch()` is preferred for its cleaner syntax and modern features.\n\n<!-- Update here: /questions/what-are-the-differences-between-xmlhttprequest-and-fetch/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-xmlhttprequest-and-fetch/en-US.mdx)\n\n<br>\n\n### How do you abort a web request using `AbortController` in JavaScript?\n\n<!-- Update here: /questions/how-do-you-abort-a-web-request-using-abortcontrollers/en-US.mdx -->\n\n`AbortController` is used to cancel ongoing asynchronous operations like fetch requests.\n\n```js live\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nfetch('https://jsonplaceholder.typicode.com/todos/1', { signal })\n  .then((response) => {\n    // Handle response\n  })\n  .catch((error) => {\n    if (error.name === 'AbortError') {\n      console.log('Request aborted');\n    } else {\n      console.error('Error:', error);\n    }\n  });\n\n// Call abort() to abort the request\ncontroller.abort();\n```\n\nAborting web requests is useful for:\n\n- Canceling requests based on user actions.\n- Prioritizing the latest requests in scenarios with multiple simultaneous requests.\n- Canceling requests that are no longer needed, e.g. after the user has navigated away from the page.\n\n<!-- Update here: /questions/how-do-you-abort-a-web-request-using-abortcontrollers/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-abort-a-web-request-using-abortcontrollers/en-US.mdx)\n\n<br>\n\n### Explain how JSONP works (and how it's not really Ajax)\n\n<!-- Update here: /questions/explain-how-jsonp-works-and-how-its-not-really-ajax/en-US.mdx -->\n\nJSONP (JSON with Padding) is a technique used to overcome the same-origin policy in web browsers, allowing you to request data from a server in a different domain. It works by dynamically creating a `<script>` tag and setting its `src` attribute to the URL of the data source. The server responds with a script that calls a predefined callback function with the data as its argument. Unlike Ajax, JSONP does not use the XMLHttpRequest object and is limited to GET requests.\n\n<!-- Update here: /questions/explain-how-jsonp-works-and-how-its-not-really-ajax/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-how-jsonp-works-and-how-its-not-really-ajax/en-US.mdx)\n\n<br>\n\n### What are workers in JavaScript used for?\n\n<!-- Update here: /questions/what-are-workers-in-javascript-used-for/en-US.mdx -->\n\nWorkers in JavaScript are background threads that allow you to run scripts in parallel with the main execution thread, without blocking or interfering with the user interface. Their key features include:\n\n- **Parallel processing**: Workers run in a separate thread from the main thread, allowing your web page to remain responsive to user interactions while the worker performs its tasks. It's useful for moving CPU-intensive work off the main thread and be free from JavaScript's single-threaded nature.\n- **Communication**: Uses `postMessage()` and `onmessage`/ `'message'` event for messaging.\n- **Access to web APIs**: Workers have access to various Web APIs, including `fetch()`, IndexedDB, and Web Storage, allowing them to perform tasks like data fetching and persisting data independently.\n- **No DOM access**: Workers cannot directly manipulate the DOM, thus cannot interact with the UI, ensuring they don't accidentally interfere with the main thread's operation.\n\nThere are three main types of workers in JavaScript:\n\n- **Web workers / Dedicated workers**\n  - Run scripts in background threads, separate from the main UI thread.\n  - Useful for CPU-intensive tasks like data processing, calculations, etc.\n  - Cannot directly access or manipulate the DOM.\n- **Service workers**\n  - Act as network proxies, handling requests between the app and network.\n  - Enable offline functionality, caching, and push notifications.\n  - Runs independently of the web page, even when it's closed.\n- **Shared workers**\n  - Can be shared by multiple scripts running in different windows or frames, as long as they're in the same domain.\n  - Scripts communicate with the shared worker by sending and receiving messages.\n  - Useful for coordinating tasks across different parts of a web page.\n\n<!-- Update here: /questions/what-are-workers-in-javascript-used-for/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-workers-in-javascript-used-for/en-US.mdx)\n\n<br>\n\n### Explain the concept of the Web Socket API\n\n<!-- Update here: /questions/explain-the-concept-of-the-web-socket-api/en-US.mdx -->\n\nThe WebSocket API provides a way to open a persistent connection between a client and a server, allowing for real-time, two-way communication. Unlike HTTP, which is request-response based, WebSocket enables full-duplex communication, meaning both the client and server can send and receive messages independently. This is particularly useful for applications like chat apps, live updates, and online gaming.\n\nThe following example uses Postman's WebSocket echo service to demonstrate how web sockets work.\n\n```js live\n// Postman's echo server that will echo back messages you send\nconst socket = new WebSocket('wss://ws.postman-echo.com/raw');\n\n// Event listener for when the connection is open\nsocket.addEventListener('open', function (event) {\n  socket.send('Hello Server!'); // Sends the message to the Postman WebSocket server\n});\n\n// Event listener for when a message is received from the server\nsocket.addEventListener('message', function (event) {\n  console.log('Message from server ', event.data);\n});\n```\n\n<!-- Update here: /questions/explain-the-concept-of-the-web-socket-api/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-the-web-socket-api/en-US.mdx)\n\n<br>\n\n### What are JavaScript polyfills for?\n\n<!-- Update here: /questions/what-are-javascript-polyfills-for/en-US.mdx -->\n\nPolyfills in JavaScript are pieces of code that provide modern functionality to older browsers that lack native support for those features. They bridge the gap between the JavaScript language features and APIs available in modern browsers and the limited capabilities of older browser versions.\n\nThey can be implemented manually or included through libraries and are often used in conjunction with feature detection.\n\nCommon use cases include:\n\n- **New JavaScript Methods**: For example, `Array.prototype.includes()`, `Object.assign()`, etc.\n- **New APIs**: Such as `fetch()`, `Promise`, `IntersectionObserver`, etc. Modern browsers support these now but for a long time they have to be polyfilled.\n\nLibraries and services for polyfills:\n\n- **`core-js`**: A modular standard library for JavaScript which includes polyfills for a wide range of ECMAScript features.\n\n  ```js\n  import 'core-js/actual/array/flat-map'; // With this, Array.prototype.flatMap is available to be used.\n\n  [1, 2].flatMap((it) => [it, it]); // => [1, 1, 2, 2]\n  ```\n\n- **Polyfill.io**: A service that provides polyfills based on the features and user agents specified in the request.\n\n  ```js\n  <script src=\"https://polyfill.io/v3/polyfill.min.js\"></script>\n  ```\n\n<!-- Update here: /questions/what-are-javascript-polyfills-for/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-javascript-polyfills-for/en-US.mdx)\n\n<br>\n\n### How do you detect if JavaScript is disabled on a page?\n\n<!-- Update here: /questions/how-do-you-detect-if-javascript-is-disabled-on-a-page/en-US.mdx -->\n\nTo detect if JavaScript is disabled on a page, you can use the `<noscript>` HTML tag. This tag allows you to display content or messages to users who have JavaScript disabled in their browsers. For example, you can include a message within the `<noscript>` tag to inform users that JavaScript is required for the full functionality of the page.\n\n```html\n<noscript>\n  <p>\n    JavaScript is disabled in your browser. Please enable JavaScript for the\n    best experience.\n  </p>\n</noscript>\n```\n\n<!-- Update here: /questions/how-do-you-detect-if-javascript-is-disabled-on-a-page/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-detect-if-javascript-is-disabled-on-a-page/en-US.mdx)\n\n<br>\n\n### What is the `Intl` namespace object for?\n\n<!-- Update here: /questions/what-is-the-intl-namespace-object-for/en-US.mdx -->\n\nThe `Intl` namespace object in JavaScript is used for internationalization purposes. It provides language-sensitive string comparison, number formatting, and date and time formatting. For example, you can use `Intl.DateTimeFormat` to format dates according to a specific locale:\n\n```js live\nconst date = new Date();\nconst formatter = new Intl.DateTimeFormat('en-US');\nconsole.log(formatter.format(date)); // Outputs date in 'MM/DD/YYYY' format\n```\n\n<!-- Update here: /questions/what-is-the-intl-namespace-object-for/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-intl-namespace-object-for/en-US.mdx)\n\n<br>\n\n### How do you validate form elements using the Constraint Validation API?\n\n<!-- Update here: /questions/how-do-you-validate-form-elements-using-the-constraint-validation-api/en-US.mdx -->\n\nThe Constraint Validation API provides a way to validate form elements in HTML. You can use properties like `validity`, `validationMessage`, and methods like `checkValidity()` and `setCustomValidity()`. For example, to check if an input is valid, you can use:\n\n```js\nconst input = document.querySelector('input');\nif (input.checkValidity()) {\n  console.log('Input is valid');\n} else {\n  console.log(input.validationMessage);\n}\n```\n\n<!-- Update here: /questions/how-do-you-validate-form-elements-using-the-constraint-validation-api/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-validate-form-elements-using-the-constraint-validation-api/en-US.mdx)\n\n<br>\n\n### How do you use `window.history` API?\n\n<!-- Update here: /questions/how-do-you-use-windowhistory-api/en-US.mdx -->\n\nThe `window.history` API allows you to manipulate the browser's session history. You can use `history.pushState()` to add a new entry to the history stack, `history.replaceState()` to modify the current entry, and `history.back()`, `history.forward()`, and `history.go()` to navigate through the history. For example, `history.pushState({page: 1}, \"title 1\", \"?page=1\")` adds a new entry to the history.\n\n<!-- Update here: /questions/how-do-you-use-windowhistory-api/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-use-windowhistory-api/en-US.mdx)\n\n<br>\n\n### How do `<iframe>` on a page communicate?\n\n<!-- Update here: /questions/how-do-iframe-on-a-page-communicate/en-US.mdx -->\n\n`<iframe>` elements on a page can communicate using the `postMessage` API. This allows for secure cross-origin communication between the parent page and the iframe. The `postMessage` method sends a message, and the `message` event listener receives it. Here's a simple example:\n\n```js\n// In the parent page\nconst iframe = document.querySelector('iframe');\niframe.contentWindow.postMessage('Hello from parent', '*');\n\n// In the iframe\nwindow.addEventListener('message', (event) => {\n  console.log(event.data); // 'Hello from parent'\n});\n```\n\n<!-- Update here: /questions/how-do-iframe-on-a-page-communicate/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-iframe-on-a-page-communicate/en-US.mdx)\n\n<br>\n\n### Difference between document `load` event and document `DOMContentLoaded` event?\n\n<!-- Update here: /questions/difference-between-document-load-event-and-document-domcontentloaded-event/en-US.mdx -->\n\nThe `DOMContentLoaded` event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. The `load` event, on the other hand, fires when the entire page, including all dependent resources such as stylesheets and images, has finished loading.\n\n```javascript\ndocument.addEventListener('DOMContentLoaded', function () {\n  console.log('DOM fully loaded and parsed');\n});\n\nwindow.addEventListener('load', function () {\n  console.log('Page fully loaded');\n});\n```\n\n<!-- Update here: /questions/difference-between-document-load-event-and-document-domcontentloaded-event/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/difference-between-document-load-event-and-document-domcontentloaded-event/en-US.mdx)\n\n<br>\n\n### How do you redirect to a new page in JavaScript?\n\n<!-- Update here: /questions/how-do-you-redirect-to-a-new-page-in-javascript/en-US.mdx -->\n\nTo redirect to a new page in JavaScript, you can use the `window.location` object. The most common methods are `window.location.href` and `window.location.replace()`. For example:\n\n```js\n// Using window.location.href\nwindow.location.href = 'https://www.example.com';\n\n// Using window.location.replace()\nwindow.location.replace('https://www.example.com');\n```\n\n<!-- Update here: /questions/how-do-you-redirect-to-a-new-page-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-redirect-to-a-new-page-in-javascript/en-US.mdx)\n\n<br>\n\n### How do you get the query string values of the current page in JavaScript?\n\n<!-- Update here: /questions/how-do-you-get-the-query-string-values-of-the-current-page-in-javascript/en-US.mdx -->\n\nTo get the query string values of the current page in JavaScript, you can use the `URLSearchParams` object. First, create a `URLSearchParams` instance with `window.location.search`, then use the `get` method to retrieve specific query parameters. For example:\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconst value = params.get('language');\nconsole.log(value);\n```\n\n<!-- Update here: /questions/how-do-you-get-the-query-string-values-of-the-current-page-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-get-the-query-string-values-of-the-current-page-in-javascript/en-US.mdx)\n\n<br>\n\n### What are server-sent events?\n\n<!-- Update here: /questions/what-are-server-sent-events/en-US.mdx -->\n\n[Server-sent events (SSE)](https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface) is a standard that allows a web page to receive automatic updates from a server via an HTTP connection. Server-sent events are used with `EventSource` instances that opens a connection with a server and allows client to receive events from the server. Connections created by server-sent events are persistent (similar to the `WebSocket`s), however there are a few differences:\n\n| Property | `WebSocket` | `EventSource` |\n| --- | --- | --- |\n| Direction | Bi-directional – both client and server can exchange messages | Unidirectional – only server sends data |\n| Data type | Binary and text data | Only text |\n| Protocol | WebSocket protocol (`ws://`) | Regular HTTP (`http://`) |\n\n**Creating an event source**\n\n```js\nconst eventSource = new EventSource('/sse-stream');\n```\n\n**Listening for events**\n\n```js\n// Fired when the connection is established.\neventSource.addEventListener('open', () => {\n  console.log('Connection opened');\n});\n\n// Fired when a message is received from the server.\neventSource.addEventListener('message', (event) => {\n  console.log('Received message:', event.data);\n});\n\n// Fired when an error occurs.\neventSource.addEventListener('error', (error) => {\n  console.error('Error occurred:', error);\n});\n```\n\n**Sending events from server**\n\n```js\nconst express = require('express');\nconst app = express();\n\napp.get('/sse-stream', (req, res) => {\n  // `Content-Type` need to be set to `text/event-stream`.\n  res.setHeader('Content-Type', 'text/event-stream');\n  res.setHeader('Cache-Control', 'no-cache');\n  res.setHeader('Connection', 'keep-alive');\n\n  // Each message should be prefixed with data.\n  const sendEvent = (data) => res.write(`data: ${data}\\n\\n`);\n\n  sendEvent('Hello from server');\n\n  const intervalId = setInterval(() => sendEvent(new Date().toString()), 1000);\n\n  res.on('close', () => {\n    console.log('Client closed connection');\n    clearInterval(intervalId);\n  });\n});\n\napp.listen(3000, () => console.log('Server started on port 3000'));\n```\n\nIn this example, the server sends a \"Hello from server\" message initially, and then sends the current date every second. The connection is kept alive until the client closes it\n\n<!-- Update here: /questions/what-are-server-sent-events/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-server-sent-events/en-US.mdx)\n\n<br>\n\n### What are Progressive Web Applications (PWAs)?\n\n<!-- Update here: /questions/what-are-progressive-web-applications-pwas/en-US.mdx -->\n\nProgressive Web Applications (PWAs) are web applications that use modern web capabilities to deliver an app-like experience to users. They are reliable, fast, and engaging. PWAs can work offline, send push notifications, and be installed on a user's home screen. They leverage technologies like service workers, web app manifests, and HTTPS to provide these features.\n\n<!-- Update here: /questions/what-are-progressive-web-applications-pwas/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-progressive-web-applications-pwas/en-US.mdx)\n\n<br>\n\n### What are modules and why are they useful?\n\n<!-- Update here: /questions/what-are-modules-and-why-are-they-useful/en-US.mdx -->\n\nModules are reusable pieces of code that can be imported and exported between different files in a project. They help in organizing code, making it more maintainable and scalable. By using modules, you can avoid global namespace pollution and manage dependencies more effectively. In JavaScript, you can use `import` and `export` statements to work with modules.\n\n```js\n// myModule.js\nexport const myFunction = () => {\n  console.log('Hello, World!');\n};\n\n// main.js\nimport { myFunction } from './myModule.js';\nmyFunction(); // Outputs: Hello, World!\n```\n\n<!-- Update here: /questions/what-are-modules-and-why-are-they-useful/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-modules-and-why-are-they-useful/en-US.mdx)\n\n<br>\n\n### Explain the differences between CommonJS modules and ES modules in JavaScript\n\n<!-- Update here: /questions/explain-the-differences-between-commonjs-modules-and-es-modules/en-US.mdx -->\n\nIn JavaScript, modules are reusable pieces of code that encapsulate functionality, making it easier to manage, maintain, and structure your applications. Modules allow you to break down your code into smaller, manageable parts, each with its own scope.\n\n**CommonJS** is an older module system that was initially designed for server-side JavaScript development with Node.js. It uses the `require()` function to load modules and the `module.exports` or `exports` object to define the exports of a module.\n\n```js\n// my-module.js\nconst value = 42;\nmodule.exports = { value };\n\n// main.js\nconst myModule = require('./my-module.js');\nconsole.log(myModule.value); // 42\n```\n\n**ES Modules** (ECMAScript Modules) are the standardized module system introduced in ES6 (ECMAScript 2015). They use the `import` and `export` statements to handle module dependencies.\n\n```js\n// my-module.js\nexport const value = 42;\n\n// main.js\nimport { value } from './my-module.js';\nconsole.log(value); // 42\n```\n\n**CommonJS vs ES modules**\n\n| Feature | CommonJS | ES modules |\n| --- | --- | --- |\n| Module Syntax | `require()` for importing `module.exports` for exporting | `import` for importing `export` for exporting |\n| Environment | Primarily used in Node.js for server-side development | Designed for both browser and server-side JavaScript (Node.js) |\n| Loading | Synchronous loading of modules | Asynchronous loading of modules |\n| Structure | Dynamic imports, can be conditionally called | Static imports/exports at the top level |\n| File extensions | `.js` (default) | `.mjs` or `.js` (with `type: \"module\"` in `package.json`) |\n| Browser support | Not natively supported in browsers | Natively supported in modern browsers |\n| Optimization | Limited optimization due to dynamic nature | Allows for optimizations like tree-shaking due to static structure |\n| Compatibility | Widely used in existing Node.js codebases and libraries | Newer standard, but gaining adoption in modern projects |\n\n<!-- Update here: /questions/explain-the-differences-between-commonjs-modules-and-es-modules/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-differences-between-commonjs-modules-and-es-modules/en-US.mdx)\n\n<br>\n\n### How do you import and export modules in JavaScript?\n\n<!-- Update here: /questions/how-do-you-import-and-export-modules-in-javascript/en-US.mdx -->\n\nIn JavaScript, you can import and export modules using the `import` and `export` statements. To export a module, you can use `export` before a function, variable, or class, or use `export default` for a single default export. To import a module, you use the `import` statement followed by the name of the exported module and the path to the module file.\n\n```js\n// Exporting a module\nexport const myFunction = () => {\n  /* ... */\n};\nexport default myFunction;\n\n// Importing a module\nimport { myFunction } from './myModule';\nimport myFunction from './myModule';\n```\n\n<!-- Update here: /questions/how-do-you-import-and-export-modules-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-import-and-export-modules-in-javascript/en-US.mdx)\n\n<br>\n\n### What are the benefits of using a module bundler?\n\n<!-- Update here: /questions/what-are-the-benefits-of-using-a-module-bundler/en-US.mdx -->\n\nUsing a module bundler like Webpack, Rollup, or Parcel helps manage dependencies, optimize performance, and improve the development workflow. It combines multiple JavaScript files into a single file or a few files, which reduces the number of HTTP requests and can include features like code splitting, tree shaking, and hot module replacement.\n\n<!-- Update here: /questions/what-are-the-benefits-of-using-a-module-bundler/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-benefits-of-using-a-module-bundler/en-US.mdx)\n\n<br>\n\n### Explain the concept of tree shaking in module bundling\n\n<!-- Update here: /questions/explain-the-concept-of-tree-shaking-in-module-bundling/en-US.mdx -->\n\nTree shaking is a technique used in module bundling to eliminate dead code, which is code that is never used or executed. This helps to reduce the final bundle size and improve application performance. It works by analyzing the dependency graph of the code and removing any unused exports. Tools like Webpack and Rollup support tree shaking when using ES6 module syntax (`import` and `export`).\n\n<!-- Update here: /questions/explain-the-concept-of-tree-shaking-in-module-bundling/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-tree-shaking-in-module-bundling/en-US.mdx)\n\n<br>\n\n### What are the metadata fields of a module?\n\n<!-- Update here: /questions/what-are-the-metadata-fields-of-a-module/en-US.mdx -->\n\nMetadata fields of a module typically include information such as the module's name, version, description, author, license, and dependencies. These fields are often found in a `package.json` file in JavaScript projects. For example:\n\n```json\n{\n  \"name\": \"my-module\",\n  \"version\": \"1.0.0\",\n  \"description\": \"A sample module\",\n  \"author\": \"John Doe\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"express\": \"^4.17.1\"\n  }\n}\n```\n\n<!-- Update here: /questions/what-are-the-metadata-fields-of-a-module/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-metadata-fields-of-a-module/en-US.mdx)\n\n<br>\n\n### What do you think of CommonJS vs ESM?\n\n<!-- Update here: /questions/what-do-you-think-of-amd-vs-commonjs/en-US.mdx -->\n\nJavaScript has evolved its module systems. ESM (ECMAScript Modules) using `import` / `export` is the official standard, natively supported in modern browsers and Node.js, designed for both synchronous and asynchronous use cases. CommonJS (CJS) using `require` / `module.exports` was the original standard for Node.js, primarily synchronous, and remains prevalent in the Node ecosystem. AMD (Asynchronous Module Definition) using `define` / `require` was an early system designed for asynchronous loading in browsers but is now largely obsolete, replaced by ESM.\n\n<!-- Update here: /questions/what-do-you-think-of-amd-vs-commonjs/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-do-you-think-of-amd-vs-commonjs/en-US.mdx)\n\n<br>\n\n### What are the different types of errors in JavaScript?\n\n<!-- Update here: /questions/what-are-the-different-types-of-errors-in-javascript/en-US.mdx -->\n\nIn JavaScript, there are three main types of errors: syntax errors, runtime errors, and logical errors. Syntax errors occur when the code violates the language's grammar rules, such as missing a parenthesis. Runtime errors happen during code execution, like trying to access a property of `undefined`. Logical errors are mistakes in the code's logic that lead to incorrect results but don't throw an error.\n\n<!-- Update here: /questions/what-are-the-different-types-of-errors-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-different-types-of-errors-in-javascript/en-US.mdx)\n\n<br>\n\n### How do you handle errors using `try...catch` blocks?\n\n<!-- Update here: /questions/how-do-you-handle-errors-using-trycatch-blocks/en-US.mdx -->\n\nTo handle errors using `try...catch` blocks, you wrap the code that might throw an error inside a `try` block. If an error occurs, the control is transferred to the `catch` block where you can handle the error. Optionally, you can use a `finally` block to execute code regardless of whether an error occurred or not.\n\n```js\ntry {\n  // Code that may throw an error\n} catch (error) {\n  // Handle the error\n} finally {\n  // Code that will run regardless of an error\n}\n```\n\n<!-- Update here: /questions/how-do-you-handle-errors-using-trycatch-blocks/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-handle-errors-using-trycatch-blocks/en-US.mdx)\n\n<br>\n\n### What is the purpose of the `finally` block?\n\n<!-- Update here: /questions/what-is-the-purpose-of-the-finally-block/en-US.mdx -->\n\nThe `finally` block in JavaScript is used to execute code after a `try` and `catch` block, regardless of whether an error was thrown or caught. It ensures that certain cleanup or finalization code runs no matter what. For example:\n\n```js\ntry {\n  // Code that may throw an error\n} catch (error) {\n  // Code to handle the error\n} finally {\n  // Code that will always run\n}\n```\n\n<!-- Update here: /questions/what-is-the-purpose-of-the-finally-block/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-purpose-of-the-finally-block/en-US.mdx)\n\n<br>\n\n### How can you create custom error objects?\n\n<!-- Update here: /questions/how-can-you-create-custom-error-objects/en-US.mdx -->\n\nTo create custom error objects in JavaScript, you can extend the built-in `Error` class. This allows you to add custom properties and methods to your error objects. Here's a quick example:\n\n```js live\nclass CustomError extends Error {\n  constructor(message) {\n    super(message);\n    this.name = 'CustomError';\n  }\n}\n\ntry {\n  throw new CustomError('This is a custom error message');\n} catch (error) {\n  console.log(error.name); // CustomError\n  console.log(error.message); // This is a custom error message\n}\n```\n\n<!-- Update here: /questions/how-can-you-create-custom-error-objects/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-create-custom-error-objects/en-US.mdx)\n\n<br>\n\n### Explain the concept of error propagation in JavaScript\n\n<!-- Update here: /questions/explain-the-concept-of-error-propagation-in-javascript/en-US.mdx -->\n\nError propagation in JavaScript refers to how errors are passed through the call stack. When an error occurs in a function, it can be caught and handled using `try...catch` blocks. If not caught, the error propagates up the call stack until it is either caught or causes the program to terminate. For example:\n\n```js live\nfunction a() {\n  throw new Error('An error occurred');\n}\n\nfunction b() {\n  a();\n}\n\ntry {\n  b();\n} catch (e) {\n  console.error(e.message); // Outputs: An error occurred\n}\n```\n\n<!-- Update here: /questions/explain-the-concept-of-error-propagation-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-error-propagation-in-javascript/en-US.mdx)\n\n<br>\n\n### What is currying and how does it work?\n\n<!-- Update here: /questions/what-is-currying-and-how-does-it-work/en-US.mdx -->\n\nCurrying is a technique in functional programming where a function that takes multiple arguments is transformed into a series of functions that each take a single argument. This allows for partial application of functions. For example, a function `f(a, b, c)` can be curried into `f(a)(b)(c)`. Here's a simple example in JavaScript:\n\n```js live\nfunction add(a) {\n  return function (b) {\n    return function (c) {\n      return a + b + c;\n    };\n  };\n}\n\nconst addOne = add(1);\nconsole.log(addOne); // function object\n\nconst addOneAndTwo = addOne(2);\nconsole.log(addOneAndTwo); // function object\n\nconst result = addOneAndTwo(3);\nconsole.log(result); // Output: 6\n```\n\n<!-- Update here: /questions/what-is-currying-and-how-does-it-work/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-currying-and-how-does-it-work/en-US.mdx)\n\n<br>\n\n### Explain the concept of partial application\n\n<!-- Update here: /questions/explain-the-concept-of-partial-application/en-US.mdx -->\n\nPartial application is a technique in functional programming where a function is applied to some of its arguments, producing a new function that takes the remaining arguments. This allows you to create more specific functions from general ones. For example, if you have a function `add(a, b)`, you can partially apply it to create a new function `add5` that always adds 5 to its argument.\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconst add5 = add.bind(null, 5);\nconsole.log(add5(10)); // Outputs 15\n```\n\n<!-- Update here: /questions/explain-the-concept-of-partial-application/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-partial-application/en-US.mdx)\n\n<br>\n\n### What are the benefits of using currying and partial application?\n\n<!-- Update here: /questions/what-are-the-benefits-of-using-currying-and-partial-application/en-US.mdx -->\n\nCurrying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. This allows for more flexible and reusable code. Partial application, on the other hand, allows you to fix a few arguments of a function and generate a new function. Both techniques help in creating more modular and maintainable code.\n\n<!-- Update here: /questions/what-are-the-benefits-of-using-currying-and-partial-application/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-benefits-of-using-currying-and-partial-application/en-US.mdx)\n\n<br>\n\n### Provide some examples of how currying and partial application can be used\n\n<!-- Update here: /questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used/en-US.mdx -->\n\nCurrying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. Partial application fixes a few arguments of a function, producing another function with a smaller number of arguments. For example, currying a function `add(a, b)` would look like `add(a)(b)`, while partial application of `add(2, b)` would fix the first argument to 2, resulting in a function that only needs the second argument.\n\nCurrying example:\n\n```js live\nconst add = (a) => (b) => a + b;\nconst addTwo = add(2);\nconsole.log(addTwo(3)); // 5\n```\n\nPartial application example:\n\n```js live\nconst add = (a, b) => a + b;\nconst addTwo = add.bind(null, 2);\nconsole.log(addTwo(3)); // 5\n```\n\n<!-- Update here: /questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used/en-US.mdx)\n\n<br>\n\n### How do currying and partial application differ from each other?\n\n<!-- Update here: /questions/how-do-currying-and-partial-application-differ-from-each-other/en-US.mdx -->\n\nCurrying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. For example, a function `f(a, b, c)` becomes `f(a)(b)(c)`. Partial application, on the other hand, fixes a few arguments of a function and produces another function with a smaller number of arguments. For example, if you partially apply `f(a, b, c)` with `a`, you get a new function `f'(b, c)`.\n\n<!-- Update here: /questions/how-do-currying-and-partial-application-differ-from-each-other/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-currying-and-partial-application-differ-from-each-other/en-US.mdx)\n\n<br>\n\n### What are `Set`s and `Map`s and how are they used?\n\n<!-- Update here: /questions/what-are-sets-and-maps-and-how-are-they-used/en-US.mdx -->\n\n`Set`s and `Map`s are built-in JavaScript objects that help manage collections of data. A `Set` is a collection of unique values, while a `Map` is a collection of key-value pairs where keys can be of any type. `Set`s are useful for storing unique items, and `Map`s are useful for associating values with keys.\n\n```js live\n// Set example\nlet mySet = new Set([1, 2, 3, 3]); // Set {1, 2, 3} (duplicate values are not added)\nmySet.add(4);\nconsole.log(mySet); // Set {1, 2, 3, 4}\n\n// Map example\nlet myMap = new Map();\nmyMap.set('key1', 'value1');\nmyMap.set('key2', 'value2');\nconsole.log(myMap.get('key1')); // 'value1'\n```\n\n<!-- Update here: /questions/what-are-sets-and-maps-and-how-are-they-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-sets-and-maps-and-how-are-they-used/en-US.mdx)\n\n<br>\n\n### What are the differences between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript?\n\n<!-- Update here: /questions/what-are-the-differences-between-map-set-and-weakmap-weakset/en-US.mdx -->\n\nThe primary difference between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript lies in how they handle keys. Here's a breakdown:\n\n**`Map` vs. `WeakMap`**\n\n`Map`s allows any data type (strings, numbers, objects) as keys. The key-value pairs remain in memory as long as the `Map` object itself is referenced. Thus they are suitable for general-purpose key-value storage where you want to maintain references to both keys and values. Common use cases include storing user data, configuration settings, or relationships between objects.\n\n`WeakMap`s only allows objects as keys. However, these object keys are held weakly. This means the garbage collector can remove them from memory even if the `WeakMap` itself still exists, as long as there are no other references to those objects. `WeakMap`s are ideal for scenarios where you want to associate data with objects without preventing those objects from being garbage collected. This can be useful for things like:\n\n- Caching data based on objects without preventing garbage collection of the objects themselves.\n- Storing private data associated with DOM nodes without affecting their lifecycle.\n\n**`Set` vs. `WeakSet`**\n\nSimilar to `Map`, `Set`s allow any data type as keys. The elements within a `Set` must be unique. `Set`s are useful for storing unique values and checking for membership efficiently. Common use cases include removing duplicates from arrays or keeping track of completed tasks.\n\nOn the other hand, `WeakSet` only allows objects as elements, and these object elements are held weakly, similar to `WeakMap` keys. `WeakSet`s are less commonly used, but applicable when you want a collection of unique objects without affecting their garbage collection. This might be necessary for:\n\n- Tracking DOM nodes that have been interacted with without affecting their memory management.\n- Implementing custom object weak references for specific use cases.\n\n**Here's a table summarizing the key differences:**\n\n| Feature | Map | WeakMap | Set | WeakSet |\n| --- | --- | --- | --- | --- |\n| Key Types | Any data type | Objects (weak references) | Any data type (unique) | Objects (weak references, unique) |\n| Garbage Collection | Keys and values are not garbage collected | Keys can be garbage collected if not referenced elsewhere | Elements are not garbage collected | Elements can be garbage collected if not referenced elsewhere |\n| Use Cases | General-purpose key-value storage | Caching, private DOM node data | Removing duplicates, membership checks | Object weak references, custom use cases |\n\n**Choosing between them**\n\n- Use `Map` and `Set` for most scenarios where you need to store key-value pairs or unique elements and want to maintain references to both the keys/elements and the values.\n- Use `WeakMap` and `WeakSet` cautiously in specific situations where you want to associate data with objects without affecting their garbage collection. Be aware of the implications of weak references and potential memory leaks if not used correctly.\n\n<!-- Update here: /questions/what-are-the-differences-between-map-set-and-weakmap-weakset/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-differences-between-map-set-and-weakmap-weakset/en-US.mdx)\n\n<br>\n\n### How do you convert a `Set` to an array in JavaScript?\n\n<!-- Update here: /questions/how-do-you-convert-a-set-to-an-array-in-javascript/en-US.mdx -->\n\nTo convert a `Set` to an array in JavaScript, you can use the `Array.from()` method or the spread operator. For example:\n\n```js live\nconst mySet = new Set([1, 2, 3]);\nconst myArray = Array.from(mySet);\n// OR const myArray = [...mySet];\n\nconsole.log(myArray); // Output: [1, 2, 3]\n```\n\n<!-- Update here: /questions/how-do-you-convert-a-set-to-an-array-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-convert-a-set-to-an-array-in-javascript/en-US.mdx)\n\n<br>\n\n### What is the difference between a `Map` object and a plain object in JavaScript?\n\n<!-- Update here: /questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/en-US.mdx -->\n\nBoth `Map` objects and plain objects in JavaScript can store key-value pairs, but they have several key differences:\n\n| Feature | `Map` | Plain object |\n| --- | --- | --- |\n| Key type | Any data type | String (or Symbol) |\n| Key order | Maintained | Not guaranteed |\n| Size property | Yes (`size`) | None |\n| Iteration | `forEach`, `keys()`, `values()`, `entries()` | `for...in`, `Object.keys()`, etc. |\n| Inheritance | No | Yes |\n| Performance | Generally better for larger datasets and frequent additions/deletions | Faster for small datasets and simple operations |\n| Serializable | No | Yes |\n\n<!-- Update here: /questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/en-US.mdx)\n\n<br>\n\n### How do `Set`s and `Map`s handle equality checks for objects?\n\n<!-- Update here: /questions/how-do-sets-and-maps-handle-equality-checks-for-objects/en-US.mdx -->\n\n`Set`s and `Map`s in JavaScript handle equality checks for objects based on reference equality, not deep equality. This means that two objects are considered equal only if they reference the same memory location. For example, if you add two different object literals with the same properties to a `Set`, they will be treated as distinct entries.\n\n```js live\nconst set = new Set();\nconst obj1 = { a: 1 };\nconst obj2 = { a: 1 };\n\nset.add(obj1);\nset.add(obj2);\n\nconsole.log(set.size); // Output: 2\n```\n\n<!-- Update here: /questions/how-do-sets-and-maps-handle-equality-checks-for-objects/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-sets-and-maps-handle-equality-checks-for-objects/en-US.mdx)\n\n<br>\n\n### What are some common performance bottlenecks in JavaScript applications?\n\n<!-- Update here: /questions/what-are-some-common-performance-bottlenecks-in-javascript-applications/en-US.mdx -->\n\nCommon performance bottlenecks in JavaScript applications include inefficient DOM manipulation, excessive use of global variables, blocking the main thread with heavy computations, memory leaks, and improper use of asynchronous operations. To mitigate these issues, you can use techniques like debouncing and throttling, optimizing DOM updates, and leveraging web workers for heavy computations.\n\n<!-- Update here: /questions/what-are-some-common-performance-bottlenecks-in-javascript-applications/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-common-performance-bottlenecks-in-javascript-applications/en-US.mdx)\n\n<br>\n\n### Explain the concept of debouncing and throttling\n\n<!-- Update here: /questions/explain-the-concept-of-debouncing-and-throttling/en-US.mdx -->\n\nDebouncing and throttling are techniques used to control the rate at which a function is executed. Debouncing ensures that a function is only called after a specified delay has passed since the last time it was invoked. Throttling ensures that a function is called at most once in a specified time interval.\n\nDebouncing delays the execution of a function until a certain amount of time has passed since it was last called. This is useful for scenarios like search input fields where you want to wait until the user has stopped typing before making an API call.\n\n```js live\nfunction debounce(func, delay) {\n  let timeoutId;\n  return function (...args) {\n    clearTimeout(timeoutId);\n    timeoutId = setTimeout(() => func.apply(this, args), delay);\n  };\n}\n\nconst debouncedHello = debounce(() => console.log('Hello world!'), 2000);\ndebouncedHello(); // Prints 'Hello world!' after 2 seconds\n```\n\nThrottling ensures that a function is called at most once in a specified time interval. This is useful for scenarios like window resizing or scrolling where you want to limit the number of times a function is called.\n\n```js live\nfunction throttle(func, limit) {\n  let inThrottle;\n  return function (...args) {\n    if (!inThrottle) {\n      func.apply(this, args);\n      inThrottle = true;\n      setTimeout(() => (inThrottle = false), limit);\n    }\n  };\n}\n\nconst handleResize = throttle(() => {\n  // Update element positions\n  console.log('Window resized at', new Date().toLocaleTimeString());\n}, 2000);\n\n// Simulate rapid calls to handleResize every 100ms\nlet intervalId = setInterval(() => {\n  handleResize();\n}, 100);\n// 'Window resized' is outputted only every 2 seconds due to throttling\n```\n\n<!-- Update here: /questions/explain-the-concept-of-debouncing-and-throttling/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-debouncing-and-throttling/en-US.mdx)\n\n<br>\n\n### How can you optimize DOM manipulation for better performance?\n\n<!-- Update here: /questions/how-can-you-optimize-dom-manipulation-for-better-performance/en-US.mdx -->\n\nTo optimize DOM manipulation for better performance, minimize direct DOM access and updates. Use techniques like batching DOM changes, using `documentFragment` for multiple elements, and leveraging virtual DOM libraries like React. Also, consider using `requestAnimationFrame` for animations and avoid layout thrashing by reading and writing DOM properties separately.\n\n<!-- Update here: /questions/how-can-you-optimize-dom-manipulation-for-better-performance/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-optimize-dom-manipulation-for-better-performance/en-US.mdx)\n\n<br>\n\n### What are some techniques for reducing reflows and repaints?\n\n<!-- Update here: /questions/what-are-some-techniques-for-reducing-reflows-and-repaints/en-US.mdx -->\n\nTo reduce reflows and repaints, you can minimize DOM manipulations, batch DOM changes, use CSS classes for style changes, avoid complex CSS selectors, and use `requestAnimationFrame` for animations. Additionally, consider using `will-change` for elements that will change frequently and avoid layout thrashing by reading and writing to the DOM separately.\n\n<!-- Update here: /questions/what-are-some-techniques-for-reducing-reflows-and-repaints/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-techniques-for-reducing-reflows-and-repaints/en-US.mdx)\n\n<br>\n\n### Explain the concept of lazy loading and how it can improve performance\n\n<!-- Update here: /questions/explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance/en-US.mdx -->\n\nLazy loading is a design pattern that delays the loading of resources until they are actually needed. This can significantly improve performance by reducing initial load times and conserving bandwidth. For example, images on a webpage can be lazy-loaded so that they only load when they come into the viewport. This can be achieved using the `loading=\"lazy\"` attribute in HTML or by using JavaScript libraries.\n\n```html\n<img src=\"image.jpg\" loading=\"lazy\" alt=\"Lazy loaded image\" />\n```\n\n<!-- Update here: /questions/explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance/en-US.mdx)\n\n<br>\n\n### What are Web Workers and how can they be used to improve performance?\n\n<!-- Update here: /questions/what-are-web-workers-and-how-can-they-be-used-to-improve-performance/en-US.mdx -->\n\nWeb Workers are a way to run JavaScript in the background, separate from the main execution thread of a web application. This helps in performing heavy computations without blocking the user interface. You can create a Web Worker using the `Worker` constructor and communicate with it using the `postMessage` and `onmessage` methods.\n\n```js\n// main.js\nconst worker = new Worker('worker.js');\nworker.postMessage('Hello, worker!');\n\nworker.onmessage = function (event) {\n  console.log('Message from worker:', event.data);\n};\n\n// worker.js\nonmessage = function (event) {\n  console.log('Message from main script:', event.data);\n  postMessage('Hello, main script!');\n};\n```\n\n<!-- Update here: /questions/what-are-web-workers-and-how-can-they-be-used-to-improve-performance/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-web-workers-and-how-can-they-be-used-to-improve-performance/en-US.mdx)\n\n<br>\n\n### Explain the concept of caching and how it can be used to improve performance\n\n<!-- Update here: /questions/explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance/en-US.mdx -->\n\nCaching is a technique used to store copies of files or data in a temporary storage location to reduce the time it takes to access them. It improves performance by reducing the need to fetch data from the original source repeatedly. In front end development, caching can be implemented using browser cache, service workers, and HTTP headers like `Cache-Control`.\n\n<!-- Update here: /questions/explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance/en-US.mdx)\n\n<br>\n\n### What are some tools that can be used to measure and analyze JavaScript performance?\n\n<!-- Update here: /questions/what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance/en-US.mdx -->\n\nTo measure and analyze JavaScript performance, you can use tools like Chrome DevTools, Lighthouse, WebPageTest, and JSPerf. Chrome DevTools provides a Performance panel for profiling, Lighthouse offers audits for performance metrics, WebPageTest allows for detailed performance testing, and JSPerf helps in comparing the performance of different JavaScript snippets.\n\n<!-- Update here: /questions/what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance/en-US.mdx)\n\n<br>\n\n### How can you optimize network requests for better performance?\n\n<!-- Update here: /questions/how-can-you-optimize-network-requests-for-better-performance/en-US.mdx -->\n\nTo optimize network requests for better performance, you can minimize the number of requests, use caching, compress data, and leverage modern web technologies like HTTP/2 and service workers. For example, you can combine multiple CSS files into one to reduce the number of requests, use `Cache-Control` headers to cache static assets, and enable Gzip compression on your server to reduce the size of the data being transferred.\n\n<!-- Update here: /questions/how-can-you-optimize-network-requests-for-better-performance/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-optimize-network-requests-for-better-performance/en-US.mdx)\n\n<br>\n\n### What are the different types of testing in software development?\n\n<!-- Update here: /questions/what-are-the-different-types-of-testing-in-software-development/en-US.mdx -->\n\nIn software development, there are several types of testing to ensure the quality and functionality of the application. These include unit testing, integration testing, system testing, and acceptance testing. Unit testing focuses on individual components, integration testing checks the interaction between components, system testing evaluates the entire system, and acceptance testing ensures the software meets user requirements.\n\n<!-- Update here: /questions/what-are-the-different-types-of-testing-in-software-development/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-the-different-types-of-testing-in-software-development/en-US.mdx)\n\n<br>\n\n### Explain the difference between unit testing, integration testing, and end-to-end testing\n\n<!-- Update here: /questions/explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing/en-US.mdx -->\n\nUnit testing focuses on testing individual components or functions in isolation to ensure they work as expected. Integration testing checks how different modules or services work together. End-to-end testing simulates real user scenarios to verify the entire application flow from start to finish.\n\n<!-- Update here: /questions/explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing/en-US.mdx)\n\n<br>\n\n### What are some popular JavaScript testing frameworks?\n\n<!-- Update here: /questions/what-are-some-popular-javascript-testing-frameworks/en-US.mdx -->\n\nSome popular JavaScript testing frameworks include Jest, Mocha, Jasmine, and Cypress. Jest is known for its simplicity and integration with React. Mocha is highly flexible and often used with other libraries like Chai for assertions. Jasmine is a behavior-driven development framework that requires no additional libraries. Cypress is an end-to-end testing framework that provides a great developer experience.\n\n<!-- Update here: /questions/what-are-some-popular-javascript-testing-frameworks/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-popular-javascript-testing-frameworks/en-US.mdx)\n\n<br>\n\n### How do you write unit tests for JavaScript code?\n\n<!-- Update here: /questions/how-do-you-write-unit-tests-for-javascript-code/en-US.mdx -->\n\nTo write unit tests for JavaScript code, you typically use a testing framework like Jest or Mocha. First, you set up your testing environment by installing the necessary libraries. Then, you write test cases using functions like `describe`, `it`, or `test` to define your tests. Each test case should focus on a small, isolated piece of functionality. You use assertions to check if the output of your code matches the expected result.\n\nExample using Jest:\n\n```js\n// sum.js\nfunction sum(a, b) {\n  return a + b;\n}\nmodule.exports = sum;\n\n// sum.test.js\nconst sum = require('./sum');\n\ntest('adds 1 + 2 to equal 3', () => {\n  expect(sum(1, 2)).toBe(3);\n});\n```\n\n<!-- Update here: /questions/how-do-you-write-unit-tests-for-javascript-code/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-write-unit-tests-for-javascript-code/en-US.mdx)\n\n<br>\n\n### Explain the concept of test-driven development (TDD)\n\n<!-- Update here: /questions/explain-the-concept-of-test-driven-development-tdd/en-US.mdx -->\n\nTest-driven development (TDD) is a software development approach where you write tests before writing the actual code. The process involves writing a failing test, writing the minimum code to pass the test, and then refactoring the code while keeping the tests passing. This ensures that the code is always tested and helps in maintaining high code quality.\n\n<!-- Update here: /questions/explain-the-concept-of-test-driven-development-tdd/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-test-driven-development-tdd/en-US.mdx)\n\n<br>\n\n### What are mocks and stubs and how are they used in testing?\n\n<!-- Update here: /questions/what-are-mocks-and-stubs-and-how-are-they-used-in-testing/en-US.mdx -->\n\nMocks and stubs are tools used in testing to simulate the behavior of real objects. Stubs provide predefined responses to function calls, while mocks are more complex and can verify interactions, such as whether a function was called and with what arguments. Stubs are used to isolate the code being tested from external dependencies, and mocks are used to ensure that the code interacts correctly with those dependencies.\n\n<!-- Update here: /questions/what-are-mocks-and-stubs-and-how-are-they-used-in-testing/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-mocks-and-stubs-and-how-are-they-used-in-testing/en-US.mdx)\n\n<br>\n\n### How can you test asynchronous code in JavaScript?\n\n<!-- Update here: /questions/how-can-you-test-asynchronous-code-in-javascript/en-US.mdx -->\n\nTo test asynchronous code in JavaScript, you can use testing frameworks like Jest or Mocha. These frameworks provide built-in support for handling asynchronous operations. You can use `async`/`await` or return promises in your test functions. For example, in Jest, you can write:\n\n```js\ntest('fetches data successfully', async () => {\n  const data = await fetchData();\n  expect(data).toBeDefined();\n});\n```\n\nAlternatively, you can use callbacks and the `done` function to signal the end of an asynchronous test.\n\n<!-- Update here: /questions/how-can-you-test-asynchronous-code-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-test-asynchronous-code-in-javascript/en-US.mdx)\n\n<br>\n\n### What are some best practices for writing maintainable and effective tests in JavaScript?\n\n<!-- Update here: /questions/what-are-some-best-practices-for-writing-maintainable-and-effective-tests/en-US.mdx -->\n\nTo write maintainable and effective tests, ensure they are clear, concise, and focused on a single behavior. Use descriptive names for test cases and avoid hardcoding values. Mock external dependencies and keep tests isolated. Regularly review and refactor tests to keep them up-to-date with the codebase.\n\n<!-- Update here: /questions/what-are-some-best-practices-for-writing-maintainable-and-effective-tests/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-best-practices-for-writing-maintainable-and-effective-tests/en-US.mdx)\n\n<br>\n\n### Explain the concept of code coverage and how it can be used to assess test quality\n\n<!-- Update here: /questions/explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality/en-US.mdx -->\n\nCode coverage is a metric that measures the percentage of code that is executed when the test suite runs. It helps in assessing the quality of tests by identifying untested parts of the codebase. Higher code coverage generally indicates more thorough testing, but it doesn't guarantee the absence of bugs. Tools like Istanbul or Jest can be used to measure code coverage.\n\n<!-- Update here: /questions/explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality/en-US.mdx)\n\n<br>\n\n### What are some tools that can be used for JavaScript testing?\n\n<!-- Update here: /questions/what-are-some-tools-that-can-be-used-for-javascript-testing/en-US.mdx -->\n\nFor JavaScript testing, you can use tools like Jest, Mocha, Jasmine, and Cypress. Jest is popular for its ease of use and built-in features. Mocha is flexible and can be paired with other libraries. Jasmine is known for its simplicity and behavior-driven development (BDD) style. Cypress is great for end-to-end testing with a focus on real browser interactions.\n\n<!-- Update here: /questions/what-are-some-tools-that-can-be-used-for-javascript-testing/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-tools-that-can-be-used-for-javascript-testing/en-US.mdx)\n\n<br>\n\n### What are design patterns and why are they useful?\n\n<!-- Update here: /questions/what-are-design-patterns-and-why-are-they-useful/en-US.mdx -->\n\nDesign patterns are reusable solutions to common problems in software design. They provide a template for how to solve a problem that can be used in many different situations. They are useful because they help developers avoid common pitfalls, improve code readability, and make it easier to maintain and scale applications.\n\n<!-- Update here: /questions/what-are-design-patterns-and-why-are-they-useful/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-design-patterns-and-why-are-they-useful/en-US.mdx)\n\n<br>\n\n### Explain the concept of the Singleton pattern\n\n<!-- Update here: /questions/explain-the-concept-of-the-singleton-pattern/en-US.mdx -->\n\nThe Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. This is useful when exactly one object is needed to coordinate actions across the system. In JavaScript, this can be implemented using closures or ES6 classes.\n\n```js live\nclass Singleton {\n  constructor() {\n    if (!Singleton.instance) {\n      Singleton.instance = this;\n    }\n    return Singleton.instance;\n  }\n}\n\nconst instance1 = new Singleton();\nconst instance2 = new Singleton();\n\nconsole.log(instance1 === instance2); // true\n```\n\n<!-- Update here: /questions/explain-the-concept-of-the-singleton-pattern/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-the-singleton-pattern/en-US.mdx)\n\n<br>\n\n### What is the Factory pattern and how is it used?\n\n<!-- Update here: /questions/what-is-the-factory-pattern-and-how-is-it-used/en-US.mdx -->\n\nThe Factory pattern is a design pattern used to create objects without specifying the exact class of the object that will be created. It provides a way to encapsulate the instantiation logic and can be particularly useful when the creation process is complex or when the type of object to be created is determined at runtime.\n\nFor example, in JavaScript, you can use a factory function to create different types of objects:\n\n```js live\nfunction createAnimal(type) {\n  if (type === 'dog') {\n    return { sound: 'woof' };\n  } else if (type === 'cat') {\n    return { sound: 'meow' };\n  }\n}\n\nconst dog = createAnimal('dog');\nconst cat = createAnimal('cat');\n```\n\n<!-- Update here: /questions/what-is-the-factory-pattern-and-how-is-it-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-factory-pattern-and-how-is-it-used/en-US.mdx)\n\n<br>\n\n### Explain the Observer pattern and its use cases\n\n<!-- Update here: /questions/explain-the-observer-pattern-and-its-use-cases/en-US.mdx -->\n\nThe Observer pattern is a design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them of any state changes. This pattern is useful for implementing distributed event-handling systems, such as updating the user interface in response to data changes or implementing event-driven architectures.\n\n<!-- Update here: /questions/explain-the-observer-pattern-and-its-use-cases/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-observer-pattern-and-its-use-cases/en-US.mdx)\n\n<br>\n\n### What is the Module pattern and how does it help with encapsulation?\n\n<!-- Update here: /questions/what-is-the-module-pattern-and-how-does-it-help-with-encapsulation/en-US.mdx -->\n\nThe Module pattern in JavaScript is a design pattern used to create self-contained modules of code. It helps with encapsulation by allowing you to define private and public members within a module. Private members are not accessible from outside the module, while public members are exposed through a returned object. This pattern helps in organizing code, avoiding global namespace pollution, and maintaining a clean separation of concerns.\n\n```js live\nvar myModule = (function () {\n  var privateVar = 'I am private';\n\n  function privateMethod() {\n    console.log(privateVar);\n  }\n\n  return {\n    publicMethod: function () {\n      privateMethod();\n    },\n  };\n})();\n\nmyModule.publicMethod(); // Logs: I am private\n```\n\n<!-- Update here: /questions/what-is-the-module-pattern-and-how-does-it-help-with-encapsulation/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-module-pattern-and-how-does-it-help-with-encapsulation/en-US.mdx)\n\n<br>\n\n### Explain the concept of the Prototype pattern\n\n<!-- Update here: /questions/explain-the-concept-of-the-prototype-pattern/en-US.mdx -->\n\nThe Prototype pattern is a creational design pattern used to create new objects by copying an existing object, known as the prototype. This pattern is useful when the cost of creating a new object is more expensive than cloning an existing one. In JavaScript, this can be achieved using the `Object.create` method or by using the `prototype` property of a constructor function.\n\n```js live\nconst prototypeObject = {\n  greet() {\n    console.log('Hello, world!');\n  },\n};\n\nconst newObject = Object.create(prototypeObject);\nnewObject.greet(); // Outputs: Hello, world!\n```\n\n<!-- Update here: /questions/explain-the-concept-of-the-prototype-pattern/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-the-prototype-pattern/en-US.mdx)\n\n<br>\n\n### What is the Decorator pattern and how is it used?\n\n<!-- Update here: /questions/what-is-the-decorator-pattern-and-how-is-it-used/en-US.mdx -->\n\nThe Decorator pattern is a structural design pattern that allows behavior to be added to individual objects, dynamically, without affecting the behavior of other objects from the same class. It is used to extend the functionalities of objects by wrapping them with additional behavior. In JavaScript, this can be achieved using higher-order functions or classes.\n\nFor example, if you have a `Car` class and you want to add features like `GPS` or `Sunroof` without modifying the `Car` class itself, you can create decorators for these features.\n\n```js live\nclass Car {\n  drive() {\n    return 'Driving';\n  }\n}\n\nclass CarDecorator {\n  constructor(car) {\n    this.car = car;\n  }\n\n  drive() {\n    return this.car.drive();\n  }\n}\n\nclass GPSDecorator extends CarDecorator {\n  drive() {\n    return `${super.drive()} with GPS`;\n  }\n}\n\nconst myCar = new Car();\nconst myCarWithGPS = new GPSDecorator(myCar);\nconsole.log(myCarWithGPS.drive()); // \"Driving with GPS\"\n```\n\n<!-- Update here: /questions/what-is-the-decorator-pattern-and-how-is-it-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-decorator-pattern-and-how-is-it-used/en-US.mdx)\n\n<br>\n\n### Explain the concept of the Strategy pattern\n\n<!-- Update here: /questions/explain-the-concept-of-the-strategy-pattern/en-US.mdx -->\n\nThe Strategy pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one as a separate class, and make them interchangeable. This pattern lets the algorithm vary independently from the clients that use it. For example, if you have different sorting algorithms, you can define each one as a strategy and switch between them without changing the client code.\n\n```js live\nclass Context {\n  constructor(strategy) {\n    this.strategy = strategy;\n  }\n\n  executeStrategy(data) {\n    return this.strategy.doAlgorithm(data);\n  }\n}\n\nclass ConcreteStrategyA {\n  doAlgorithm(data) {\n    // Implementation of algorithm A\n    return 'Algorithm A was run on ' + data;\n  }\n}\n\nclass ConcreteStrategyB {\n  doAlgorithm(data) {\n    // Implementation of algorithm B\n    return 'Algorithm B was run on ' + data;\n  }\n}\n\n// Usage\nconst context = new Context(new ConcreteStrategyA());\ncontext.executeStrategy('someData'); // Output: Algorithm A was run on someData\n```\n\n<!-- Update here: /questions/explain-the-concept-of-the-strategy-pattern/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-the-strategy-pattern/en-US.mdx)\n\n<br>\n\n### What is the Command pattern and how is it used?\n\n<!-- Update here: /questions/what-is-the-command-pattern-and-how-is-it-used/en-US.mdx -->\n\nThe Command pattern is a behavioral design pattern that turns a request into a stand-alone object containing all information about the request. This transformation allows for parameterization of methods with different requests, queuing of requests, and logging of the requests. It also supports undoable operations. In JavaScript, it can be implemented by creating command objects with `execute` and `undo` methods.\n\n```js live\nclass Command {\n  execute() {}\n  undo() {}\n}\n\nclass LightOnCommand extends Command {\n  constructor(light) {\n    super();\n    this.light = light;\n  }\n  execute() {\n    this.light.on();\n  }\n  undo() {\n    this.light.off();\n  }\n}\n\nclass Light {\n  on() {\n    console.log('Light is on');\n  }\n  off() {\n    console.log('Light is off');\n  }\n}\n\nconst light = new Light();\nconst lightOnCommand = new LightOnCommand(light);\nlightOnCommand.execute(); // Light is on\nlightOnCommand.undo(); // Light is off\n```\n\n<!-- Update here: /questions/what-is-the-command-pattern-and-how-is-it-used/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-the-command-pattern-and-how-is-it-used/en-US.mdx)\n\n<br>\n\n### Why is extending built-in JavaScript objects not a good idea?\n\n<!-- Update here: /questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/en-US.mdx -->\n\nExtending a built-in/native JavaScript object means adding properties/functions to its `prototype`. While this may seem like a good idea at first, it is dangerous in practice. Imagine your code uses a few libraries that both extend the `Array.prototype` by adding the same `contains` method, the implementations will overwrite each other and your code will have unpredictable behavior if these two methods do not work the same way.\n\nThe only time you may want to extend a native object is when you want to create a polyfill, essentially providing your own implementation for a method that is part of the JavaScript specification but might not exist in the user's browser due to it being an older browser.\n\n<!-- Update here: /questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/en-US.mdx)\n\n<br>\n\n### What is Cross-Site Scripting (XSS) and how can you prevent it?\n\n<!-- Update here: /questions/what-is-cross-site-scripting-xss-and-how-can-you-prevent-it/en-US.mdx -->\n\nCross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users. This can lead to data theft, session hijacking, and other malicious activities. To prevent XSS, you should validate and sanitize user inputs, use Content Security Policy (CSP), and escape data before rendering it in the browser.\n\n<!-- Update here: /questions/what-is-cross-site-scripting-xss-and-how-can-you-prevent-it/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-cross-site-scripting-xss-and-how-can-you-prevent-it/en-US.mdx)\n\n<br>\n\n### Explain the concept of Cross-Site Request Forgery (CSRF) and its mitigation techniques\n\n<!-- Update here: /questions/explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques/en-US.mdx -->\n\nCross-Site Request Forgery (CSRF) is an attack where a malicious website tricks a user's browser into making an unwanted request to another site where the user is authenticated. This can lead to unauthorized actions being performed on behalf of the user. Mitigation techniques include using anti-CSRF tokens, SameSite cookies, and ensuring proper CORS configurations.\n\n<!-- Update here: /questions/explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques/en-US.mdx)\n\n<br>\n\n### How can you prevent SQL injection vulnerabilities in JavaScript applications?\n\n<!-- Update here: /questions/how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications/en-US.mdx -->\n\nTo prevent SQL injection vulnerabilities in JavaScript applications, always use parameterized queries or prepared statements instead of string concatenation to construct SQL queries. This ensures that user input is treated as data and not executable code. Additionally, use ORM libraries that handle SQL injection prevention for you, and always validate and sanitize user inputs.\n\n<!-- Update here: /questions/how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications/en-US.mdx)\n\n<br>\n\n### What are some best practices for handling sensitive data in JavaScript?\n\n<!-- Update here: /questions/what-are-some-best-practices-for-handling-sensitive-data-in-javascript/en-US.mdx -->\n\nHandling sensitive data in JavaScript requires careful attention to security practices. Avoid storing sensitive data in client-side storage like localStorage or sessionStorage. Use HTTPS to encrypt data in transit. Implement proper authentication and authorization mechanisms. Sanitize and validate all inputs to prevent injection attacks. Consider using environment variables for sensitive data in server-side code.\n\n<!-- Update here: /questions/what-are-some-best-practices-for-handling-sensitive-data-in-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-best-practices-for-handling-sensitive-data-in-javascript/en-US.mdx)\n\n<br>\n\n### Explain the concept of Content Security Policy (CSP) and how it enhances security\n\n<!-- Update here: /questions/explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security/en-US.mdx -->\n\nContent Security Policy (CSP) is a security feature that helps prevent various types of attacks, such as Cross-Site Scripting (XSS) and data injection attacks, by specifying which content sources are trusted. It works by allowing developers to define a whitelist of trusted sources for content like scripts, styles, and images. This is done through HTTP headers or meta tags. For example, you can use the `Content-Security-Policy` header to specify that only scripts from your own domain should be executed:\n\n```http\nContent-Security-Policy: script-src 'self'\n```\n\n<!-- Update here: /questions/explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security/en-US.mdx)\n\n<br>\n\n### What are some common security headers and their purpose?\n\n<!-- Update here: /questions/what-are-some-common-security-headers-and-their-purpose/en-US.mdx -->\n\nSecurity headers are HTTP response headers that help protect web applications from various attacks. Some common security headers include:\n\n- `Content-Security-Policy (CSP)`: Prevents cross-site scripting (XSS) and other code injection attacks by specifying allowed content sources.\n- `X-Content-Type-Options`: Prevents MIME type sniffing by instructing the browser to follow the declared `Content-Type`.\n- `Strict-Transport-Security (HSTS)`: Enforces secure (HTTPS) connections to the server.\n- `X-Frame-Options`: Prevents clickjacking by controlling whether a page can be displayed in a frame.\n- `X-XSS-Protection`: Enables the cross-site scripting (XSS) filter built into most browsers.\n- `Referrer-Policy`: Controls how much referrer information is included with requests.\n\n<!-- Update here: /questions/what-are-some-common-security-headers-and-their-purpose/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-common-security-headers-and-their-purpose/en-US.mdx)\n\n<br>\n\n### How can you prevent clickjacking attacks?\n\n<!-- Update here: /questions/how-can-you-prevent-clickjacking-attacks/en-US.mdx -->\n\nTo prevent clickjacking attacks, you can use the `X-Frame-Options` HTTP header to control whether your site can be embedded in iframes. Set it to `DENY` to prevent all framing, or `SAMEORIGIN` to allow framing only from the same origin. Additionally, you can use the `Content-Security-Policy` (CSP) header with the `frame-ancestors` directive to specify which origins are allowed to frame your content.\n\n```http\nX-Frame-Options: DENY\n```\n\n```http\nContent-Security-Policy: frame-ancestors 'self'\n```\n\n<!-- Update here: /questions/how-can-you-prevent-clickjacking-attacks/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-prevent-clickjacking-attacks/en-US.mdx)\n\n<br>\n\n### Explain the concept of input validation and its importance in security\n\n<!-- Update here: /questions/explain-the-concept-of-input-validation-and-its-importance-in-security/en-US.mdx -->\n\nInput validation is the process of ensuring that user input is correct, safe, and meets the application's requirements. It is crucial for security because it helps prevent attacks like SQL injection, cross-site scripting (XSS), and other forms of data manipulation. By validating input, you ensure that only properly formatted data enters your system, reducing the risk of malicious data causing harm.\n\n<!-- Update here: /questions/explain-the-concept-of-input-validation-and-its-importance-in-security/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-concept-of-input-validation-and-its-importance-in-security/en-US.mdx)\n\n<br>\n\n### What are some tools and techniques for identifying security vulnerabilities in JavaScript code?\n\n<!-- Update here: /questions/what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code/en-US.mdx -->\n\nTo identify security vulnerabilities in JavaScript code, you can use static code analysis tools like ESLint with security plugins, dynamic analysis tools like OWASP ZAP, and dependency checkers like npm audit. Additionally, manual code reviews and adhering to secure coding practices are essential techniques.\n\n<!-- Update here: /questions/what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code/en-US.mdx)\n\n<br>\n\n### How can you implement secure authentication and authorization in JavaScript applications?\n\n<!-- Update here: /questions/how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications/en-US.mdx -->\n\nTo implement secure authentication and authorization in JavaScript applications, use HTTPS to encrypt data in transit, and store sensitive data like tokens securely using `localStorage` or `sessionStorage`. Implement token-based authentication using JWTs, and validate tokens on the server side. Use libraries like OAuth for third-party authentication and ensure proper role-based access control (RBAC) for authorization.\n\n<!-- Update here: /questions/how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications/en-US.mdx)\n\n<br>\n\n### Explain the same-origin policy with regards to JavaScript\n\n<!-- Update here: /questions/explain-the-same-origin-policy-with-regards-to-javascript/en-US.mdx -->\n\nThe same-origin policy is a security measure implemented in web browsers to prevent malicious scripts on one page from accessing data on another page. It ensures that web pages can only make requests to the same origin, where the origin is defined by the combination of the protocol, domain, and port. For example, a script from `http://example.com` cannot access data from `http://anotherdomain.com`.\n\n<!-- Update here: /questions/explain-the-same-origin-policy-with-regards-to-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-the-same-origin-policy-with-regards-to-javascript/en-US.mdx)\n\n<br>\n\n### What is `'use strict';` in JavaScript for?\n\n<!-- Update here: /questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx -->\n\n`'use strict'` is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.\n\n**Advantages**\n\n- Makes it impossible to accidentally create global variables.\n- Makes assignments which would otherwise silently fail to throw an exception.\n- Makes attempts to delete undeletable properties throw an exception (where before the attempt would simply have no effect).\n- Requires that function parameter names be unique.\n- `this` is `undefined` in the global context.\n- It catches some common coding bloopers, throwing exceptions.\n- It disables features that are confusing or poorly thought out.\n\n**Disadvantages**\n\n- Many missing features that some developers might be used to.\n- No more access to `function.caller` and `function.arguments`.\n- Concatenation of scripts written in different strict modes might cause issues.\n\nOverall, the benefits outweigh the disadvantages and there is not really a need to rely on the features that strict mode prohibits. We should all be using strict mode by default.\n\n<!-- Update here: /questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx)\n\n<br>\n\n### What tools and techniques do you use for debugging JavaScript code?\n\n<!-- Update here: /questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/en-US.mdx -->\n\nSome of the most commonly used tools and techniques for debugging JavaScript:\n\n- JavaScript language\n  - `console` methods (e.g. `console.log()`, `console.error()`, `console.warn()`, `console.table()`)\n  - `debugger` statement\n- Breakpoints (browser or IDE)\n- JavaScript frameworks\n  - [React Devtools](https://github.com/facebook/react-devtools)\n  - [Redux Devtools](https://github.com/gaearon/redux-devtools)\n  - [Vue Devtools](https://github.com/vuejs/vue-devtools)\n- Browser developer tools\n  - **Chrome DevTools**: The most widely used tool for debugging JavaScript. It provides a rich set of features including the ability to set breakpoints, inspect variables, view the call stack, and more.\n  - **Firefox Developer Tools**: Similar to Chrome DevTools with its own set of features for debugging.\n  - **Safari Web Inspector**: Provides tools for debugging on Safari.\n  - **Edge Developer Tools**: Similar to Chrome DevTools, as Edge is now Chromium-based.\n- Network requests\n  - **Postman**: Useful for debugging API calls.\n  - **Fiddler**: Helps capture and inspect HTTP/HTTPS traffic.\n  - **Charles Proxy**: Another tool for intercepting and debugging network calls.\n\n<!-- Update here: /questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/en-US.mdx)\n\n<br>\n\n### How does JavaScript garbage collection work?\n\n<!-- Update here: /questions/how-does-javascript-garbage-collection-work/en-US.mdx -->\n\nGarbage collection in JavaScript is an automatic memory management mechanism that reclaims memory occupied by objects and variables that are no longer in use by the program. The two most common algorithms are mark-and-sweep and generational garbage collection.\n\n**Mark-and-sweep**\n\nThe most common garbage collection algorithm used in JavaScript is the Mark-and-sweep algorithm. It operates in two phases:\n\n- **Marking phase**: The garbage collector traverses the object graph, starting from the root objects (global variables, currently executing functions, etc.), and marks all reachable objects as \"in-use\".\n- **Sweeping phase**: The garbage collector sweeps through memory, removing all unmarked objects, as they are considered unreachable and no longer needed.\n\nThis algorithm effectively identifies and removes objects that have become unreachable, freeing up memory for new allocations.\n\n**Generational garbage collection**\n\nLeveraged by modern JavaScript engines, objects are divided into different generations based on their age and usage patterns. Frequently accessed objects are moved to younger generations, while less frequently used objects are promoted to older generations. This optimization reduces the overhead of garbage collection by focusing on the younger generations, where most objects are short-lived.\n\nDifferent JavaScript engines (differs according to browsers) implement different garbage collection algorithms and there's no standard way of doing garbage collection.\n\n<!-- Update here: /questions/how-does-javascript-garbage-collection-work/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-does-javascript-garbage-collection-work/en-US.mdx)\n\n<br>\n\n### Explain what a single page app is and how to make one SEO-friendly\n\n<!-- Update here: /questions/explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly/en-US.mdx -->\n\nA single page application (SPA) is a web application that loads a single HTML page and dynamically updates content as the user interacts with the app. This approach provides a more fluid user experience but can be challenging for SEO because search engines may not execute JavaScript to render content. To make an SPA SEO-friendly, you can use server-side rendering (SSR) or static site generation (SSG) to ensure that search engines can index your content. Tools like Next.js for React or Nuxt.js for Vue.js can help achieve this.\n\n<!-- Update here: /questions/explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly/en-US.mdx)\n\n<br>\n\n### How can you share code between JavaScript files?\n\n<!-- Update here: /questions/how-can-you-share-code-between-files/en-US.mdx -->\n\nTo share code between JavaScript files, you can use modules. In modern JavaScript, you can use ES6 modules with `export` and `import` statements. For example, you can export a function from one file and import it into another:\n\n```javascript\n// file1.js\nexport function greet() {\n  console.log('Hello, world!');\n}\n\n// file2.js\nimport { greet } from './file1.js';\ngreet();\n```\n\nAlternatively, in Node.js, you can use `module.exports` and `require`:\n\n```javascript\n// file1.js\nmodule.exports = function greet() {\n  console.log('Hello, world!');\n};\n\n// file2.js\nconst greet = require('./file1.js');\ngreet();\n```\n\n<!-- Update here: /questions/how-can-you-share-code-between-files/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-can-you-share-code-between-files/en-US.mdx)\n\n<br>\n\n### How do you organize your code?\n\n<!-- Update here: /questions/how-do-you-organize-your-code-module-pattern-classical-inheritance/en-US.mdx -->\n\nI organize my code by following a modular approach, using a clear folder structure, and adhering to coding standards and best practices. I separate concerns by dividing code into different layers such as components, services, and utilities. I also use naming conventions and documentation to ensure code readability and maintainability.\n\n<!-- Update here: /questions/how-do-you-organize-your-code-module-pattern-classical-inheritance/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/how-do-you-organize-your-code-module-pattern-classical-inheritance/en-US.mdx)\n\n<br>\n\n### What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?\n\n<!-- Update here: /questions/what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript/en-US.mdx -->\n\nUsing languages that compile to JavaScript, like TypeScript or CoffeeScript, can offer several advantages such as improved syntax, type safety, and better tooling. However, they also come with disadvantages like added build steps, potential performance overhead, and the need to learn new syntax.\n\nAdvantages:\n\n- Improved syntax and readability\n- Type safety and error checking\n- Better tooling and editor support\n\nDisadvantages:\n\n- Added build steps and complexity\n- Potential performance overhead\n- Learning curve for new syntax\n\n<!-- Update here: /questions/what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript/en-US.mdx)\n\n<br>\n\n### When would you use `document.write()`?\n\n<!-- Update here: /questions/when-would-you-use-document-write/en-US.mdx -->\n\n`document.write()` is rarely used in modern web development because it can overwrite the entire document if called after the page has loaded. It is mainly used for simple tasks like writing content during the initial page load, such as for educational purposes or quick debugging. However, it is generally recommended to use other methods like `innerHTML`, `appendChild()`, or modern frameworks for manipulating the DOM.\n\n<!-- Update here: /questions/when-would-you-use-document-write/en-US.mdx -->\n\n<br>\n    \n[Back to top ↑](#table-of-contents-all-questions) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/yangshun/top-javascript-interview-questions/edit/main/questions/when-would-you-use-document-write/en-US.mdx)\n\n<br>\n\n\n<!-- QUESTIONS:ALL:END -->\n\n## Questions by Difficulty\n\nJavaScript interview questions categorized by difficulty.\n\n### Basic-level JavaScript Interviews Questions\n\n<!-- QUESTIONS:BASIC:START -->\n\n1. [Explain the concept of \"hoisting\" in JavaScript](#explain-the-concept-of-hoisting-in-javascript)\n2. [What are the differences between JavaScript variables created using `let`, `var` or `const`?](#what-are-the-differences-between-javascript-variables-created-using-let-var-or-const)\n3. [What is the difference between `==` and `===` in JavaScript?](#what-is-the-difference-between--and--in-javascript)\n4. [What is the event loop in JavaScript runtimes?](#what-is-the-event-loop-in-javascript-runtimes)\n5. [Explain event delegation in JavaScript](#explain-event-delegation-in-javascript)\n6. [Explain how `this` works in JavaScript](#explain-how-this-works-in-javascript)\n7. [Describe the difference between a cookie, `sessionStorage` and `localStorage` in browsers](#describe-the-difference-between-a-cookie-sessionstorage-and-localstorage-in-browsers)\n8. [Describe the difference between `<script>`, `<script async>` and `<script defer>`](#describe-the-difference-between-script-script-async-and-script-defer)\n9. [What's the difference between a JavaScript variable that is: `null`, `undefined` or undeclared?](#whats-the-difference-between-a-javascript-variable-that-is-null-undefined-or-undeclared)\n10. [What's the difference between `.call` and `.apply` in JavaScript?](#whats-the-difference-between-call-and-apply-in-javascript)\n11. [Explain `Function.prototype.bind` in JavaScript](#explain-functionprototypebind-in-javascript)\n12. [What advantage is there for using the JavaScript arrow syntax for a method in a constructor?](#what-advantage-is-there-for-using-the-javascript-arrow-syntax-for-a-method-in-a-constructor)\n13. [Explain how prototypal inheritance works in JavaScript](#explain-how-prototypal-inheritance-works-in-javascript)\n14. [Difference between: `function Person(){}`, `const person = Person()`, and `const person = new Person()` in JavaScript?](#difference-between-function-person-const-person--person-and-const-person--new-person-in-javascript)\n15. [Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}` in JavaScript](#explain-the-differences-on-the-usage-of-foo-between-function-foo--and-var-foo--function--in-javascript)\n16. [What are the various ways to create objects in JavaScript?](#what-are-the-various-ways-to-create-objects-in-javascript)\n17. [What is the definition of a higher-order function in JavaScript?](#what-is-the-definition-of-a-higher-order-function-in-javascript)\n18. [What are the differences between JavaScript ES2015 classes and ES5 function constructors?](#what-are-the-differences-between-javascript-es2015-classes-and-es5-function-constructors)\n19. [Describe event bubbling in JavaScript and browsers](#describe-event-bubbling-in-javascript-and-browsers)\n20. [Describe event capturing in JavaScript and browsers](#describe-event-capturing-in-javascript-and-browsers)\n21. [What is the difference between `mouseenter` and `mouseover` event in JavaScript and browsers?](#what-is-the-difference-between-mouseenter-and-mouseover-event-in-javascript-and-browsers)\n22. [Explain the difference between synchronous and asynchronous functions in JavaScript](#explain-the-difference-between-synchronous-and-asynchronous-functions-in-javascript)\n23. [Explain AJAX in as much detail as possible](#explain-ajax-in-as-much-detail-as-possible)\n24. [What are the advantages and disadvantages of using AJAX?](#what-are-the-advantages-and-disadvantages-of-using-ajax)\n25. [What are the differences between `XMLHttpRequest` and `fetch()` in JavaScript and browsers?](#what-are-the-differences-between-xmlhttprequest-and-fetch-in-javascript-and-browsers)\n26. [What are the various data types in JavaScript?](#what-are-the-various-data-types-in-javascript)\n27. [What language constructs do you use for iterating over object properties and array items in JavaScript?](#what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items-in-javascript)\n28. [What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?](#what-are-the-benefits-of-using-spread-syntax-in-javascript-and-how-is-it-different-from-rest-syntax)\n29. [What is the difference between a `Map` object and a plain object in JavaScript?](#what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript)\n30. [What are the differences between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript?](#what-are-the-differences-between-mapset-and-weakmapweakset-in-javascript)\n31. [Can you offer a use case for the new arrow => function syntax?](#can-you-offer-a-use-case-for-the-new-arrow--function-syntax)\n32. [Explain the concept of a callback function in asynchronous operations](#explain-the-concept-of-a-callback-function-in-asynchronous-operations)\n33. [Explain the concept of caching and how it can be used to improve performance](#explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance)\n34. [Explain the concept of debouncing and throttling](#explain-the-concept-of-debouncing-and-throttling)\n35. [Explain the concept of destructuring assignment for objects and arrays](#explain-the-concept-of-destructuring-assignment-for-objects-and-arrays)\n36. [Explain the concept of hoisting with regards to functions](#explain-the-concept-of-hoisting-with-regards-to-functions)\n37. [Explain the concept of inheritance in ES2015 classes](#explain-the-concept-of-inheritance-in-es2015-classes)\n38. [Explain the concept of lazy loading and how it can improve performance](#explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance)\n39. [Explain the concept of lexical scoping](#explain-the-concept-of-lexical-scoping)\n40. [Explain the concept of scope in JavaScript](#explain-the-concept-of-scope-in-javascript)\n41. [Explain the concept of the Prototype pattern](#explain-the-concept-of-the-prototype-pattern)\n42. [Explain the concept of the Singleton pattern](#explain-the-concept-of-the-singleton-pattern)\n43. [Explain the concept of the spread operator and its uses](#explain-the-concept-of-the-spread-operator-and-its-uses)\n44. [Explain the concept of `this` binding in event handlers](#explain-the-concept-of-this-binding-in-event-handlers)\n45. [Explain the difference between classical inheritance and prototypal inheritance](#explain-the-difference-between-classical-inheritance-and-prototypal-inheritance)\n46. [Explain the difference between `document.querySelector()` and `document.getElementById()`](#explain-the-difference-between-documentqueryselector-and-documentgetelementbyid)\n47. [Explain the difference between dot notation and bracket notation for accessing object properties](#explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties)\n48. [Explain the difference between global scope, function scope, and block scope](#explain-the-difference-between-global-scope-function-scope-and-block-scope)\n49. [Explain the difference between shallow copy and deep copy](#explain-the-difference-between-shallow-copy-and-deep-copy)\n50. [Explain the difference in hoisting between `var`, `let`, and `const`](#explain-the-difference-in-hoisting-between-var-let-and-const)\n51. [How can closures be used to create private variables?](#how-can-closures-be-used-to-create-private-variables)\n52. [How can you avoid problems related to hoisting?](#how-can-you-avoid-problems-related-to-hoisting)\n53. [How can you share code between JavaScript files?](#how-can-you-share-code-between-javascript-files)\n54. [How do `Set`s and `Map`s handle equality checks for objects?](#how-do-sets-and-maps-handle-equality-checks-for-objects)\n55. [How do you access the index of an element in an array during iteration?](#how-do-you-access-the-index-of-an-element-in-an-array-during-iteration)\n56. [How do you add, remove, and modify HTML elements using JavaScript?](#how-do-you-add-remove-and-modify-html-elements-using-javascript)\n57. [How do you add, remove, and update elements in an array?](#how-do-you-add-remove-and-update-elements-in-an-array)\n58. [How do you check if an object has a specific property?](#how-do-you-check-if-an-object-has-a-specific-property)\n59. [How do you check the data type of a variable?](#how-do-you-check-the-data-type-of-a-variable)\n60. [How do you convert a `Set` to an array in JavaScript?](#how-do-you-convert-a-set-to-an-array-in-javascript)\n61. [How do you convert a string to a number in JavaScript?](#how-do-you-convert-a-string-to-a-number-in-javascript)\n62. [How do you create a constructor function?](#how-do-you-create-a-constructor-function)\n63. [How do you get the query string values of the current page in JavaScript?](#how-do-you-get-the-query-string-values-of-the-current-page-in-javascript)\n64. [How do you handle errors in asynchronous operations?](#how-do-you-handle-errors-in-asynchronous-operations)\n65. [How do you handle errors using `try...catch` blocks?](#how-do-you-handle-errors-using-trycatch-blocks)\n66. [How do you import and export modules in JavaScript?](#how-do-you-import-and-export-modules-in-javascript)\n67. [How do you make an HTTP request using the Fetch API?](#how-do-you-make-an-http-request-using-the-fetch-api)\n68. [How do you manipulate CSS styles using JavaScript?](#how-do-you-manipulate-css-styles-using-javascript)\n69. [How do you prevent the default behavior of an event?](#how-do-you-prevent-the-default-behavior-of-an-event)\n70. [How do you redirect to a new page in JavaScript?](#how-do-you-redirect-to-a-new-page-in-javascript)\n71. [How do you reliably determine whether an object is empty?](#how-do-you-reliably-determine-whether-an-object-is-empty)\n72. [How do you use `window.history` API?](#how-do-you-use-windowhistory-api)\n73. [Provide some examples of how currying and partial application can be used](#provide-some-examples-of-how-currying-and-partial-application-can-be-used)\n74. [What are callback functions and how are they used?](#what-are-callback-functions-and-how-are-they-used)\n75. [What are default parameters and how are they used?](#what-are-default-parameters-and-how-are-they-used)\n76. [What are design patterns and why are they useful?](#what-are-design-patterns-and-why-are-they-useful)\n77. [What are event listeners and how are they used?](#what-are-event-listeners-and-how-are-they-used)\n78. [What are modules and why are they useful?](#what-are-modules-and-why-are-they-useful)\n79. [What are Promises and how do they work?](#what-are-promises-and-how-do-they-work)\n80. [What are rest parameters and how are they used?](#what-are-rest-parameters-and-how-are-they-used)\n81. [What are `Set`s and `Map`s and how are they used?](#what-are-sets-and-maps-and-how-are-they-used)\n82. [What are some popular JavaScript testing frameworks?](#what-are-some-popular-javascript-testing-frameworks)\n83. [What are some tools that can be used for JavaScript testing?](#what-are-some-tools-that-can-be-used-for-javascript-testing)\n84. [What are template literals and how are they used?](#what-are-template-literals-and-how-are-they-used)\n85. [What are the advantages of using the spread operator with arrays and objects?](#what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects)\n86. [What are the common pitfalls of using the `this` keyword?](#what-are-the-common-pitfalls-of-using-the-this-keyword)\n87. [What are the different methods for iterating over an array?](#what-are-the-different-methods-for-iterating-over-an-array)\n88. [What are the different ways to copy an object or an array?](#what-are-the-different-ways-to-copy-an-object-or-an-array)\n89. [What are the different ways to make an API call in JavaScript?](#what-are-the-different-ways-to-make-an-api-call-in-javascript)\n90. [What do you think of CommonJS vs ESM?](#what-do-you-think-of-commonjs-vs-esm)\n91. [What is recursion and how is it used in JavaScript?](#what-is-recursion-and-how-is-it-used-in-javascript)\n92. [What is the difference between a parameter and an argument?](#what-is-the-difference-between-a-parameter-and-an-argument)\n93. [What is the DOM and how is it structured?](#what-is-the-dom-and-how-is-it-structured)\n94. [What is the purpose of the `break` and `continue` statements?](#what-is-the-purpose-of-the-break-and-continue-statements)\n95. [What is the purpose of the `finally` block?](#what-is-the-purpose-of-the-finally-block)\n96. [What is the purpose of the `new` keyword?](#what-is-the-purpose-of-the-new-keyword)\n97. [What is the purpose of the `switch` statement?](#what-is-the-purpose-of-the-switch-statement)\n98. [What is the spread operator and how is it used?](#what-is-the-spread-operator-and-how-is-it-used)\n99. [What is the ternary operator and how is it used?](#what-is-the-ternary-operator-and-how-is-it-used)\n100. [What is the use of `Promise.all()`](#what-is-the-use-of-promiseall)\n\n<!-- QUESTIONS:BASIC:END -->\n\n### Intermediate-level JavaScript Interviews Questions\n\n<!-- QUESTIONS:INTERMEDIATE:START -->\n\n1. [What's a typical use case for anonymous functions in JavaScript?](#whats-a-typical-use-case-for-anonymous-functions-in-javascript)\n2. [What is a closure in JavaScript, and how/why would you use one?](#what-is-a-closure-in-javascript-and-howwhy-would-you-use-one)\n3. [What are the pros and cons of using Promises instead of callbacks in JavaScript?](#what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks-in-javascript)\n4. [How do you abort a web request using `AbortController` in JavaScript?](#how-do-you-abort-a-web-request-using-abortcontroller-in-javascript)\n5. [Why is extending built-in JavaScript objects not a good idea?](#why-is-extending-built-in-javascript-objects-not-a-good-idea)\n6. [Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?](#why-is-it-in-general-a-good-idea-to-leave-the-global-javascript-scope-of-a-website-as-is-and-never-touch-it)\n7. [Explain the differences between CommonJS modules and ES modules in JavaScript](#explain-the-differences-between-commonjs-modules-and-es-modules-in-javascript)\n8. [Explain the difference between mutable and immutable objects in JavaScript](#explain-the-difference-between-mutable-and-immutable-objects-in-javascript)\n9. [Why might you want to create static class members in JavaScript?](#why-might-you-want-to-create-static-class-members-in-javascript)\n10. [What are `Symbol`s used for in JavaScript?](#what-are-symbols-used-for-in-javascript)\n11. [What are JavaScript object getters and setters for?](#what-are-javascript-object-getters-and-setters-for)\n12. [What tools and techniques do you use for debugging JavaScript code?](#what-tools-and-techniques-do-you-use-for-debugging-javascript-code)\n13. [Difference between document `load` event and document `DOMContentLoaded` event?](#difference-between-document-load-event-and-document-domcontentloaded-event)\n14. [Explain how JSONP works (and how it's not really Ajax)](#explain-how-jsonp-works-and-how-its-not-really-ajax)\n15. [Explain the concept of a microtask queue](#explain-the-concept-of-a-microtask-queue)\n16. [Explain the concept of code coverage and how it can be used to assess test quality](#explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality)\n17. [Explain the concept of Content Security Policy (CSP) and how it enhances security](#explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security)\n18. [Explain the concept of Cross-Site Request Forgery (CSRF) and its mitigation techniques](#explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques)\n19. [Explain the concept of error propagation in JavaScript](#explain-the-concept-of-error-propagation-in-javascript)\n20. [Explain the concept of input validation and its importance in security](#explain-the-concept-of-input-validation-and-its-importance-in-security)\n21. [Explain the concept of partial application](#explain-the-concept-of-partial-application)\n22. [Explain the concept of tagged templates](#explain-the-concept-of-tagged-templates)\n23. [Explain the concept of test-driven development (TDD)](#explain-the-concept-of-test-driven-development-tdd)\n24. [Explain the concept of the Strategy pattern](#explain-the-concept-of-the-strategy-pattern)\n25. [Explain the concept of the Web Socket API](#explain-the-concept-of-the-web-socket-api)\n26. [Explain the concept of tree shaking in module bundling](#explain-the-concept-of-tree-shaking-in-module-bundling)\n27. [Explain the difference between unit testing, integration testing, and end-to-end testing](#explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing)\n28. [Explain the different states of a Promise](#explain-the-different-states-of-a-promise)\n29. [Explain the different ways the `this` keyword can be bound](#explain-the-different-ways-the-this-keyword-can-be-bound)\n30. [Explain the event phases in a browser](#explain-the-event-phases-in-a-browser)\n31. [Explain the Observer pattern and its use cases](#explain-the-observer-pattern-and-its-use-cases)\n32. [Explain the same-origin policy with regards to JavaScript](#explain-the-same-origin-policy-with-regards-to-javascript)\n33. [Explain what a single page app is and how to make one SEO-friendly](#explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly)\n34. [How can you create custom error objects?](#how-can-you-create-custom-error-objects)\n35. [How can you prevent SQL injection vulnerabilities in JavaScript applications?](#how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications)\n36. [How can you test asynchronous code in JavaScript?](#how-can-you-test-asynchronous-code-in-javascript)\n37. [How do currying and partial application differ from each other?](#how-do-currying-and-partial-application-differ-from-each-other)\n38. [How do `<iframe>` on a page communicate?](#how-do-iframe-on-a-page-communicate)\n39. [How do you detect if JavaScript is disabled on a page?](#how-do-you-detect-if-javascript-is-disabled-on-a-page)\n40. [How do you organize your code?](#how-do-you-organize-your-code)\n41. [How do you write unit tests for JavaScript code?](#how-do-you-write-unit-tests-for-javascript-code)\n42. [How is `Promise.all()` different from `Promise.allSettled()`?](#how-is-promiseall-different-from-promiseallsettled)\n43. [What are Progressive Web Applications (PWAs)?](#what-are-progressive-web-applications-pwas)\n44. [What are some best practices for handling sensitive data in JavaScript?](#what-are-some-best-practices-for-handling-sensitive-data-in-javascript)\n45. [What are some best practices for writing maintainable and effective tests in JavaScript?](#what-are-some-best-practices-for-writing-maintainable-and-effective-tests-in-javascript)\n46. [What are some common performance bottlenecks in JavaScript applications?](#what-are-some-common-performance-bottlenecks-in-javascript-applications)\n47. [What are some common security headers and their purpose?](#what-are-some-common-security-headers-and-their-purpose)\n48. [What are some tools and techniques for identifying security vulnerabilities in JavaScript code?](#what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code)\n49. [What are the benefits of using a module bundler?](#what-are-the-benefits-of-using-a-module-bundler)\n50. [What are the benefits of using currying and partial application?](#what-are-the-benefits-of-using-currying-and-partial-application)\n51. [What are the different types of errors in JavaScript?](#what-are-the-different-types-of-errors-in-javascript)\n52. [What are the different types of testing in software development?](#what-are-the-different-types-of-testing-in-software-development)\n53. [What are the metadata fields of a module?](#what-are-the-metadata-fields-of-a-module)\n54. [What are the potential issues caused by hoisting?](#what-are-the-potential-issues-caused-by-hoisting)\n55. [What are the potential pitfalls of using closures?](#what-are-the-potential-pitfalls-of-using-closures)\n56. [What is async/await and how does it simplify asynchronous code?](#what-is-asyncawait-and-how-does-it-simplify-asynchronous-code)\n57. [What is Cross-Site Scripting (XSS) and how can you prevent it?](#what-is-cross-site-scripting-xss-and-how-can-you-prevent-it)\n58. [What is currying and how does it work?](#what-is-currying-and-how-does-it-work)\n59. [What is `Object.freeze()` for?](#what-is-objectfreeze-for)\n60. [What is `Object.preventExtensions()` for?](#what-is-objectpreventextensions-for)\n61. [What is `Object.seal()` for?](#what-is-objectseal-for)\n62. [What is the Command pattern and how is it used?](#what-is-the-command-pattern-and-how-is-it-used)\n63. [What is the Decorator pattern and how is it used?](#what-is-the-decorator-pattern-and-how-is-it-used)\n64. [What is the difference between `event.preventDefault()` and `event.stopPropagation()`?](#what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation)\n65. [What is the difference between `innerHTML` and `textContent`?](#what-is-the-difference-between-innerhtml-and-textcontent)\n66. [What is the difference between `setTimeout()`, `setImmediate()`, and `process.nextTick()`?](#what-is-the-difference-between-settimeout-setimmediate-and-processnexttick)\n67. [What is the difference between the Window object and the Document object?](#what-is-the-difference-between-the-window-object-and-the-document-object)\n68. [What is the Factory pattern and how is it used?](#what-is-the-factory-pattern-and-how-is-it-used)\n69. [What is the `Intl` namespace object for?](#what-is-the-intl-namespace-object-for)\n70. [What is the Module pattern and how does it help with encapsulation?](#what-is-the-module-pattern-and-how-does-it-help-with-encapsulation)\n71. [What is the prototype chain and how does it work?](#what-is-the-prototype-chain-and-how-does-it-work)\n72. [What's the difference between an \"attribute\" and a \"property\" in the DOM?](#whats-the-difference-between-an-attribute-and-a-property-in-the-dom)\n\n<!-- QUESTIONS:INTERMEDIATE:END -->\n\n### Advanced-level JavaScript Interviews Questions\n\n<!-- QUESTIONS:ADVANCED:START -->\n\n1. [What is `'use strict';` in JavaScript for?](#what-is-use-strict-in-javascript-for)\n2. [What are JavaScript polyfills for?](#what-are-javascript-polyfills-for)\n3. [What are iterators and generators in JavaScript and what are they used for?](#what-are-iterators-and-generators-in-javascript-and-what-are-they-used-for)\n4. [What are server-sent events?](#what-are-server-sent-events)\n5. [What are JavaScript object property flags and descriptors?](#what-are-javascript-object-property-flags-and-descriptors)\n6. [What are proxies in JavaScript used for?](#what-are-proxies-in-javascript-used-for)\n7. [What are workers in JavaScript used for?](#what-are-workers-in-javascript-used-for)\n8. [How does JavaScript garbage collection work?](#how-does-javascript-garbage-collection-work)\n9. [Explain why the following doesn't work as an IIFE: `function foo(){}();`. What needs to be changed to properly make it an IIFE?](#explain-why-the-following-doesnt-work-as-an-iife-function-foo-what-needs-to-be-changed-to-properly-make-it-an-iife)\n10. [How can you implement secure authentication and authorization in JavaScript applications?](#how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications)\n11. [How can you optimize DOM manipulation for better performance?](#how-can-you-optimize-dom-manipulation-for-better-performance)\n12. [How can you optimize network requests for better performance?](#how-can-you-optimize-network-requests-for-better-performance)\n13. [How can you prevent clickjacking attacks?](#how-can-you-prevent-clickjacking-attacks)\n14. [How do you validate form elements using the Constraint Validation API?](#how-do-you-validate-form-elements-using-the-constraint-validation-api)\n15. [How does hoisting affect function declarations and expressions?](#how-does-hoisting-affect-function-declarations-and-expressions)\n16. [What are mocks and stubs and how are they used in testing?](#what-are-mocks-and-stubs-and-how-are-they-used-in-testing)\n17. [What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?](#what-are-some-of-the-advantagesdisadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript)\n18. [What are some techniques for reducing reflows and repaints?](#what-are-some-techniques-for-reducing-reflows-and-repaints)\n19. [What are some tools that can be used to measure and analyze JavaScript performance?](#what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance)\n20. [What are Web Workers and how can they be used to improve performance?](#what-are-web-workers-and-how-can-they-be-used-to-improve-performance)\n21. [When would you use `document.write()`?](#when-would-you-use-documentwrite)\n\n<!-- QUESTIONS:ADVANCED:END -->\n"
  },
  {
    "path": "__template__/concise/en-US.mdx",
    "content": "---\ntitle: TODO_REPLACE_TITLE\n---\n\nTODO_REPLACE_BODY\n"
  },
  {
    "path": "__template__/concise/metadata.json",
    "content": "{\n  \"slug\": \"todo-change-me\",\n  \"languages\": [],\n  \"companies\": [],\n  \"premium\": false,\n  \"duration\": 5,\n  \"published\": false,\n  \"featured\": false,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\"\n}\n"
  },
  {
    "path": "__template__/detailed/en-US.mdx",
    "content": "---\ntitle: TODO_REPLACE_TITLE\n---\n\n## TL;DR\n\n<!-- Do not use any headings within the TL;DR section.  -->\n\n---\n\n## Some heading\n\nTODO\n\n## Further reading\n\n- [Foo](#foo)\n- [Bar](#bar)\n"
  },
  {
    "path": "__template__/detailed/metadata.json",
    "content": "{\n  \"slug\": \"todo-change-me\",\n  \"languages\": [],\n  \"companies\": [],\n  \"premium\": false,\n  \"duration\": 5,\n  \"published\": false,\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\"\n}\n"
  },
  {
    "path": "data/questions.json",
    "content": "{\n  \"Data Types & Variables\": [\n    \"what-are-the-various-data-types-in-javascript\",\n    \"how-do-you-check-the-data-type-of-a-variable\",\n    \"whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states\",\n    \"what-are-the-differences-between-variables-created-using-let-var-or-const\",\n    \"why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it\",\n    \"how-do-you-convert-a-string-to-a-number-in-javascript\",\n    \"what-are-template-literals-and-how-are-they-used\",\n    \"explain-the-concept-of-tagged-templates\",\n    \"what-is-the-spread-operator-and-how-is-it-used\",\n    \"what-are-symbols-used-for\",\n    \"what-are-proxies-in-javascript-used-for\"\n  ],\n  \"Hoisting\": [\n    \"explain-hoisting\",\n    \"explain-the-difference-in-hoisting-between-var-let-and-const\",\n    \"how-does-hoisting-affect-function-declarations-and-expressions\",\n    \"what-are-the-potential-issues-caused-by-hoisting\",\n    \"how-can-you-avoid-problems-related-to-hoisting\"\n  ],\n  \"Operators & Control Flow\": [\n    \"what-is-the-difference-between-double-equal-and-triple-equal\",\n    \"what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items\",\n    \"what-is-the-purpose-of-the-break-and-continue-statements\",\n    \"what-is-the-ternary-operator-and-how-is-it-used\",\n    \"how-do-you-access-the-index-of-an-element-in-an-array-during-iteration\",\n    \"what-is-the-purpose-of-the-switch-statement\",\n    \"what-are-rest-parameters-and-how-are-they-used\",\n    \"explain-the-concept-of-the-spread-operator-and-its-uses\",\n    \"what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax\",\n    \"what-are-iterators-and-generators-and-what-are-they-used-for\"\n  ],\n  \"Functions\": [\n    \"explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function\",\n    \"what-is-the-difference-between-a-parameter-and-an-argument\",\n    \"explain-the-concept-of-hoisting-with-regards-to-functions\",\n    \"whats-the-difference-between-call-and-apply\",\n    \"can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions\",\n    \"difference-between-function-person-var-person-person-and-var-person-new-person\",\n    \"what-is-the-definition-of-a-higher-order-function\",\n    \"what-are-callback-functions-and-how-are-they-used\",\n    \"whats-a-typical-use-case-for-anonymous-functions\",\n    \"what-is-recursion-and-how-is-it-used-in-javascript\",\n    \"what-are-default-parameters-and-how-are-they-used\",\n    \"explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife\"\n  ],\n  \"Objects & Arrays\": [\n    \"what-are-the-various-ways-to-create-objects-in-javascript\",\n    \"explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties\",\n    \"what-are-the-different-methods-for-iterating-over-an-array\",\n    \"how-do-you-add-remove-and-update-elements-in-an-array\",\n    \"what-are-the-different-ways-to-copy-an-object-or-an-array\",\n    \"explain-the-difference-between-shallow-copy-and-deep-copy\",\n    \"what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects\",\n    \"how-do-you-check-if-an-object-has-a-specific-property\",\n    \"explain-the-difference-between-mutable-and-immutable-objects\",\n    \"explain-the-concept-of-destructuring-assignment-for-objects-and-arrays\",\n    \"what-is-objectfreeze-for\",\n    \"what-is-objectseal-for\",\n    \"what-is-objectpreventextensions-for\",\n    \"what-are-javascript-object-getters-and-setters-for\",\n    \"what-are-javascript-object-property-flags-and-descriptors\",\n    \"how-do-you-reliably-determine-whether-an-object-is-empty\"\n  ],\n  \"Asynchronous JavaScript\": [\n    \"what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue\",\n    \"explain-the-difference-between-synchronous-and-asynchronous-functions\",\n    \"explain-the-concept-of-a-callback-function-in-asynchronous-operations\",\n    \"what-are-promises-and-how-do-they-work\",\n    \"explain-the-different-states-of-a-promise\",\n    \"what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks\",\n    \"what-is-the-use-of-promiseall\",\n    \"how-is-promiseall-different-from-promiseallsettled\",\n    \"what-is-asyncawait-and-how-does-it-simplify-asynchronous-code\",\n    \"how-do-you-handle-errors-in-asynchronous-operations\",\n    \"explain-the-concept-of-a-microtask-queue\",\n    \"what-is-the-difference-between-settimeout-setimmediate-and-processnexttick\"\n  ],\n  \"Prototypes & Inheritance\": [\n    \"explain-how-prototypal-inheritance-works\",\n    \"what-is-the-prototype-chain-and-how-does-it-work\",\n    \"explain-the-difference-between-classical-inheritance-and-prototypal-inheritance\",\n    \"explain-the-concept-of-inheritance-in-es2015-classes\",\n    \"what-is-the-purpose-of-the-new-keyword\",\n    \"how-do-you-create-a-constructor-function\",\n    \"what-are-the-differences-between-es6-class-and-es5-function-constructors\",\n    \"what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor\",\n    \"why-you-might-want-to-create-static-class-members\"\n  ],\n  \"Closures & Scope\": [\n    \"what-is-a-closure-and-how-why-would-you-use-one\",\n    \"explain-the-concept-of-lexical-scoping\",\n    \"explain-the-concept-of-scope-in-javascript\",\n    \"how-can-closures-be-used-to-create-private-variables\",\n    \"what-are-the-potential-pitfalls-of-using-closures\",\n    \"explain-the-difference-between-global-scope-function-scope-and-block-scope\"\n  ],\n  \"This Keyword\": [\n    \"explain-how-this-works-in-javascript\",\n    \"explain-function-prototype-bind\",\n    \"explain-the-different-ways-the-this-keyword-can-be-bound\",\n    \"what-are-the-common-pitfalls-of-using-the-this-keyword\",\n    \"explain-the-concept-of-this-binding-in-event-handlers\"\n  ],\n  \"DOM Manipulation & Events\": [\n    \"what-is-the-dom-and-how-is-it-structured\",\n    \"whats-the-difference-between-an-attribute-and-a-property\",\n    \"explain-the-difference-between-documentqueryselector-and-documentgetelementbyid\",\n    \"how-do-you-add-remove-and-modify-html-elements-using-javascript\",\n    \"what-are-event-listeners-and-how-are-they-used\",\n    \"explain-the-event-phases-in-a-browser\",\n    \"describe-event-bubbling\",\n    \"describe-event-capturing\",\n    \"explain-event-delegation\",\n    \"how-do-you-prevent-the-default-behavior-of-an-event\",\n    \"what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation\",\n    \"what-is-the-difference-between-mouseenter-and-mouseover-event\",\n    \"what-is-the-difference-between-innerhtml-and-textcontent\",\n    \"how-do-you-manipulate-css-styles-using-javascript\"\n  ],\n  \"Web APIs & Browser APIs\": [\n    \"describe-the-difference-between-script-async-and-script-defer\",\n    \"what-is-the-difference-between-the-window-object-and-the-document-object\",\n    \"describe-the-difference-between-a-cookie-sessionstorage-and-localstorage\",\n    \"how-do-you-make-an-http-request-using-the-fetch-api\",\n    \"what-are-the-different-ways-to-make-an-api-call-in-javascript\",\n    \"explain-ajax-in-as-much-detail-as-possible\",\n    \"what-are-the-advantages-and-disadvantages-of-using-ajax\",\n    \"what-are-the-differences-between-xmlhttprequest-and-fetch\",\n    \"how-do-you-abort-a-web-request-using-abortcontrollers\",\n    \"explain-how-jsonp-works-and-how-its-not-really-ajax\",\n    \"what-are-workers-in-javascript-used-for\",\n    \"explain-the-concept-of-the-web-socket-api\",\n    \"what-are-javascript-polyfills-for\",\n    \"how-do-you-detect-if-javascript-is-disabled-on-a-page\",\n    \"what-is-the-intl-namespace-object-for\",\n    \"how-do-you-validate-form-elements-using-the-constraint-validation-api\",\n    \"how-do-you-use-windowhistory-api\",\n    \"how-do-iframe-on-a-page-communicate\",\n    \"difference-between-document-load-event-and-document-domcontentloaded-event\",\n    \"how-do-you-redirect-to-a-new-page-in-javascript\",\n    \"how-do-you-get-the-query-string-values-of-the-current-page-in-javascript\",\n    \"what-are-server-sent-events\",\n    \"what-are-progressive-web-applications-pwas\"\n  ],\n  \"Modules\": [\n    \"what-are-modules-and-why-are-they-useful\",\n    \"explain-the-differences-between-commonjs-modules-and-es-modules\",\n    \"how-do-you-import-and-export-modules-in-javascript\",\n    \"what-are-the-benefits-of-using-a-module-bundler\",\n    \"explain-the-concept-of-tree-shaking-in-module-bundling\",\n    \"what-are-the-metadata-fields-of-a-module\",\n    \"what-do-you-think-of-amd-vs-commonjs\"\n  ],\n  \"Error Handling\": [\n    \"what-are-the-different-types-of-errors-in-javascript\",\n    \"how-do-you-handle-errors-using-trycatch-blocks\",\n    \"what-is-the-purpose-of-the-finally-block\",\n    \"how-can-you-create-custom-error-objects\",\n    \"explain-the-concept-of-error-propagation-in-javascript\"\n  ],\n  \"Currying & Partial Application\": [\n    \"what-is-currying-and-how-does-it-work\",\n    \"explain-the-concept-of-partial-application\",\n    \"what-are-the-benefits-of-using-currying-and-partial-application\",\n    \"provide-some-examples-of-how-currying-and-partial-application-can-be-used\",\n    \"how-do-currying-and-partial-application-differ-from-each-other\"\n  ],\n  \"Sets & Maps\": [\n    \"what-are-sets-and-maps-and-how-are-they-used\",\n    \"what-are-the-differences-between-map-set-and-weakmap-weakset\",\n    \"how-do-you-convert-a-set-to-an-array-in-javascript\",\n    \"what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript\",\n    \"how-do-sets-and-maps-handle-equality-checks-for-objects\"\n  ],\n  \"Performance Optimization\": [\n    \"what-are-some-common-performance-bottlenecks-in-javascript-applications\",\n    \"explain-the-concept-of-debouncing-and-throttling\",\n    \"how-can-you-optimize-dom-manipulation-for-better-performance\",\n    \"what-are-some-techniques-for-reducing-reflows-and-repaints\",\n    \"explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance\",\n    \"what-are-web-workers-and-how-can-they-be-used-to-improve-performance\",\n    \"explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance\",\n    \"what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance\",\n    \"how-can-you-optimize-network-requests-for-better-performance\"\n  ],\n  \"Testing\": [\n    \"what-are-the-different-types-of-testing-in-software-development\",\n    \"explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing\",\n    \"what-are-some-popular-javascript-testing-frameworks\",\n    \"how-do-you-write-unit-tests-for-javascript-code\",\n    \"explain-the-concept-of-test-driven-development-tdd\",\n    \"what-are-mocks-and-stubs-and-how-are-they-used-in-testing\",\n    \"how-can-you-test-asynchronous-code-in-javascript\",\n    \"what-are-some-best-practices-for-writing-maintainable-and-effective-tests\",\n    \"explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality\",\n    \"what-are-some-tools-that-can-be-used-for-javascript-testing\"\n  ],\n  \"Design Patterns\": [\n    \"what-are-design-patterns-and-why-are-they-useful\",\n    \"explain-the-concept-of-the-singleton-pattern\",\n    \"what-is-the-factory-pattern-and-how-is-it-used\",\n    \"explain-the-observer-pattern-and-its-use-cases\",\n    \"what-is-the-module-pattern-and-how-does-it-help-with-encapsulation\",\n    \"explain-the-concept-of-the-prototype-pattern\",\n    \"what-is-the-decorator-pattern-and-how-is-it-used\",\n    \"explain-the-concept-of-the-strategy-pattern\",\n    \"what-is-the-command-pattern-and-how-is-it-used\",\n    \"why-is-extending-built-in-javascript-objects-not-a-good-idea\"\n  ],\n  \"Security\": [\n    \"what-is-cross-site-scripting-xss-and-how-can-you-prevent-it\",\n    \"explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques\",\n    \"how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications\",\n    \"what-are-some-best-practices-for-handling-sensitive-data-in-javascript\",\n    \"explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security\",\n    \"what-are-some-common-security-headers-and-their-purpose\",\n    \"how-can-you-prevent-clickjacking-attacks\",\n    \"explain-the-concept-of-input-validation-and-its-importance-in-security\",\n    \"what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code\",\n    \"how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications\",\n    \"explain-the-same-origin-policy-with-regards-to-javascript\"\n  ],\n  \"Misc\": [\n    \"what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it\",\n    \"what-tools-and-techniques-do-you-use-for-debugging-javascript-code\",\n    \"how-does-javascript-garbage-collection-work\",\n    \"explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly\",\n    \"how-can-you-share-code-between-files\",\n    \"how-do-you-organize-your-code-module-pattern-classical-inheritance\",\n    \"what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript\",\n    \"when-would-you-use-document-write\"\n  ]\n}\n"
  },
  {
    "path": "langnostic.config.ts",
    "content": "import { ConfigType } from 'langnostic';\n\nexport default {\n  ai: {\n    provider: 'google',\n  },\n  localeConfig: {\n    source: 'en-US',\n    target: ['zh-CN'],\n  },\n  groups: [\n    {\n      name: 'quiz-js',\n      plugin: 'mdx',\n      paths: [\n        {\n          source: './questions/*/en-US.mdx',\n          target: './questions/*/{locale}.mdx',\n        },\n      ],\n    },\n  ],\n} satisfies ConfigType;\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"top-javascript-interview-questions\",\n  \"version\": \"1.0.0\",\n  \"description\": \"List of top JavaScript interview questions\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"gen\": \"tsx scripts/gen.ts\",\n    \"rank\": \"tsx scripts/rank.ts\",\n    \"i18n\": \"langnostic translate\"\n  },\n  \"keywords\": [\n    \"javascript\",\n    \"interview\",\n    \"questions\"\n  ],\n  \"author\": \"yangshun\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"@types/node\": \"^20.14.2\",\n    \"github-slugger\": \"^2.0.0\",\n    \"globby\": \"^14.0.1\",\n    \"gray-matter\": \"^4.0.3\",\n    \"langnostic\": \"^0.0.8\",\n    \"lodash-es\": \"^4.17.21\",\n    \"tsx\": \"^4.15.1\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^5.8.2\"\n  },\n  \"engines\": {\n    \"node\": \">= 22.15.0\"\n  },\n  \"packageManager\": \"pnpm@10.9.0\"\n}\n"
  },
  {
    "path": "pnpm-workspace.yaml",
    "content": "# To let pnpm know this is the repo root as it's also installed as a submodule\n"
  },
  {
    "path": "questions/can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"5ba0d4da\",\n    \"subtitle\": \"4d47ead\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"4010c03b\",\n        \"b7950cbe\",\n        \"2a7816d0\",\n        \"678d2642\",\n        \"7ac0c956\",\n        \"4e1ff55c\",\n        \"d3b7242\",\n        \"a203d791\",\n        \"8550812\",\n        \"54dee6b3\",\n        \"a6f52eea\",\n        \"cb0ae1a8\",\n        \"e5dcf6c0\",\n        \"839f0ebb\",\n        \"d8fa43b8\",\n        \"30eae852\",\n        \"be10dd6f\",\n        \"1f4770e5\",\n        \"6232231\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4010c03b\",\n        \"b7950cbe\",\n        \"2a7816d0\",\n        \"678d2642\",\n        \"7ac0c956\",\n        \"4e1ff55c\",\n        \"d3b7242\",\n        \"a203d791\",\n        \"8550812\",\n        \"54dee6b3\",\n        \"a6f52eea\",\n        \"cb0ae1a8\",\n        \"e5dcf6c0\",\n        \"839f0ebb\",\n        \"d8fa43b8\",\n        \"30eae852\",\n        \"be10dd6f\",\n        \"1f4770e5\",\n        \"6232231\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions/en-US.mdx",
    "content": "---\ntitle: Can you offer a use case for the new arrow => function syntax?\nsubtitle: How does this new syntax differ from other functions?\n---\n\n## TL;DR\n\nArrow functions provide a concise syntax for writing functions in JavaScript. They are particularly useful for maintaining the `this` context within methods and callbacks. For example, in an event handler or array method like `map`, arrow functions can simplify the code and avoid issues with `this` binding.\n\n```js live\nconst numbers = [1, 2, 3];\nconst doubled = numbers.map((n) => n * 2);\nconsole.log(doubled); // [2, 4, 6]\n```\n\n---\n\n## Use case for the new arrow => function syntax\n\n### Simplifying syntax\n\nArrow functions provide a more concise way to write functions. This is especially useful for short functions or callbacks.\n\n```js live\n// Traditional function\nconst add = function (a, b) {\n  return a + b;\n};\n\n// Arrow function\nconst anotherAdd = (a, b) => a + b;\n\nconsole.log(add(2, 3)); // Output: 5\nconsole.log(anotherAdd(2, 3)); // Output: 5\n```\n\n### Lexical `this` binding\n\nArrow functions do not have their own `this` context. Instead, they inherit `this` from the surrounding scope. This is particularly useful in methods and callbacks where the `this` context can be tricky.\n\n```js live\nfunction Timer() {\n  this.seconds = 0;\n  this.increment = () => {\n    this.seconds++; // 'this.seconds' is inherited from the outer scope\n    console.log(this.seconds);\n  };\n}\n\nconst timer = new Timer();\ntimer.increment(); // 1\ntimer.increment(); // 2\n```\n\nIn the example above, using a traditional function inside `setInterval` would require additional steps to maintain the correct `this` context.\n\n### Using arrow functions in array methods\n\nArrow functions are often used in array methods like `map`, `filter`, and `reduce` for cleaner and more readable code.\n\n```js live\nconst numbers = [1, 2, 3, 4, 5];\n\n// Traditional function\nconst doubledTraditional = numbers.map(function (n) {\n  return n * 2;\n});\n\n// Arrow function\nconst doubled = numbers.map((n) => n * 2);\n\nconsole.log(doubled); // [2, 4, 6, 8, 10]\n```\n\n### Event handlers\n\nArrow functions can be used in event handlers to maintain the `this` context of the class or object.\n\n```js live\nclass Button {\n  constructor() {\n    this.count = 0;\n    this.button = document.createElement('button');\n    this.button.innerText = 'Click me';\n    this.button.addEventListener('click', () => {\n      this.count++;\n      console.log('count:', this.count);\n    });\n    document.body.appendChild(this.button);\n  }\n}\n\nconst myButton = new Button();\nmyButton.button.click(); // count: 1\nmyButton.button.click(); // count: 2\n```\n\n## Further reading\n\n- [MDN Web Docs: Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\n- [JavaScript.info: Arrow functions revisited](https://javascript.info/arrow-functions)\n- [Eloquent JavaScript: Functions](https://eloquentjavascript.net/03_functions.html)\n"
  },
  {
    "path": "questions/can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions/metadata.json",
    "content": "{\n  \"slug\": \"can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": false,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 999,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions/pt-BR.mdx",
    "content": "---\ntitle: Você pode oferecer um caso de uso para a nova sintaxe de arrow function =>?\nsubtitle: Como essa nova sintaxe difere de outras funções?\n---\n\nA sintaxe de função `=>`, também conhecida como \"funções de seta\", é um recurso introduzido no ECMAScript 6 (ES6) para o JavaScript. Ela fornece uma maneira mais concisa de escrever funções e também apresenta algumas diferenças em relação ao comportamento do `this` em comparação com expressões de função tradicionais. Aqui está um caso de uso simples para ilustrar sua utilidade:\n\n## Caso de Uso: filtrando um array\n\nImagine que você tenha um array de números e queira filtrar todos os números menores que 10. Usando a sintaxe de função tradicional e a nova sintaxe de função de seta, você pode realizar isso das seguintes maneiras:\n\n### Sintaxe de função tradicional\n\n```js\nconst numbers = [1, 5, 10, 15, 20];\nconst numbersFiltrados = numbers.filter(function (number) {\n  return number >= 10;\n});\n\nconsole.log(numbersFiltrados); // Saída: [10, 15, 20]\n```\n\n### Sintaxe de função de seta\n\n```js\nconst numbers = [1, 5, 10, 15, 20];\nconst numbersFiltrados = numbers.filter((number) => number >= 10);\n\nconsole.log(numbersFiltrados); // Saída: [10, 15, 20]\n```\n\n## Vantagens das funções de seta\n\n1. **Concisão**: As funções de seta são mais concisas, tornando seu código mais curto e mais fácil de ler.\n1. **Comportamento do `this`**: As funções de seta não possuem seu próprio `this`. Em vez disso, elas herdam o `this` do escopo pai no momento em que são definidas. Isso é particularmente útil em cenários em que você está lidando com callbacks e deseja manter o contexto do `this`.\n1. **Retorno Implícito**: Se o corpo da função consistir em uma única expressão, as funções de seta permitem omitir a palavra-chave `return` e as chaves.\n\n## Quando usar funções de seta\n\n- Quando você precisa de uma função rápida de uma única linha.\n- Em funções de retorno de chamada (callbacks) onde você deseja preservar o escopo léxico do `this`.\n- Ao trabalhar com funções de ordem superior como `map`, `filter`, `reduce`, etc.\n\n## Quando não usar funções de seta\n\n- **Métodos em objetos**: As funções de seta não têm seu próprio contexto `this`, o que pode levar a comportamentos inesperados em métodos de objetos.\n- **Como construtores**: As funções de seta não podem ser usadas como construtores e gerarão um erro se usadas com a palavra-chave `new`.\n- **Quando você precisa de hoisting de função**: As funções de seta não são içadas (hoisted), ao contrário das declarações de função tradicionais.\n\nAs funções de seta são uma adição poderosa ao JavaScript, simplificando a sintaxe das funções e abordando algumas armadilhas comuns associadas à palavra-chave `this` em funções tradicionais. Elas são especialmente úteis nos padrões de desenvolvimento JavaScript modernos.\n"
  },
  {
    "path": "questions/can-you-offer-a-use-case-for-the-new-arrow-function-syntax-how-does-this-new-syntax-differ-from-other-functions/zh-CN.mdx",
    "content": "---\ntitle: 箭头 => 函数语法有什么用例？\nsubtitle: 这种新语法与其他函数有何不同？\n---\n\n## TL;DR\n\n箭头函数为用 JavaScript 编写函数提供了一种简洁的语法。它们对于在方法和回调中维护 `this` 上下文特别有用。例如，在事件处理程序或像 `map` 这样的数组方法中，箭头函数可以简化代码并避免 `this` 绑定问题。\n\n```js live\nconst numbers = [1, 2, 3];\nconst doubled = numbers.map((n) => n * 2);\nconsole.log(doubled); // [2, 4, 6]\n```\n\n***\n\n## 新箭头 => 函数语法的用例\n\n### 简化语法\n\n箭头函数提供了一种更简洁的编写函数的方式。这对于短函数或回调特别有用。\n\n```js live\n// Traditional function\nconst add = function (a, b) {\n  return a + b;\n};\n\n// Arrow function\nconst anotherAdd = (a, b) => a + b;\n\nconsole.log(add(2, 3)); // Output: 5\nconsole.log(anotherAdd(2, 3)); // Output: 5\n```\n\n### 词法 `this` 绑定\n\n箭头函数没有自己的 `this` 上下文。相反，它们从周围的范围继承 `this`。这在 `this` 上下文可能很棘手的方法和回调中特别有用。\n\n```js live\nfunction Timer() {\n  this.seconds = 0;\n  this.increment = () => {\n    this.seconds++; // 'this.seconds' is inherited from the outer scope\n    console.log(this.seconds);\n  };\n}\n\nconst timer = new Timer();\ntimer.increment(); // 1\ntimer.increment(); // 2\n```\n\n在上面的例子中，在 `setInterval` 中使用传统函数需要额外的步骤来维护正确的 `this` 上下文。\n\n### 在数组方法中使用箭头函数\n\n箭头函数通常用于 `map`、`filter` 和 `reduce` 等数组方法中，以获得更简洁、更易读的代码。\n\n```js live\nconst numbers = [1, 2, 3, 4, 5];\n\n// Traditional function\nconst doubledTraditional = numbers.map(function (n) {\n  return n * 2;\n});\n\n// Arrow function\nconst doubled = numbers.map((n) => n * 2);\n\nconsole.log(doubled); // [2, 4, 6, 8, 10]\n```\n\n### 事件处理程序\n\n箭头函数可用于事件处理程序，以维护类或对象的 `this` 上下文。\n\n```js live\nclass Button {\n  constructor() {\n    this.count = 0;\n    this.button = document.createElement('button');\n    this.button.innerText = 'Click me';\n    this.button.addEventListener('click', () => {\n      this.count++;\n      console.log('count:', this.count);\n    });\n    document.body.appendChild(this.button);\n  }\n}\n\nconst myButton = new Button();\nmyButton.button.click(); // count: 1\nmyButton.button.click(); // count: 2\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\n* [JavaScript.info: Arrow functions revisited](https://javascript.info/arrow-functions)\n* [Eloquent JavaScript: Functions](https://eloquentjavascript.net/03_functions.html)\n"
  },
  {
    "path": "questions/describe-event-bubbling/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"e76fac09\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"1cdd9fe1\",\n        \"940c1a5e\",\n        \"2a7816d0\",\n        \"8f8a1b0c\",\n        \"72e7e3c9\",\n        \"63bf7424\",\n        \"a71258b2\",\n        \"7009889d\",\n        \"7c18e66f\",\n        \"ae34ee20\",\n        \"e04e0f0f\",\n        \"d186cc4a\",\n        \"a517a702\",\n        \"9e538dcd\",\n        \"3818abba\",\n        \"cd29d4cf\",\n        \"10d6cb7a\",\n        \"1f177e65\",\n        \"d7a0aa2\",\n        \"68b07c90\",\n        \"e2a961ac\",\n        \"c81ac723\",\n        \"965b6bd7\",\n        \"b0d83e27\",\n        \"a8ff50ea\",\n        \"3625d327\",\n        \"ac7b2126\",\n        \"853c279d\",\n        \"b37f85fb\",\n        \"3c0717ad\",\n        \"26112098\",\n        \"2dfccf1a\",\n        \"5a641ee3\",\n        \"647830d7\",\n        \"758c287c\",\n        \"ad083d17\",\n        \"da4b57bd\",\n        \"1f4770e5\",\n        \"d00fe19e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"1cdd9fe1\",\n        \"940c1a5e\",\n        \"2a7816d0\",\n        \"8f8a1b0c\",\n        \"72e7e3c9\",\n        \"63bf7424\",\n        \"a71258b2\",\n        \"7009889d\",\n        \"7c18e66f\",\n        \"ae34ee20\",\n        \"e04e0f0f\",\n        \"d186cc4a\",\n        \"a517a702\",\n        \"9e538dcd\",\n        \"3818abba\",\n        \"cd29d4cf\",\n        \"10d6cb7a\",\n        \"1f177e65\",\n        \"d7a0aa2\",\n        \"68b07c90\",\n        \"e2a961ac\",\n        \"c81ac723\",\n        \"965b6bd7\",\n        \"b0d83e27\",\n        \"a8ff50ea\",\n        \"3625d327\",\n        \"ac7b2126\",\n        \"853c279d\",\n        \"b37f85fb\",\n        \"3c0717ad\",\n        \"26112098\",\n        \"2dfccf1a\",\n        \"5a641ee3\",\n        \"647830d7\",\n        \"758c287c\",\n        \"ad083d17\",\n        \"da4b57bd\",\n        \"1f4770e5\",\n        \"d00fe19e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/describe-event-bubbling/en-US.mdx",
    "content": "---\ntitle: Describe event bubbling in JavaScript and browsers\n---\n\n## TL;DR\n\nEvent bubbling is a DOM event propagation mechanism where an event (e.g. a click), starts at the target element and bubbles up to the root of the document. This allows ancestor elements to also respond to the event.\n\nEvent bubbling is essential for event delegation, where a single event handler manages events for multiple child elements, enhancing performance and code simplicity. While convenient, failing to manage event propagation properly can lead to unintended behavior, such as multiple handlers firing for a single event.\n\n---\n\n## What is event bubbling?\n\nEvent bubbling is a propagation mechanism in the DOM (Document Object Model) where an event, such as a click or a keyboard event, is first triggered on the target element that initiated the event and then propagates upward (bubbles) through the DOM tree to the root of the document.\n\n**Note**: even before the event bubbling phase happens is the [event capturing](/questions/quiz/describe-event-capturing) phase which is the opposite of bubbling where the event goes down from the document root to the target element.\n\n## Bubbling phase\n\nDuring the bubbling phase, the event starts at the target element and bubbles up through its ancestors in the DOM hierarchy. This means that the event handlers attached to the target element and its ancestors can all potentially receive and respond to the event.\n\nHere's an example using modern ES6 syntax to demonstrate event bubbling:\n\n```js live\n// HTML:\n// <div id=\"parent\">\n//   <button id=\"child\">Click me!</button>\n// </div>\nconst parentDiv = document.createElement('div');\nparentDiv.id = 'parent';\nconst button = document.createElement('button');\nbutton.id = 'child';\nparentDiv.appendChild(button);\ndocument.body.appendChild(parentDiv);\n\nconst parent = document.getElementById('parent');\nconst child = document.getElementById('child');\n\nparent.addEventListener('click', () => {\n  console.log('Parent element clicked');\n});\n\nchild.addEventListener('click', () => {\n  console.log('Child element clicked');\n});\n\n// Simulate clicking the button:\nchild.click();\n```\n\nWhen you click the \"Click me!\" button, both the child and parent event handlers will be triggered due to the event bubbling.\n\n## Stopping the bubbling\n\nEvent bubbling can be stopped during the bubbling phase using the `stopPropagation()` method. If an event handler calls `stopPropagation()`, it prevents the event from further bubbling up the DOM tree, ensuring that only the handlers of the elements up to that point in the hierarchy are executed.\n\n```js live\n// HTML:\n// <div id=\"parent\">\n//   <button id=\"child\">Click me!</button>\n// </div>\nconst parentDiv = document.createElement('div');\nparentDiv.id = 'parent';\nconst button = document.createElement('button');\nbutton.id = 'child';\nparentDiv.appendChild(button);\ndocument.body.appendChild(parentDiv);\n\nconst parent = document.getElementById('parent');\nconst child = document.getElementById('child');\n\nparent.addEventListener('click', () => {\n  console.log('Parent element clicked');\n});\n\nchild.addEventListener('click', (event) => {\n  console.log('Child element clicked');\n  event.stopPropagation(); // Stops propagation to parent\n});\n\n// Simulate clicking the button:\nchild.click();\n```\n\n## Event delegation\n\nEvent bubbling is the basis for a technique called [event delegation](/questions/quiz/explain-event-delegation), where you attach a single event handler to a common ancestor of multiple elements and use event delegation to handle events for those elements efficiently. This is particularly useful when you have a large number of similar elements, like a list of items, and you want to avoid attaching individual event handlers to each item.\n\n```js\nparent.addEventListener('click', (event) => {\n  if (event.target && event.target.id === 'child') {\n    console.log('Child element clicked');\n  }\n});\n```\n\n## Benefits\n\n- **Cleaner code:** Reduced number of event listeners improves code readability and maintainability.\n- **Efficient event handling:** Minimizes performance overhead by attaching fewer listeners.\n- **Flexibility:** Allows handling events happening on child elements without directly attaching listeners to them.\n\n## Pitfalls\n\n- **Accidental event handling:** Be mindful that parent elements might unintentionally capture events meant for children. Use `event.target` to identify the specific element that triggered the event.\n- **Event order:** Events bubble up in a specific order. If multiple parents have event listeners, their order of execution depends on the DOM hierarchy.\n- **Over-delegation:** While delegating events to a common ancestor is efficient, attaching a listener too high in the DOM tree might capture unintended events.\n\n## Use cases\n\nHere are some practical ways to use event bubbling to write better code.\n\n### Reducing code with event delegation\n\nImagine you have a product list with numerous items, each with a \"Buy Now\" button. Traditionally, you might attach a separate click event listener to each button:\n\n```js\n// HTML:\n// <ul id=\"product-list\">\n//   <li><button id=\"item1-buy\">Buy Now</button></li>\n//   <li><button id=\"item2-buy\">Buy Now</button></li>\n// </ul>\n\nconst item1Buy = document.getElementById('item1-buy');\nconst item2Buy = document.getElementById('item2-buy');\n\nitem1Buy.addEventListener('click', handleBuyClick);\nitem2Buy.addEventListener('click', handleBuyClick);\n\n// ... repeat for each item ...\n\nfunction handleBuyClick(event) {\n  console.log('Buy button clicked for item:', event.target.id);\n}\n```\n\nThis approach becomes cumbersome as the number of items grows. Here's how event bubbling can simplify things:\n\n```js\n// HTML:\n// <ul id=\"product-list\">\n//   <li><button id=\"item1-buy\">Buy Now</button></li>\n//   <li><button id=\"item2-buy\">Buy Now</button></li>\n// </ul>\n\nconst productList = document.getElementById('product-list');\n\nproductList.addEventListener('click', handleBuyClick);\n\nfunction handleBuyClick(event) {\n  // Check if the clicked element is a button within the list\n  if (event.target.tagName.toLowerCase() === 'button') {\n    console.log('Buy button clicked for item:', event.target.id);\n  }\n}\n```\n\nBy attaching the listener to the parent (`productList`) and checking the clicked element (`event.target`) within the handler, you achieve the same functionality with less code. This approach scales well when the items are dynamic as no new event handlers have to be added or removed when the list of items change.\n\n### Dropdown menus\n\nConsider a dropdown menu where clicking anywhere on the menu element (parent) should close it. With event bubbling, you can achieve this with a single listener:\n\n```js\n// HTML:\n// <div id=\"dropdown\">\n//   <button>Open Menu</button>\n//   <ul>\n//     <li>Item 1</li>\n//     <li>Item 2</li>\n//   </ul>\n// </div>\n\nconst dropdown = document.getElementById('dropdown');\n\ndropdown.addEventListener('click', handleDropdownClick);\n\nfunction handleDropdownClick(event) {\n  // Close the dropdown if clicked outside the button\n  if (event.target !== dropdown.querySelector('button')) {\n    console.log('Dropdown closed');\n    // Your logic to hide the dropdown content\n  }\n}\n```\n\nHere, the click event bubbles up from the clicked element (button or list item) to the `dropdown` element. The handler checks if the clicked element is not the `<button>` and closes the menu accordingly.\n\n### Accordion menus\n\nImagine an accordion menu where clicking a section header (parent) expands or collapses the content section (child) below it. Event bubbling makes this straightforward:\n\n```js\n// HTML:\n// <div class=\"accordion\">\n//   <div class=\"header\">Section 1</div>\n//   <div class=\"content\">Content for Section 1</div>\n//   <div class=\"header\">Section 2</div>\n//   <div class=\"content\">Content for Section 2</div>\n// </div>\n\nconst accordion = document.querySelector('.accordion');\n\naccordion.addEventListener('click', handleAccordionClick);\n\nfunction handleAccordionClick(event) {\n  // Check if clicked element is a header\n  if (event.target.classList.contains('header')) {\n    const content = event.target.nextElementSibling;\n    content.classList.toggle('active'); // Toggle display of content\n  }\n}\n```\n\nBy attaching the listener to the `accordion` element, clicking on any header triggers the event. The handler checks if the clicked element is a header and toggles the visibility of the corresponding content section.\n\n## Further reading\n\n- [MDN Web Docs on Event Bubbling](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling)\n- [JavaScript.info - Bubbling and Capturing](https://javascript.info/bubbling-and-capturing)\n- [W3C DOM Level 3 Events Specification](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)\n"
  },
  {
    "path": "questions/describe-event-bubbling/metadata.json",
    "content": "{\n  \"slug\": \"describe-event-bubbling\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 210,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/describe-event-bubbling/pt-BR.mdx",
    "content": "---\ntitle: Descreva a propagação de eventos\n---\n\nA propagação de eventos é um mecanismo na DOM (Modelo de Objetos do Documento) em que um evento, como um clique ou um evento de teclado, é primeiro acionado no elemento de destino que iniciou o evento e, em seguida, se propaga para cima (bolhas) pela árvore da DOM até a raiz do documento.\n\n## Fase de bolha\n\nDurante a fase de bolha, o evento começa no elemento de destino e se propaga pelos seus ancestrais na hierarquia da DOM. Isso significa que os manipuladores de eventos associados ao elemento de destino e aos seus ancestrais podem potencialmente receber e responder ao evento.\n\nAqui está um exemplo usando a sintaxe moderna do ES6 para demonstrar a propagação de eventos:\n\n```js\n// HTML:\n// <div id=\"pai\">\n//   <button id=\"filho\">Clique em mim!</button>\n// </div>\n\nconst pai = document.getElementById('pai');\nconst filho = document.getElementById('filho');\n\npai.addEventListener('click', () => {\n  console.log('Cliquei no elemento pai');\n});\n\nfilho.addEventListener('click', () => {\n  console.log('Cliquei no elemento filho');\n});\n```\n\nQuando você clica no botão \"Clique em mim!\", devido à propagação de eventos, os manipuladores de eventos do filho e do pai serão acionados.\n\n## Parando a propagação\n\nA propagação de eventos pode ser interrompida durante a fase de bolha usando o método `stopPropagation()`. Se um manipulador de eventos chamar `stopPropagation()`, ele impedirá que o evento continue a se propagar pela árvore da DOM, garantindo que apenas os manipuladores dos elementos até aquele ponto na hierarquia sejam executados.\n\n## Delegação de eventos\n\nA propagação de eventos é a base para uma técnica chamada \"delegação de eventos\", onde você anexa um único manipulador de eventos a um ancestral comum de vários elementos e usa a delegação de eventos para lidar eficientemente com os eventos desses elementos. Isso é particularmente útil quando você tem um grande número de elementos semelhantes, como uma lista de itens, e deseja evitar a adição de manipuladores de eventos individuais a cada item.\n\n## Referências\n\n- [MDN Web Docs sobre Propagação de Eventos](https://developer.mozilla.org/pt-BR/docs/Web/API/Event/stopPropagation)\n- [JavaScript.info - Bolhas e Captura](https://javascript.info/bubbling-and-capturing)\n- [Especificação de Eventos do W3C DOM Nível 3](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)\n"
  },
  {
    "path": "questions/describe-event-bubbling/zh-CN.mdx",
    "content": "---\ntitle: 描述 JavaScript 和浏览器的事件冒泡\n---\n\n## TL;DR\n\n事件冒泡是一种 DOM 事件传播机制，其中一个事件（例如点击）从目标元素开始，冒泡到文档的根。这允许祖先元素也响应事件。\n\n事件冒泡对于事件委托至关重要，其中单个事件处理程序管理多个子元素的事件，从而提高性能和代码简洁性。虽然方便，但未能正确管理事件传播可能导致意外行为，例如多个处理程序为单个事件触发。\n\n***\n\n## 什么是事件冒泡？\n\n事件冒泡是 DOM（文档对象模型）中的一种传播机制，其中一个事件（例如点击或键盘事件）首先在触发事件的目标元素上触发，然后向上（冒泡）通过 DOM 树传播到文档的根。\n\n**注意**：甚至在事件冒泡阶段发生之前是 [事件捕获](/questions/quiz/describe-event-capturing) 阶段，该阶段与冒泡相反，事件从文档根向下到目标元素。\n\n## 冒泡阶段\n\n在冒泡阶段，事件从目标元素开始，通过其在 DOM 层次结构中的祖先元素冒泡。这意味着附加到目标元素及其祖先的事件处理程序都可能接收并响应事件。\n\n这里有一个使用现代 ES6 语法的示例，用于演示事件冒泡：\n\n```js live\n// HTML:\n// <div id=\"parent\">\n//   <button id=\"child\">Click me!</button>\n// </div>\nconst parentDiv = document.createElement('div');\nparentDiv.id = 'parent';\nconst button = document.createElement('button');\nbutton.id = 'child';\nparentDiv.appendChild(button);\ndocument.body.appendChild(parentDiv);\n\nconst parent = document.getElementById('parent');\nconst child = document.getElementById('child');\n\nparent.addEventListener('click', () => {\n  console.log('Parent element clicked');\n});\n\nchild.addEventListener('click', () => {\n  console.log('Child element clicked');\n});\n\n// Simulate clicking the button:\nchild.click();\n```\n\n当您点击“Click me!”按钮时，由于事件冒泡，子元素和父元素的事件处理程序都将被触发。\n\n## 停止冒泡\n\n可以使用 `stopPropagation()` 方法在冒泡阶段停止事件冒泡。如果事件处理程序调用 `stopPropagation()`，它会阻止事件进一步冒泡到 DOM 树中，确保仅执行层次结构中该点之前的元素的处理程序。\n\n```js live\n// HTML:\n// <div id=\"parent\">\n//   <button id=\"child\">Click me!</button>\n// </div>\nconst parentDiv = document.createElement('div');\nparentDiv.id = 'parent';\nconst button = document.createElement('button');\nbutton.id = 'child';\nparentDiv.appendChild(button);\ndocument.body.appendChild(parentDiv);\n\nconst parent = document.getElementById('parent');\nconst child = document.getElementById('child');\n\nparent.addEventListener('click', () => {\n  console.log('Parent element clicked');\n});\n\nchild.addEventListener('click', (event) => {\n  console.log('Child element clicked');\n  event.stopPropagation(); // Stops propagation to parent\n});\n\n// Simulate clicking the button:\nchild.click();\n```\n\n## 事件委托\n\n事件冒泡是[事件委托](/questions/quiz/explain-event-delegation)技术的基础，您可以在多个元素的公共祖先上附加单个事件处理程序，并使用事件委托来有效地处理这些元素的事件。当您有大量相似的元素（如项目列表）并且希望避免将单独的事件处理程序附加到每个项目时，这特别有用。\n\n```js\nparent.addEventListener('click', (event) => {\n  if (event.target && event.target.id === 'child') {\n    console.log('Child element clicked');\n  }\n});\n```\n\n## 优点\n\n* **更简洁的代码：** 减少事件监听器的数量，提高代码可读性和可维护性。\n* **高效的事件处理：** 通过附加更少的监听器，最大限度地减少性能开销。\n* **灵活性：** 允许处理子元素上发生的事件，而无需直接将监听器附加到它们。\n\n## 陷阱\n\n* **意外的事件处理：** 请注意，父元素可能会无意中捕获子元素发生的事件。使用 `event.target` 来识别触发事件的特定元素。\n* **事件顺序：** 事件以特定顺序冒泡。如果多个父元素有事件监听器，它们的执行顺序取决于 DOM 层次结构。\n* **过度委托：** 虽然将事件委托给公共祖先是有效的，但在 DOM 树中附加一个过高的监听器可能会捕获意外的事件。\n\n## 用例\n\n以下是一些使用事件冒泡编写更好代码的实用方法。\n\n### 使用事件委托减少代码\n\n想象一下，您有一个产品列表，其中包含许多项目，每个项目都有一个“立即购买”按钮。 传统上，您可以将单独的点击事件监听器附加到每个按钮：\n\n```js\n// HTML:\n// <ul id=\"product-list\">\n//   <li><button id=\"item1-buy\">立即购买</button></li>\n//   <li><button id=\"item2-buy\">立即购买</button></li>\n// </ul>\n\nconst item1Buy = document.getElementById('item1-buy');\nconst item2Buy = document.getElementById('item2-buy');\n\nitem1Buy.addEventListener('click', handleBuyClick);\nitem2Buy.addEventListener('click', handleBuyClick);\n\n// ... 对每个项目重复 ...\n\nfunction handleBuyClick(event) {\n  console.log('点击了项目的购买按钮：', event.target.id);\n}\n```\n\n随着项目数量的增加，这种方法变得很麻烦。 以下是事件冒泡如何简化事情的方法：\n\n```js\n// HTML:\n// <ul id=\"product-list\">\n//   <li><button id=\"item1-buy\">Buy Now</button></li>\n//   <li><button id=\"item2-buy\">Buy Now</button></li>\n// </ul>\n\nconst productList = document.getElementById('product-list');\n\nproductList.addEventListener('click', handleBuyClick);\n\nfunction handleBuyClick(event) {\n  // Check if the clicked element is a button within the list\n  if (event.target.tagName.toLowerCase() === 'button') {\n    console.log('Buy button clicked for item:', event.target.id);\n  }\n}\n```\n\n通过将监听器附加到父元素 (`productList`) 并在处理程序中检查被点击的元素 (`event.target`)，您可以用更少的代码实现相同的功能。 当项目是动态的时，这种方法可以很好地扩展，因为当项目列表发生变化时，不需要添加或删除新的事件处理程序。\n\n### 下拉菜单\n\n考虑一个下拉菜单，点击菜单元素（父元素）的任何地方都应该关闭它。使用事件冒泡，您可以使用一个监听器来实现这一点：\n\n```js\n// HTML:\n// <div id=\"dropdown\">\n//   <button>打开菜单</button>\n//   <ul>\n//     <li>项目 1</li>\n//     <li>项目 2</li>\n//   </ul>\n// </div>\n\nconst dropdown = document.getElementById('dropdown');\n\ndropdown.addEventListener('click', handleDropdownClick);\n\nfunction handleDropdownClick(event) {\n  // 如果在按钮外部单击，则关闭下拉菜单\n  if (event.target !== dropdown.querySelector('button')) {\n    console.log('下拉菜单已关闭');\n    // 隐藏下拉菜单内容的逻辑\n  }\n}\n```\n\n在这里，点击事件从被点击的元素（按钮或列表项）冒泡到 `dropdown` 元素。 处理程序检查被点击的元素是否不是 `<button>`，并相应地关闭菜单。\n\n### 手风琴菜单\n\n想象一个手风琴菜单，点击一个部分标题（父级）会展开或折叠其下方的部分内容（子级）。 事件冒泡使这变得简单：\n\n```js\n// HTML:\n// <div class=\"accordion\">\n//   <div class=\"header\">第 1 节</div>\n//   <div class=\"content\">第 1 节的内容</div>\n//   <div class=\"header\">第 2 节</div>\n//   <div class=\"content\">第 2 节的内容</div>\n// </div>\n\nconst accordion = document.querySelector('.accordion');\n\naccordion.addEventListener('click', handleAccordionClick);\n\nfunction handleAccordionClick(event) {\n  // 检查点击的元素是否是标题\n  if (event.target.classList.contains('header')) {\n    const content = event.target.nextElementSibling;\n    content.classList.toggle('active'); // 切换内容的显示\n  }\n}\n```\n\n通过将监听器附加到 `accordion` 元素，单击任何标题都会触发该事件。 处理程序检查被点击的元素是否是标题，并切换相应内容部分的可见性。\n\n## 延伸阅读\n\n* [MDN Web Docs on Event Bubbling](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling)\n* [JavaScript.info - Bubbling and Capturing](https://javascript.info/bubbling-and-capturing)\n* [W3C DOM Level 3 Events Specification](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)\n"
  },
  {
    "path": "questions/describe-event-capturing/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"b0183641\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"2dbbafe4\",\n        \"58d82875\",\n        \"2a7816d0\",\n        \"4a46b75a\",\n        \"ac6b91fb\",\n        \"ebfdcf8e\",\n        \"3285d324\",\n        \"947f1c67\",\n        \"f2557d8b\",\n        \"b391e542\",\n        \"5089e2e8\",\n        \"571f9b6a\",\n        \"28762f9d\",\n        \"37ab3c2f\",\n        \"9d56c158\",\n        \"7b811adc\",\n        \"440e1878\",\n        \"59c63cca\",\n        \"e96a802a\",\n        \"e300e4d1\",\n        \"1f4770e5\",\n        \"7aa67f80\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"2dbbafe4\",\n        \"58d82875\",\n        \"2a7816d0\",\n        \"4a46b75a\",\n        \"ac6b91fb\",\n        \"ebfdcf8e\",\n        \"3285d324\",\n        \"947f1c67\",\n        \"f2557d8b\",\n        \"b391e542\",\n        \"5089e2e8\",\n        \"571f9b6a\",\n        \"28762f9d\",\n        \"37ab3c2f\",\n        \"9d56c158\",\n        \"7b811adc\",\n        \"440e1878\",\n        \"59c63cca\",\n        \"e96a802a\",\n        \"e300e4d1\",\n        \"1f4770e5\",\n        \"7aa67f80\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/describe-event-capturing/en-US.mdx",
    "content": "---\ntitle: Describe event capturing in JavaScript and browsers\n---\n\n## TL;DR\n\nEvent capturing is a lesser-used counterpart to [event bubbling](/questions/quiz/describe-event-bubbling) in the DOM event propagation mechanism. It follows the opposite order, where an event triggers first on the ancestor element and then travels down to the target element.\n\nEvent capturing is rarely used as compared to event bubbling, but it can be used in specific scenarios where you need to intercept events at a higher level before they reach the target element. It is disabled by default but can be enabled through an option on `addEventListener()`.\n\n---\n\n## What is event capturing?\n\nEvent capturing is a propagation mechanism in the DOM (Document Object Model) where an event, such as a click or a keyboard event, is first triggered at the root of the document and then flows down through the DOM tree to the target element.\n\nCapturing has a higher priority than bubbling, meaning that capturing event handlers are executed before bubbling event handlers, as shown by the phases of event propagation:\n\n- **Capturing phase**: The event moves down towards the target element\n- **Target phase**: The event reaches the target element\n- **Bubbling phase**: The event bubbles up from the target element\n\nNote that event capturing is disabled by default. To enable it you have to pass the capture option into `addEventListener()`.\n\n## Capturing phase\n\nDuring the capturing phase, the event starts at the document root and propagates down to the target element. Any event listeners on ancestor elements in this path will be triggered before the target element's handler. But note that event capturing can't happen until the third argument of `addEventListener()` is set to `true` as shown below (default value is `false`).\n\nHere's an example using modern ES2015 syntax to demonstrate event capturing:\n\n```js\n// HTML:\n// <div id=\"parent\">\n//   <button id=\"child\">Click me!</button>\n// </div>\n\nconst parent = document.getElementById('parent');\nconst child = document.getElementById('child');\n\nparent.addEventListener(\n  'click',\n  () => {\n    console.log('Parent element clicked (capturing)');\n  },\n  true, // Set third argument to true for capturing\n);\n\nchild.addEventListener('click', () => {\n  console.log('Child element clicked');\n});\n```\n\nWhen you click the \"Click me!\" button, it will trigger the parent element's capturing handler first, followed by the child element's handler.\n\n## Stopping propagation\n\nEvent propagation can be stopped during the capturing phase using the `stopPropagation()` method. This prevents the event from traveling further down the DOM tree.\n\n```js\n// HTML:\n// <div id=\"parent\">\n//   <button id=\"child\">Click me!</button>\n// </div>\n\nconst parent = document.getElementById('parent');\nconst child = document.getElementById('child');\n\nparent.addEventListener(\n  'click',\n  (event) => {\n    console.log('Parent element clicked (capturing)');\n    event.stopPropagation(); // Stop event propagation\n  },\n  true,\n);\n\nchild.addEventListener('click', () => {\n  console.log('Child element clicked');\n});\n```\n\nAs a result of stopping event propagation, just the `parent` event listener will now be called when you click the \"Click Me!\" button, and the `child` event listener will never be called because the event propagation has stopped at the `parent` element.\n\n## Uses of event capturing\n\nEvent capturing is rarely used as compared to event bubbling, but it can be used in specific scenarios where you need to intercept events at a higher level before they reach the target element.\n\n- **Stopping event bubbling:** Imagine you have a nested element (like a button) inside a container element. Clicking the button might also trigger a click event on the container. By enabling event capturing on the container's event listener, you can capture the click event there and prevent it from traveling down to the button, potentially causing unintended behavior.\n- **Custom dropdown menus:**: When building custom dropdown menus, you might want to capture clicks outside the menu element to close the menu. Using `capture: true` on the `document` object allows you to listen for clicks anywhere on the page and close the menu if the click happens outside its boundaries.\n- **Efficiency in certain scenarios:**: In some situations, event capturing can be slightly more efficient than relying on bubbling. This is because the event doesn't need to propagate through all child elements before reaching the handler. However, the performance difference is usually negligible for most web applications.\n\n## Further reading\n\n- [Event Capturing | MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_capture)\n- [Bubbling and Capturing | JavaScript.info](https://javascript.info/bubbling-and-capturing)\n- [W3C DOM Level 3 Events Specification](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)\n"
  },
  {
    "path": "questions/describe-event-capturing/metadata.json",
    "content": "{\n  \"slug\": \"describe-event-capturing\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 220,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/describe-event-capturing/zh-CN.mdx",
    "content": "---\ntitle: 描述 JavaScript 和浏览器中的事件捕获\n---\n\n## TL;DR\n\n事件捕获是 DOM 事件传播机制中较少使用的 [事件冒泡](/questions/quiz/describe-event-bubbling) 的对应部分。它遵循相反的顺序，事件首先在祖先元素上触发，然后向下传递到目标元素。\n\n与事件冒泡相比，事件捕获很少使用，但它可用于特定场景，例如需要在事件到达目标元素之前拦截更高级别的事件。默认情况下，它是禁用的，但可以通过 `addEventListener()` 上的一个选项来启用。\n\n***\n\n## 什么是事件捕获？\n\n事件捕获是 DOM（文档对象模型）中的一种传播机制，其中事件（例如单击或键盘事件）首先在文档的根处触发，然后通过 DOM 树向下流向目标元素。\n\n捕获的优先级高于冒泡，这意味着捕获事件处理程序在冒泡事件处理程序之前执行，如事件传播的各个阶段所示：\n\n* **捕获阶段**：事件向下移动到目标元素\n* **目标阶段**：事件到达目标元素\n* **冒泡阶段**：事件从目标元素冒泡\n\n请注意，默认情况下禁用事件捕获。要启用它，您必须将捕获选项传递到 `addEventListener()`。\n\n## 捕获阶段\n\n在捕获阶段，事件从文档根开始并向下传播到目标元素。此路径上任何祖先元素上的任何事件侦听器都将在目标元素的处理程序之前触发。但请注意，除非将 `addEventListener()` 的第三个参数设置为 `true`，否则事件捕获不会发生，如下所示（默认值为 `false`）。\n\n以下是使用现代 ES2015 语法的示例，用于演示事件捕获：\n\n```js\n// HTML:\n// <div id=\"parent\">\n//   <button id=\"child\">Click me!</button>\n// </div>\n\nconst parent = document.getElementById('parent');\nconst child = document.getElementById('child');\n\nparent.addEventListener(\n  'click',\n  () => {\n    console.log('Parent element clicked (capturing)');\n  },\n  true, // Set third argument to true for capturing\n);\n\nchild.addEventListener('click', () => {\n  console.log('Child element clicked');\n});\n```\n\n当您单击“Click me!”按钮时，它将首先触发父元素的捕获处理程序，然后触发子元素的处理程序。\n\n## 停止传播\n\n可以使用 `stopPropagation()` 方法在捕获阶段停止事件传播。这可以防止事件进一步向下传递 DOM 树。\n\n```js\n// HTML:\n// <div id=\"parent\">\n//   <button id=\"child\">Click me!</button>\n// </div>\n\nconst parent = document.getElementById('parent');\nconst child = document.getElementById('child');\n\nparent.addEventListener(\n  'click',\n  (event) => {\n    console.log('Parent element clicked (capturing)');\n    event.stopPropagation(); // Stop event propagation\n  },\n  true,\n);\n\nchild.addEventListener('click', () => {\n  console.log('Child element clicked');\n});\n```\n\n由于停止了事件传播，当您单击“Click Me!”按钮时，现在将仅调用 `parent` 事件侦听器，并且永远不会调用 `child` 事件侦听器，因为事件传播已在 `parent` 元素处停止。\n\n## 事件捕获的用途\n\n与事件冒泡相比，事件捕获很少使用，但它可以在特定情况下使用，例如需要在事件到达目标元素之前在高层拦截事件。\n\n* **阻止事件冒泡：** 想象一下，您有一个嵌套元素（如按钮）位于容器元素内。单击该按钮也可能触发容器上的单击事件。通过在容器的事件侦听器上启用事件捕获，您可以在那里捕获单击事件，并阻止其向下传播到按钮，从而可能导致意外行为。\n* **自定义下拉菜单：** 在构建自定义下拉菜单时，您可能希望捕获菜单元素之外的点击以关闭菜单。在 `document` 对象上使用 `capture: true` 允许您侦听页面上的任何位置的点击，并在点击发生在菜单边界之外时关闭菜单。\n* **在某些情况下提高效率：** 在某些情况下，事件捕获可能比依赖冒泡更有效。这是因为事件不需要在到达处理程序之前通过所有子元素传播。但是，对于大多数 Web 应用程序来说，性能差异通常可以忽略不计。\n\n## 延伸阅读\n\n* [事件捕获 | MDN](https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Building_blocks/Events#event_capture)\n* [冒泡和捕获 | JavaScript.info](https://zh.javascript.info/bubbling-and-capturing)\n* [W3C DOM Level 3 事件规范](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)\n"
  },
  {
    "path": "questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"cd74bf50\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"2133a8df\",\n        \"b3cb0b4e\",\n        \"67d43f33\",\n        \"d3702ac3\",\n        \"2a7816d0\",\n        \"42be5204\",\n        \"56f591d9\",\n        \"29d2bdb5\",\n        \"3e6fef3e\",\n        \"5775ff1b\",\n        \"8f3fb45c\",\n        \"63b5f704\",\n        \"6108b198\",\n        \"480fe8f4\",\n        \"bacd445e\",\n        \"b8c8cecb\",\n        \"58df7471\",\n        \"a8bf2799\",\n        \"2d2cfe6d\",\n        \"a812e0c\",\n        \"daa22c54\",\n        \"ecb36fec\",\n        \"722f87c0\",\n        \"dfbcf26f\",\n        \"247aee\",\n        \"bdc995c7\",\n        \"6f00d300\",\n        \"a69065a3\",\n        \"93d07e2c\",\n        \"34e87c45\",\n        \"c5a208c4\",\n        \"add698fb\",\n        \"ae632d35\",\n        \"62fd75b6\",\n        \"599beffc\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"2133a8df\",\n        \"b3cb0b4e\",\n        \"67d43f33\",\n        \"d3702ac3\",\n        \"2a7816d0\",\n        \"42be5204\",\n        \"56f591d9\",\n        \"29d2bdb5\",\n        \"3e6fef3e\",\n        \"5775ff1b\",\n        \"8f3fb45c\",\n        \"63b5f704\",\n        \"6108b198\",\n        \"480fe8f4\",\n        \"bacd445e\",\n        \"b8c8cecb\",\n        \"58df7471\",\n        \"a8bf2799\",\n        \"2d2cfe6d\",\n        \"a812e0c\",\n        \"daa22c54\",\n        \"ecb36fec\",\n        \"722f87c0\",\n        \"dfbcf26f\",\n        \"247aee\",\n        \"bdc995c7\",\n        \"6f00d300\",\n        \"a69065a3\",\n        \"93d07e2c\",\n        \"34e87c45\",\n        \"c5a208c4\",\n        \"add698fb\",\n        \"ae632d35\",\n        \"62fd75b6\",\n        \"599beffc\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/en-US.mdx",
    "content": "---\ntitle: Describe the difference between a cookie, `sessionStorage` and `localStorage` in browsers\n---\n\n## TL;DR\n\nAll of the following are mechanisms of storing data on the client, the user's browser in this case. `localStorage` and `sessionStorage` both implement the [Web Storage API interface](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API).\n\n- **Cookies**: Suitable for server-client communication, small storage capacity, can be persistent or session-based, domain-specific. Sent to the server on every request.\n- **`localStorage`**: Suitable for long-term storage, data persists even after the browser is closed, accessible across all tabs and windows of the same origin, highest storage capacity among the three.\n- **`sessionStorage`**: Suitable for temporary data within a single page session, data is cleared when the tab or window is closed, has a higher storage capacity compared to cookies.\n\nHere's a table summarizing the 3 client storage mechanisms.\n\n| Property | Cookie | `localStorage` | `sessionStorage` |\n| --- | --- | --- | --- |\n| Initiator | Client or server. Server can use `Set-Cookie` header | Client | Client |\n| Lifespan | As specified | Until deleted | Until tab is closed |\n| Persistent across browser sessions | If a future expiry date is set | Yes | No |\n| Sent to server with every HTTP request | Yes, sent via `Cookie` header | No | No |\n| Total capacity (per domain) | 4kb | 5MB | 5MB |\n| Access | Across windows/tabs | Across windows/tabs | Same tab |\n| Security | JavaScript cannot access `HttpOnly` cookies | None | None |\n\n---\n\n## Storage on the web\n\nCookies, `localStorage`, and `sessionStorage`, are all storage mechanisms on the client (web browser). It is useful to store data on the client for client-only state like access tokens, themes, personalized layouts, so that users can have a consistent experience on a website across tabs and usage sessions.\n\nThese client-side storage mechanisms have the following common properties:\n\n- This means the clients can read and modify the values (except for `HttpOnly` cookies).\n- Key-value based storage.\n- They are only able to store values as strings. Non-strings will have to be serialized into a string (e.g. `JSON.stringify()`) in order to be stored.\n\n### Use cases for each storage mechanism\n\nSince cookies have a relatively low maximum size, it is not advisable to store all your client-side data within cookies. The distinguishing properties about cookies are that cookies are sent to the server on every HTTP request so the low maximum size is a feature that prevents your HTTP requests from being too large due to cookies. Automatic expiry of cookies is a useful feature as well.\n\nWith that in mind, the best kind of data to store within cookies is small pieces of data that needs to be transmitted to the server, such as auth tokens, session IDs, analytics tracking IDs, GDPR cookie consent, language preferences that are important for authentication, authorization, and rendering on the server. These values are sometimes sensitive and can benefit from the `HttpOnly`, `Secure`, and `Expires`/`Max-Age` capabilities that cookies provide.\n\n`localStorage` and `sessionStorage` both implement the [Web Storage API interface](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API). Web Storages have a generous total capacity of 5MB, so storage size is usually not a concern. The key difference is that values stored in Web Storage are not automatically sent along HTTP requests.\n\nWhile you can manually include values from Web Storage when making AJAX/`fetch()` requests, the browser does not include them in the initial request / first load of the page. Hence Web Storage should not be used to store data that is relied on by the server for the initial rendering of the page if server-side rendering is being used (typically authentication/authorization-related information). `localStorage` is most suitable for user preferences data that do not expire, like themes and layouts (if it is not important for the server to render the final layout). `sessionStorage` is most suitable for temporary data that only needs to be accessible within the current browsing session, such as form data (useful to preserve data during accidental reloads).\n\nThe following sections dive deeper into each client storage mechanism.\n\n### Cookies\n\nCookies are used to store small pieces of data on the client side that can be sent back to the server with every HTTP request.\n\n- **Storage capacity**: Limited to around 4KB for all cookies.\n- **Lifespan**: Cookies can have a specific expiration date set using the `Expires` or `Max-Age` attributes. If no expiration date is set, the cookie is deleted when the browser is closed (session cookie).\n- **Access**: Cookies are domain-specific and can be shared across different pages and subdomains within the same domain.\n- **Security**: Cookies can be marked as `HttpOnly` to prevent access from JavaScript, reducing the risk of XSS attacks. They can also be secured with the `Secure` flag to ensure they are sent only when HTTPS is used.\n\n```js\n// Set a cookie for the name/key `auth_token` with an expiry.\ndocument.cookie =\n  'auth_token=abc123def; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/';\n\n// Read all cookies. There's no way to read specific cookies using `document.cookie`.\n// You have to parse the string yourself.\nconsole.log(document.cookie); // auth_token=abc123def\n\n// Delete the cookie with the name/key `auth_token` by setting an\n// expiry date in the past. The value doesn't matter.\ndocument.cookie = 'auth_token=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';\n```\n\nIt is a pain to read/write to cookies. `document.cookie` returns a single string containing all the key/value pairs delimited by `;` and you have to parse the string yourself. The [`js-cookie`](https://github.com/js-cookie/js-cookie) npm library provides a simple and lightweight API for reading/writing cookies in JavaScript.\n\nA modern native way of accessing cookies is via the [Cookie Store API](https://developer.mozilla.org/en-US/docs/Web/API/Cookie_Store_API) which is only available on HTTPS pages.\n\n```js\n// Set a cookie. More options are available too.\ncookieStore.set('auth_token', 'abc123def');\n\n// Async method to access a single cookie and do something with it.\ncookieStore.get('auth_token').then(...);\n\n// Async method to get all cookies.\ncookieStore.getAll().then(...);\n\n// Async method to delete a single cookie.\ncookieStore.delete('auth_token').then(() =>\n  console.log('Cookie deleted')\n);\n```\n\nThe CookieStore API is relatively new and may not be supported in all browsers (supported in latest Chrome and Edge as of June 2024). Refer to [caniuse.com](https://caniuse.com/mdn-api_cookiestore) for the latest compatibility.\n\n### `localStorage`\n\n`localStorage` is used for storing data that persists even after the browser is closed and reopened. It is designed for long-term storage of data.\n\n- **Storage capacity**: Typically around 5MB per origin (varies by browser).\n- **Lifespan**: Data in `localStorage` persists until explicitly deleted by the user or the application.\n- **Access**: Data is accessible within all tabs and windows of the same origin.\n- **Security**: All JavaScript on the page have access to values within `localStorage`.\n\n```js\n// Set a value in localStorage.\nlocalStorage.setItem('key', 'value');\n\n// Get a value from localStorage.\nconsole.log(localStorage.getItem('key'));\n\n// Remove a value from localStorage.\nlocalStorage.removeItem('key');\n\n// Clear all data in localStorage.\nlocalStorage.clear();\n```\n\n### `sessionStorage`\n\n`sessionStorage` is used to store data for the duration of the page session. It is designed for temporary storage of data.\n\n- **Storage Capacity**: Typically around 5MB per origin (varies by browser).\n- **Lifespan**: Data in `sessionStorage` is cleared when the page session ends (i.e., when the browser or tab is closed). Reloading the page does not destroy data within `sessionStorage`.\n- **Access**: Data is accessible only within the current tab (or browsing context). Different tabs share different `sessionStorage` objects even if they belong to the same browser window. In this context, window refers to a browser window that can contain multiple tabs.\n- **Security**: All JavaScript on the same page have access to values within `sessionStorage` for that page.\n\n```js\n// Set a value in sessionStorage.\nsessionStorage.setItem('key', 'value');\n\n// Get a value from sessionStorage.\nconsole.log(sessionStorage.getItem('key'));\n\n// Remove a value from sessionStorage.\nsessionStorage.removeItem('key');\n\n// Clear all data in sessionStorage.\nsessionStorage.clear();\n```\n\n## Notes\n\nThere are also other client-side storage mechanisms like [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) which is more powerful than the above-mentioned technologies but more complicated to use.\n\n## References\n\n- [What is the difference between localStorage, sessionStorage, session and cookies?](https://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookies)\n"
  },
  {
    "path": "questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/metadata.json",
    "content": "{\n  \"slug\": \"describe-the-difference-between-a-cookie-sessionstorage-and-localstorage\",\n  \"languages\": [],\n  \"companies\": [\"amazon\", \"bytedance\", \"tiktok\", \"apple\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 70,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/pt-BR.mdx",
    "content": "---\ntitle: Descreva a diferença entre cookie, `sessionStorage` e `localStorage`.\n---\n\nLocal storage is useful for storing data that the user will need to access later, such as offline data, because it stores the data in the browser and the system. This data will persist even if the user closes and reopens the browser and is accessible by other sites.\n\nSession storage is a great way to improve the performance of your web applications. It stores data locally on the browser but is specific to (and only accessible by) the respective site/browser tab and is only available while the user is on the site/tab. This is a more secure storage method due to the restrictive access and promotes better site performance due to reduced data transfer between server and client.\n\nCookies are a good choice for storing data that should not be persisted for a long time, such as session IDs. Cookies allow you to set an expiry time at which point it would be deleted. Cookies can only be smaller sized data compared to the other two storage methods.\n\n## Similaridades\n\nCookies, `localStorage`, and `sessionStorage`, são todos:\n\n- Mecanismos de armazenamento no lado do cliente. Isso significa que os clientes podem ler e modificar os valores.\n- Armazenamento baseado em chave-valor.\n- Eles só são capazes de armazenar valores como strings. Objetos terão que ser serializados em uma string (`JSON.stringify()`) a fim de serem armazenados.\n\n## Diferenças\n\n| Propriedade | Cookie | `localStorage` | `sessionStorage` |\n| --- | --- | --- | --- |\n| Iniciador | Cliente ou servidor. O servidor pode usar o cabeçalho `Set-Cookie` | Cliente | Cliente |\n| Vencimento | Definir manualmente | Para sempre | Ao fechar a aba |\n| Persistente através de sessões do navegador | Depende se a expiração está definida | Sim | Não |\n| Enviado para o servidor com cada solicitação HTTP | Os cookies são automaticamente enviados via cabeçalho `Cookie` | Não | Não |\n| Capacidade (por domínio) | 4kb | 5MB | 5MB |\n| Acesso | Quqlquer Janela | Quqlquer Janela | Mesma Guia |\n\nTambém existem outros mecanismos de armazenamento do lado do cliente, como [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) que é mais poderoso do que as tecnologias acima mencionadas, mas mais complicado de usar.\n"
  },
  {
    "path": "questions/describe-the-difference-between-a-cookie-sessionstorage-and-localstorage/zh-CN.mdx",
    "content": "---\ntitle: 描述浏览器中 cookie、`sessionStorage` 和 `localStorage` 之间的区别\n---\n\n## 总结\n\n以下都是在客户端（本例中为用户的浏览器）上存储数据的机制。`localStorage` 和 `sessionStorage` 都实现了 [Web Storage API 接口](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API)。\n\n* **Cookies**：适用于服务器-客户端通信，存储容量小，可以是持久性的或基于会话的，特定于域。在每次请求时发送到服务器。\n* **`localStorage`**：适用于长期存储，即使在浏览器关闭后数据仍然存在，可在同一来源的所有选项卡和窗口中访问，在三者中存储容量最高。\n* **`sessionStorage`**：适用于单个页面会话中的临时数据，当选项卡或窗口关闭时数据将被清除，与 cookies 相比具有更高的存储容量。\n\n以下表格总结了 3 种客户端存储机制。\n\n| 属性 | Cookie | `localStorage` | `sessionStorage` |\n| --- | --- | --- | --- |\n| 发起者 | 客户端或服务器。服务器可以使用 `Set-Cookie` 标头 | 客户端 | 客户端 |\n| 寿命 | 如指定 | 直到删除 | 直到选项卡关闭 |\n| 是否跨浏览器会话持久 | 如果设置了未来的过期日期 | 是 | 否 |\n| 是否随每个 HTTP 请求发送到服务器 | 是，通过 `Cookie` 标头发送 | 否 | 否 |\n| 总容量（每个域） | 4kb | 5MB | 5MB |\n| 访问 | 跨窗口/选项卡 | 跨窗口/选项卡 | 相同选项卡 |\n| 安全性 | JavaScript 无法访问 `HttpOnly` cookies | 无 | 无 |\n\n***\n\n## Web 上的存储\n\nCookies、`localStorage` 和 `sessionStorage` 都是客户端（Web 浏览器）上的存储机制。在客户端存储数据对于仅客户端的状态很有用，例如访问令牌、主题、个性化布局，以便用户可以在跨选项卡和使用会话的网站上获得一致的体验。\n\n这些客户端存储机制具有以下常见属性：\n\n* 这意味着客户端可以读取和修改值（`HttpOnly` cookies 除外）。\n* 基于键值对的存储。\n* 它们只能将值存储为字符串。非字符串必须被序列化为字符串（例如 `JSON.stringify()`）才能被存储。\n\n### 每种存储机制的用例\n\n由于 cookies 的最大大小相对较小，因此不建议将所有客户端数据存储在 cookies 中。关于 cookies 的显著特性是 cookies 会在每个 HTTP 请求中发送到服务器，因此较小的最大大小是一个特性，可以防止您的 HTTP 请求由于 cookies 而变得过大。cookies 的自动过期也是一个有用的特性。\n\n考虑到这一点，最适合存储在 cookies 中的数据是需要传输到服务器的小块数据，例如身份验证令牌、会话 ID、分析跟踪 ID、GDPR cookie 同意、对身份验证、授权和在服务器上呈现很重要的语言偏好。这些值有时很敏感，并且可以从 cookies 提供的 `HttpOnly`、`Secure` 和 `Expires`/`Max-Age` 功能中受益。\n\n`localStorage` 和 `sessionStorage` 都实现了 [Web Storage API 接口](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API)。Web Storages 具有 5MB 的总容量，因此存储大小通常不是问题。关键的区别在于，存储在 Web Storage 中的值不会自动随 HTTP 请求一起发送。\n\n虽然您可以在发出 AJAX/`fetch()` 请求时手动包含来自 Web Storage 的值，但浏览器不会在页面的初始请求/首次加载中包含它们。因此，如果使用服务器端渲染（通常是与身份验证/授权相关的信息），则不应使用 Web Storage 来存储服务器用于页面初始渲染所依赖的数据。`localStorage` 最适合不失效的用户偏好数据，例如主题和布局（如果服务器渲染最终布局并不重要）。`sessionStorage` 最适合只需要在当前浏览会话中访问的临时数据，例如表单数据（用于在意外重新加载期间保留数据）。\n\n以下部分深入探讨了每种客户端存储机制。\n\n### Cookies\n\nCookies 用于在客户端存储小块数据，这些数据可以通过每个 HTTP 请求发送回服务器。\n\n* **存储容量**：所有 cookies 限制在 4KB 左右。\n* **寿命**：Cookies 可以使用 `Expires` 或 `Max-Age` 属性设置特定的过期日期。如果未设置过期日期，则在浏览器关闭时删除 cookie（会话 cookie）。\n* **访问**：Cookies 是特定于域的，可以在同一域内的不同页面和子域之间共享。\n* **安全性**：Cookies 可以标记为 `HttpOnly` 以防止从 JavaScript 访问，从而降低 XSS 攻击的风险。它们也可以使用 `Secure` 标志进行保护，以确保仅在使用 HTTPS 时发送它们。\n\n```js\n// Set a cookie for the name/key `auth_token` with an expiry.\ndocument.cookie =\n  'auth_token=abc123def; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/';\n\n// Read all cookies. There's no way to read specific cookies using `document.cookie`.\n// You have to parse the string yourself.\nconsole.log(document.cookie); // auth_token=abc123def\n\n// Delete the cookie with the name/key `auth_token` by setting an\n// expiry date in the past. The value doesn't matter.\ndocument.cookie = 'auth_token=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';\n```\n\n读取/写入 Cookie 是一件很痛苦的事情。`document.cookie` 返回一个包含所有由 `;` 分隔的键/值对的字符串，您必须自己解析该字符串。[`js-cookie`](https://github.com/js-cookie/js-cookie) npm 库提供了一个简单轻量级的 API，用于在 JavaScript 中读写 Cookie。\n\n访问 Cookie 的现代原生方式是通过 [Cookie Store API](https://developer.mozilla.org/en-US/docs/Web/API/Cookie_Store_API)，该 API 仅在 HTTPS 页面上可用。\n\n```js\n// Set a cookie. More options are available too.\ncookieStore.set('auth_token', 'abc123def');\n\n// Async method to access a single cookie and do something with it.\ncookieStore.get('auth_token').then(...);\n\n// Async method to get all cookies.\ncookieStore.getAll().then(...);\n\n// Async method to delete a single cookie.\ncookieStore.delete('auth_token').then(() =>\n  console.log('Cookie deleted')\n);\n```\n\nCookieStore API 相对较新，可能并非所有浏览器都支持（截至 2024 年 6 月，在最新的 Chrome 和 Edge 中受支持）。请参阅 [caniuse.com](https://caniuse.com/mdn-api_cookiestore) 以获取最新的兼容性信息。\n\n### `localStorage`\n\n`localStorage` 用于存储即使在浏览器关闭并重新打开后仍保留的数据。它专为长期存储数据而设计。\n\n* **存储容量**：通常每个来源约 5MB（因浏览器而异）。\n* **生命周期**：`localStorage` 中的数据会一直存在，直到用户或应用程序显式删除。\n* **访问**：数据可在同一来源的所有选项卡和窗口中访问。\n* **安全性**：页面上的所有 JavaScript 都可以访问 `localStorage` 中的值。\n\n```js\n// Set a value in localStorage.\nlocalStorage.setItem('key', 'value');\n\n// Get a value from localStorage.\nconsole.log(localStorage.getItem('key'));\n\n// Remove a value from localStorage.\nlocalStorage.removeItem('key');\n\n// Clear all data in localStorage.\nlocalStorage.clear();\n```\n\n### `sessionStorage`\n\n`sessionStorage` 用于存储页面会话期间的数据。它专为临时存储数据而设计。\n\n* **存储容量**: 通常每个来源约 5MB（取决于浏览器）。\n* **生命周期**: `sessionStorage` 中的数据在页面会话结束时清除（即，当浏览器或选项卡关闭时）。重新加载页面不会销毁 `sessionStorage` 中的数据。\n* **访问**: 数据仅在当前选项卡（或浏览上下文）中可访问。不同的选项卡共享不同的 `sessionStorage` 对象，即使它们属于同一个浏览器窗口。在这种情况下，窗口指的是可以包含多个选项卡的浏览器窗口。\n* **安全性**: 同一页面上的所有 JavaScript 都可以访问该页面 `sessionStorage` 中的值。\n\n```js\n// Set a value in sessionStorage.\nsessionStorage.setItem('key', 'value');\n\n// Get a value from sessionStorage.\nconsole.log(sessionStorage.getItem('key'));\n\n// Remove a value from sessionStorage.\nsessionStorage.removeItem('key');\n\n// Clear all data in sessionStorage.\nsessionStorage.clear();\n```\n\n## 注意事项\n\n还有其他客户端存储机制，例如 [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API)，它比上述技术更强大，但使用起来更复杂。\n\n## 参考\n\n* [localStorage、sessionStorage、session 和 cookie 之间有什么区别？](https://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookies)\n"
  },
  {
    "path": "questions/describe-the-difference-between-script-async-and-script-defer/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"d7ae8e9e\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"f015f69a\",\n        \"c770ec40\",\n        \"9267a3a\",\n        \"15376261\",\n        \"2a7816d0\",\n        \"3dab564a\",\n        \"b62205e7\",\n        \"35bc0a6e\",\n        \"4bb1139c\",\n        \"c697e0a0\",\n        \"1135cb8e\",\n        \"43aae7f3\",\n        \"25fe358b\",\n        \"9413283\",\n        \"ecb7916f\",\n        \"a40917e4\",\n        \"bcdaddfc\",\n        \"8762e9b8\",\n        \"54597c7c\",\n        \"96e9e665\",\n        \"add698fb\",\n        \"43628d33\",\n        \"acc96ff7\",\n        \"1f4770e5\",\n        \"956d9bb9\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"f015f69a\",\n        \"c770ec40\",\n        \"9267a3a\",\n        \"15376261\",\n        \"2a7816d0\",\n        \"3dab564a\",\n        \"b62205e7\",\n        \"35bc0a6e\",\n        \"4bb1139c\",\n        \"c697e0a0\",\n        \"1135cb8e\",\n        \"43aae7f3\",\n        \"25fe358b\",\n        \"9413283\",\n        \"ecb7916f\",\n        \"a40917e4\",\n        \"bcdaddfc\",\n        \"8762e9b8\",\n        \"54597c7c\",\n        \"96e9e665\",\n        \"add698fb\",\n        \"43628d33\",\n        \"acc96ff7\",\n        \"1f4770e5\",\n        \"956d9bb9\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/describe-the-difference-between-script-async-and-script-defer/en-US.mdx",
    "content": "---\ntitle: Describe the difference between `<script>`, `<script async>` and `<script defer>`\n---\n\n## TL;DR\n\nAll of these ways (`<script>`, `<script async>`, and `<script defer>`) are used to load and execute JavaScript files in an HTML document, but they differ in how the browser handles loading and execution of the script:\n\n- `<script>` is the default way of including JavaScript. The browser blocks HTML parsing while the script is being downloaded and executed. The browser will not continue rendering the page until the script has finished executing.\n- `<script async>` downloads the script asynchronously, in parallel with parsing the HTML. Executes the script as soon as it is available, potentially interrupting the HTML parsing. `<script async>` do not wait for each other and execute in no particular order.\n- `<script defer>` downloads the script asynchronously, in parallel with parsing the HTML. However, the execution of the script is deferred until HTML parsing is complete, in the order they appear in the HTML.\n\nHere's a table summarizing the 3 ways of loading `<script>`s in a HTML document.\n\n| Feature | `<script>` | `<script async>` | `<script defer>` |\n| --- | --- | --- | --- |\n| Parsing behavior | Blocks HTML parsing | Runs parallel to parsing | Runs parallel to parsing |\n| Execution order | In order of appearance | Not guaranteed | In order of appearance |\n| DOM dependency | No | No | Yes (waits for DOM) |\n\n---\n\n## What `<script>` tags are for\n\n`<script>` tags are used to include JavaScript on a web page. The `async` and `defer` attributes are used to change how/when the loading and execution of the script happens.\n\n## `<script>`\n\nFor normal `<script>` tags without any `async` or `defer`, when they are encountered, HTML parsing is blocked, the script is fetched and executed immediately. HTML parsing resumes after the script is executed. This can block rendering of the page if the script is large.\n\nUse `<script>` for critical scripts that the page relies on to render properly.\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>Regular Script</title>\n  </head>\n  <body>\n    <!-- Content before the script -->\n    <h1>Regular Script Example</h1>\n    <p>This content will be rendered before the script executes.</p>\n\n    <!-- Regular script -->\n    <script src=\"regular.js\"></script>\n\n    <!-- Content after the script -->\n    <p>This content will be rendered after the script executes.</p>\n  </body>\n</html>\n```\n\n{/* TODO: Add CSB examples for blocking scripts */}\n\n## `<script async>`\n\nIn `<script async>`, the browser downloads the script file asynchronously (in parallel with HTML parsing) and executes it as soon as it is available (potentially before HTML parsing completes). The execution will not necessarily be executed in the order in which it appears in the HTML document. This can improve perceived performance because the browser doesn't wait for the script to download before continuing to render the page.\n\nUse `<script async>` when the script is independent of any other scripts on the page, for example, analytics and ads scripts.\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>Async Script</title>\n  </head>\n  <body>\n    <!-- Content before the script -->\n    <h1>Async Script Example</h1>\n    <p>This content will be rendered before the async script executes.</p>\n\n    <!-- Async script -->\n    <script async src=\"async.js\"></script>\n\n    <!-- Content after the script -->\n    <p>\n      This content may be rendered before or after the async script executes.\n    </p>\n  </body>\n</html>\n```\n\n## `<script defer>`\n\nSimilar to `<script async>`, `<script defer>` also downloads the script in parallel to HTML parsing but the script is only executed when the document has been fully parsed and before firing `DOMContentLoaded`. If there are multiple of them, each deferred script is executed in the order they appeared in the HTML document.\n\nIf a script relies on a fully-parsed DOM, the `defer` attribute will be useful in ensuring that the HTML is fully parsed before executing.\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>Deferred Script</title>\n  </head>\n  <body>\n    <!-- Content before the script -->\n    <h1>Deferred Script Example</h1>\n    <p>This content will be rendered before the deferred script executes.</p>\n\n    <!-- Deferred script -->\n    <script defer src=\"deferred.js\"></script>\n\n    <!-- Content after the script -->\n    <p>This content will be rendered before the deferred script executes.</p>\n  </body>\n</html>\n```\n\n## Notes\n\n- The `async` attribute should be used for scripts that are not critical to the initial rendering of the page and do not depend on each other, while the `defer` attribute should be used for scripts that depend on / is depended on by another script.\n- The `async` and `defer` attributes are ignored for scripts that have no `src` attribute.\n- `<script>`s with `defer` or `async` that contain `document.write()` will be ignored with a message like \"A call to `document.write()` from an asynchronously-loaded external script was ignored\".\n- Even though `async` and `defer` help to make script downloading asynchronous, the scripts are still eventually executed on the main thread. If these scripts are computationally intensive, it can result in laggy/frozen UI. [Partytown](https://partytown.builder.io/) is a library that helps relocate script executions into a [web worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) and off the [main thread](https://developer.mozilla.org/en-US/docs/Glossary/Main_thread), which is great for third-party scripts where you do not have control over the code.\n\n{/* TODO: Add image https://media.licdn.com/dms/image/D5612AQEYCnsZ1f9GFQ/article-cover_image-shrink_600_2000/0/1699370054733?e=2147483647&v=beta&t=MeKuUXk5QMblVoausf5p3swTkBCICOHoRsijQqMfxZE */}\n\n## Further reading\n\n- [`<script>`: The Script element | MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)\n- [async vs defer attributes](https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html)\n"
  },
  {
    "path": "questions/describe-the-difference-between-script-async-and-script-defer/metadata.json",
    "content": "{\n  \"slug\": \"describe-the-difference-between-script-async-and-script-defer\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"html\", \"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 80,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/describe-the-difference-between-script-async-and-script-defer/pt-BR.mdx",
    "content": "---\ntitle: Descreva a diferença entre `<script>`, `<script async>` e `<script defer>`\n---\n\ntags `<script>` são usadas para incluir JavaScript em uma página da web. Os atributos `async` e `defer` são usados para mudar como/quando o carregamento e a execução do script acontecem.\n\n## Simples `<script>`\n\nPara tags normais `<script>` sem qualquer `async` ou `defer`, quando forem encontrados, a análise do HTML é bloqueada, o script é buscado e executado imediatamente. A análise do HTML é retomada após a execução do script.\n\n## `<script async>`\n\nNo `<script async>`, o script será buscado em paralelo à análise do HTML e será executado assim que estiver disponível (potencialmente antes da conclusão da análise do HTML) e não será necessariamente executado na ordem em que aparece no documento HTML. Use `async` quando o script é independente de quaisquer outros scripts na página, por exemplo, analytics.\n\n## `<script defer>`\n\nNo `<script defer>`, o script será buscado em paralelo à análise HTML e executado quando o documento tiver sido totalmente analisado, mas antes de disparar `DOMContentLoaded`. Se houver múltiplos, cada script adiado é executado na ordem em que eles apareceram no documento HTML.\n\nSe um script depende de um DOM totalmente analisado, o atributo `defer` será útil para garantir que o HTML seja totalmente analisado antes de ser executado.\n\n## Notas\n\n- Geralmente, o atributo `async` deve ser usado para scripts que não são críticos para a renderização inicial da página e não dependem um do outro. enquanto o atributo `defer` deve ser usado para scripts que dependem de / é dependente de outro script.\n- Os atributos `async` e `defer` são ignorados para scripts que não têm o atributo `src`.\n- `<script>`s com `defer` ou `async` que contêm `document.write()` serão ignorados com uma mensagem como \"Uma chamada para o documento.write() de um script externo carregado de forma assíncrona foi ignorada\".\n\n## Referências\n\n- [`<script>`: O elemento Script | MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)\n- [async vs defer attributes](https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html)\n"
  },
  {
    "path": "questions/describe-the-difference-between-script-async-and-script-defer/zh-CN.mdx",
    "content": "---\ntitle: 描述 `<script>`、`<script async>` 和 `<script defer>` 之间的区别\n---\n\n## TL;DR\n\n所有这些方式（`<script>`、`<script async>` 和 `<script defer>`）都用于在 HTML 文档中加载和执行 JavaScript 文件，但它们在浏览器处理脚本的加载和执行方式上有所不同：\n\n* `<script>` 是包含 JavaScript 的默认方式。浏览器在下载和执行脚本时会阻止 HTML 解析。在脚本执行完毕之前，浏览器不会继续渲染页面。\n* `<script async>` 异步下载脚本，与解析 HTML 并行。在脚本可用后立即执行脚本，可能会中断 HTML 解析。`<script async>` 之间不会互相等待，并且以不特定的顺序执行。\n* `<script defer>` 异步下载脚本，与解析 HTML 并行。但是，脚本的执行被推迟到 HTML 解析完成后，按照它们在 HTML 中出现的顺序。\n\n这是一个表格，总结了在 HTML 文档中加载 `<script>` 的 3 种方式。\n\n| 特性 | `<script>` | `<script async>` | `<script defer>` |\n| --- | --- | --- | --- |\n| 解析行为 | 阻止 HTML 解析 | 与解析并行运行 | 与解析并行运行 |\n| 执行顺序 | 按照出现顺序 | 不保证 | 按照出现顺序 |\n| DOM 依赖 | 否 | 否 | 是（等待 DOM） |\n\n***\n\n## `<script>` 标签的用途\n\n`<script>` 标签用于在网页中包含 JavaScript。`async` 和 `defer` 属性用于更改脚本的加载和执行方式/时间。\n\n## `<script>`\n\n对于没有任何 `async` 或 `defer` 的普通 `<script>` 标签，当遇到它们时，HTML 解析会被阻止，脚本会被立即获取和执行。HTML 解析在脚本执行完毕后恢复。如果脚本很大，这可能会阻止页面的渲染。\n\n将 `<script>` 用于页面依赖于正确渲染的关键脚本。\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>Regular Script</title>\n  </head>\n  <body>\n    <!-- Content before the script -->\n    <h1>Regular Script Example</h1>\n    <p>This content will be rendered before the script executes.</p>\n\n    <!-- Regular script -->\n    <script src=\"regular.js\"></script>\n\n    <!-- Content after the script -->\n    <p>This content will be rendered after the script executes.</p>\n  </body>\n</html>\n```\n\n{/* TODO: Add CSB examples for blocking scripts */}\n\n## `<script async>`\n\n在 `<script async>` 中，浏览器异步下载脚本文件（与 HTML 解析并行），并在脚本可用后立即执行（可能在 HTML 解析完成之前）。执行不一定按照它在 HTML 文档中出现的顺序执行。这可以提高感知的性能，因为浏览器在继续渲染页面之前不必等待脚本下载。\n\n当脚本独立于页面上的任何其他脚本时，使用 `<script async>`，例如分析和广告脚本。\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>Async Script</title>\n  </head>\n  <body>\n    <!-- Content before the script -->\n    <h1>Async Script Example</h1>\n    <p>This content will be rendered before the async script executes.</p>\n\n    <!-- Async script -->\n    <script async src=\"async.js\"></script>\n\n    <!-- Content after the script -->\n    <p>\n      This content may be rendered before or after the async script executes.\n    </p>\n  </body>\n</html>\n```\n\n## `<script defer>`\n\n与 `<script async>` 类似，`<script defer>` 也会与 HTML 解析并行下载脚本，但脚本仅在文档被完全解析并且在触发 `DOMContentLoaded` 之前执行。如果有多个，则每个延迟脚本按照它们在 HTML 文档中出现的顺序执行。\n\n如果脚本依赖于完全解析的 DOM，则 `defer` 属性将有助于确保在执行之前完全解析 HTML。\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>Deferred Script</title>\n  </head>\n  <body>\n    <!-- Content before the script -->\n    <h1>Deferred Script Example</h1>\n    <p>This content will be rendered before the deferred script executes.</p>\n\n    <!-- Deferred script -->\n    <script defer src=\"deferred.js\"></script>\n\n    <!-- Content after the script -->\n    <p>This content will be rendered before the deferred script executes.</p>\n  </body>\n</html>\n```\n\n## 注意事项\n\n* `async` 属性应用于对页面初始渲染不关键且彼此不依赖的脚本，而 `defer` 属性应用于依赖于/被另一个脚本依赖的脚本。\n* 对于没有 `src` 属性的脚本，将忽略 `async` 和 `defer` 属性。\n* 包含 `document.write()` 的带有 `defer` 或 `async` 的 `<script>` 将被忽略，并显示类似“从异步加载的外部脚本对 `document.write()` 的调用被忽略”的消息。\n* 即使 `async` 和 `defer` 有助于使脚本下载异步，但脚本最终仍在主线程上执行。如果这些脚本是计算密集型的，则可能导致 UI 滞后/冻结。[Partytown](https://partytown.builder.io/) 是一个库，它有助于将脚本执行重新定位到 [web worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) 并从 [主线程](https://developer.mozilla.org/en-US/docs/Glossary/Main_thread) 中移出，这对于您无法控制代码的第三方脚本非常有用。\n\n{/* TODO: Add image https://media.licdn.com/dms/image/D5612AQEYCnsZ1f9GFQ/article-cover_image-shrink_600_2000/0/1699370054733?e=2147483647&v=beta&t=MeKuUXk5QMblVoausf5p3swTkBCICOHoRsijQqMfxZE */}\n\n## 延伸阅读\n\n* [`<script>`: The Script element | MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)\n* [async vs defer attributes](https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html)\n"
  },
  {
    "path": "questions/difference-between-document-load-event-and-document-domcontentloaded-event/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"81ee2f0a\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"cc68c002\",\n        \"a62a2a23\",\n        \"2a7816d0\",\n        \"55364efe\",\n        \"f4edb19c\",\n        \"e14328af\",\n        \"c610f08\",\n        \"1a0691e8\",\n        \"c345447a\",\n        \"c0525804\",\n        \"67423e0a\",\n        \"f3f1deb7\",\n        \"1f4770e5\",\n        \"d3ff56e2\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"cc68c002\",\n        \"a62a2a23\",\n        \"2a7816d0\",\n        \"55364efe\",\n        \"f4edb19c\",\n        \"e14328af\",\n        \"c610f08\",\n        \"1a0691e8\",\n        \"c345447a\",\n        \"c0525804\",\n        \"67423e0a\",\n        \"f3f1deb7\",\n        \"1f4770e5\",\n        \"d3ff56e2\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/difference-between-document-load-event-and-document-domcontentloaded-event/en-US.mdx",
    "content": "---\ntitle: Difference between document `load` event and document `DOMContentLoaded` event?\n---\n\n## TL;DR\n\nThe `DOMContentLoaded` event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. The `load` event, on the other hand, fires when the entire page, including all dependent resources such as stylesheets and images, has finished loading.\n\n```javascript\ndocument.addEventListener('DOMContentLoaded', function () {\n  console.log('DOM fully loaded and parsed');\n});\n\nwindow.addEventListener('load', function () {\n  console.log('Page fully loaded');\n});\n```\n\n---\n\n## Difference between document `load` event and document `DOMContentLoaded` event\n\n### `DOMContentLoaded` event\n\nThe `DOMContentLoaded` event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. This event is useful when you want to execute JavaScript code as soon as the DOM is ready, without waiting for all resources to be fully loaded.\n\n```javascript\ndocument.addEventListener('DOMContentLoaded', function () {\n  console.log('DOM fully loaded and parsed');\n});\n```\n\n### `load` event\n\nThe `load` event is fired when the entire page, including all dependent resources such as stylesheets, images, and subframes, has finished loading. This event is useful when you need to perform actions that require all resources to be fully loaded, such as initializing a slideshow or performing layout calculations that depend on image sizes.\n\n```javascript\nwindow.addEventListener('load', function () {\n  console.log('Page fully loaded');\n});\n```\n\n### Key differences\n\n- **Timing**: `DOMContentLoaded` fires earlier than `load`. `DOMContentLoaded` occurs after the HTML is fully parsed, while `load` waits for all resources to be loaded.\n- **Use cases**: Use `DOMContentLoaded` for tasks that only require the DOM to be ready, such as attaching event listeners or manipulating the DOM. Use `load` for tasks that depend on all resources being fully loaded, such as image-dependent layout calculations.\n\n## Further reading\n\n- [MDN Web Docs: DOMContentLoaded](https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event)\n- [MDN Web Docs: load event](https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event)\n- [JavaScript.info: DOMContentLoaded, load, beforeunload, unload](https://javascript.info/onload-ondomcontentloaded)\n"
  },
  {
    "path": "questions/difference-between-document-load-event-and-document-domcontentloaded-event/metadata.json",
    "content": "{\n  \"slug\": \"difference-between-document-load-event-and-document-domcontentloaded-event\",\n  \"languages\": [],\n  \"companies\": [\"atlassian\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": false,\n  \"topics\": [\"html\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/difference-between-document-load-event-and-document-domcontentloaded-event/pt-BR.mdx",
    "content": "---\ntitle: Qual a diferença entre o evento `load` do documento e o evento `DOMContentLoaded` do documento?\n---\n\nO evento `DOMContentLoaded` é disparado quando o documento HTML inicial foi completamente carregado e analisado, sem esperar que folhas de estilo, imagens e subframes terminem de carregar.\n\nO evento `load` do `window` só é disparado após o DOM e todos os recursos e ativos dependentes terem sido carregados.\n"
  },
  {
    "path": "questions/difference-between-document-load-event-and-document-domcontentloaded-event/zh-CN.mdx",
    "content": "---\ntitle: document `load` 事件和 document `DOMContentLoaded` 事件的区别？\n---\n\n## TL;DR\n\n`DOMContentLoaded` 事件在初始 HTML 文档完全加载和解析后触发，而无需等待样式表、图像和子框架完成加载。另一方面，`load` 事件在整个页面（包括所有依赖资源，如样式表和图像）完成加载后触发。\n\n```javascript\ndocument.addEventListener('DOMContentLoaded', function () {\n  console.log('DOM fully loaded and parsed');\n});\n\nwindow.addEventListener('load', function () {\n  console.log('Page fully loaded');\n});\n```\n\n***\n\n## document `load` 事件和 document `DOMContentLoaded` 事件的区别\n\n### `DOMContentLoaded` 事件\n\n`DOMContentLoaded` 事件在初始 HTML 文档完全加载和解析后触发，而无需等待样式表、图像和子框架完成加载。当您希望在 DOM 准备就绪后立即执行 JavaScript 代码，而无需等待所有资源完全加载时，此事件非常有用。\n\n```javascript\ndocument.addEventListener('DOMContentLoaded', function () {\n  console.log('DOM fully loaded and parsed');\n});\n```\n\n### `load` 事件\n\n`load` 事件在整个页面（包括所有依赖资源，如样式表、图像和子框架）完成加载后触发。当您需要执行需要所有资源完全加载的操作时，此事件非常有用，例如初始化幻灯片或执行依赖于图像大小的布局计算。\n\n```javascript\nwindow.addEventListener('load', function () {\n  console.log('Page fully loaded');\n});\n```\n\n### 关键区别\n\n*   **时序**：`DOMContentLoaded` 比 `load` 提前触发。`DOMContentLoaded` 在 HTML 完全解析后发生，而 `load` 等待所有资源加载完毕。\n*   **用例**：将 `DOMContentLoaded` 用于仅需要 DOM 就绪的任务，例如附加事件侦听器或操作 DOM。将 `load` 用于依赖所有资源完全加载的任务，例如依赖于图像的布局计算。\n\n## 延伸阅读\n\n*   [MDN Web Docs: DOMContentLoaded](https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event)\n*   [MDN Web Docs: load event](https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event)\n*   [JavaScript.info: DOMContentLoaded, load, beforeunload, unload](https://javascript.info/onload-ondomcontentloaded)\n"
  },
  {
    "path": "questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"a53864cf\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"d37f9ad6\",\n        \"bdd1f71e\",\n        \"2a7816d0\",\n        \"244434dd\",\n        \"954b69a7\",\n        \"cca5f117\",\n        \"83de2a2f\",\n        \"8675603b\",\n        \"45c8e75a\",\n        \"da77f48f\",\n        \"eb511457\",\n        \"738d0f97\",\n        \"484f0af9\",\n        \"13aa5e50\",\n        \"30c4051a\",\n        \"ebd53803\",\n        \"45e20bd0\",\n        \"1f4770e5\",\n        \"178428f1\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d37f9ad6\",\n        \"bdd1f71e\",\n        \"2a7816d0\",\n        \"244434dd\",\n        \"954b69a7\",\n        \"cca5f117\",\n        \"83de2a2f\",\n        \"8675603b\",\n        \"45c8e75a\",\n        \"da77f48f\",\n        \"eb511457\",\n        \"738d0f97\",\n        \"484f0af9\",\n        \"13aa5e50\",\n        \"30c4051a\",\n        \"ebd53803\",\n        \"45e20bd0\",\n        \"1f4770e5\",\n        \"178428f1\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/difference-between-function-person-var-person-person-and-var-person-new-person/en-US.mdx",
    "content": "---\ntitle: 'Difference between: `function Person(){}`, `const person = Person()`, and `const person = new Person()` in JavaScript?'\n---\n\n## TL;DR\n\n- `function Person(){}`: A function declaration in JavaScript. It can be used as a regular function or as a constructor.\n- `const person = Person()`: Calls `Person` as a regular function, not a constructor. If `Person` is intended to be a constructor, this will lead to unexpected behavior.\n- `const person = new Person()`: Creates a new instance of `Person`, correctly utilizing the constructor function to initialize the new object.\n\n| Aspect | `function Person(){}` | `const person = Person()` | `const person = new Person()` |\n| --- | --- | --- | --- |\n| Type | Function declaration | Function call | Constructor call |\n| Usage | Defines a function | Invokes `Person` as a regular function | Creates a new instance of `Person` |\n| Instance Creation | No instance created | No instance created | New instance created |\n| Common Mistake | N/A | Misusing as constructor leading to `undefined` | None (when used correctly) |\n\n---\n\n## Function declaration\n\n`function Person(){}` is a standard function declaration in JavaScript. When written in PascalCase, it follows the convention for functions intended to be used as constructors.\n\n```js\nfunction Person(name) {\n  this.name = name;\n}\n```\n\nThis code defines a function named `Person` that takes a parameter `name` and assigns it to the `name` property of the object created from this constructor function. When the `this` keyword is used in a constructor, it refers to the newly created object.\n\n## Function call\n\n`const person = Person()` simply invoke the function's code. When you invoke `Person` as a regular function (i.e., without the `new` keyword), the function does not behave as a constructor. Instead, it executes its code and returns `undefined` if no return value is specified and that gets assigned to the variable intended as the instance. Invoking as such is a common mistake if the function is intended to be used as a constructor.\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person = Person('John'); // Throws error in strict mode\nconsole.log(person); // undefined\nconsole.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined\n```\n\nIn this case, `Person('John')` does not create a new object. The `person` variable is assigned `undefined` because the `Person` function does not explicitly return a value. Attempting to access `person.name` throws an error because `person` is `undefined`.\n\n## Constructor call\n\n`const person = new Person()` creates an instance of the `Person` object using the new operator, which inherits from `Person.prototype`. An alternative would be to use `Object.create`, such as: `Object.create(Person.prototype)` and `Person.call(person, 'John')` initializes the object.\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person = new Person('John');\nconsole.log(person); // Person { name: 'John' }\nconsole.log(person.name); // 'John'\n\n// Alternative\nconst person1 = Object.create(Person.prototype);\nPerson.call(person1, 'John');\nconsole.log(person1); // Person { name: 'John' }\nconsole.log(person1.name); // 'John'\n```\n\nIn this case, `new Person('John')` creates a new object, and `this` within `Person` refers to this new object. The `name` property is correctly set on the new object. The `person` variable is assigned the new instance of `Person` with the name property set to `'John'`. And for the alternative object creation, `Object.create(Person.prototype)` creates a new object with `Person.prototype` as its prototype. `Person.call(person, 'John')` initializes the object, setting the `name` property.\n\n## Follow-Up Questions\n\n- What are the differences between function constructors and ES6 class syntax?\n- What are some common use cases for `Object.create`?\n\n## Further reading\n\n- [MDN Web Docs: Object prototypes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes)\n- [Differences between Class and Function Constructors](https://www.greatfrontend.com/questions/quiz/what-are-the-differences-between-es6-class-and-es5-function-constructors?fpr=yangshun)\n- [How `this` keyword works in JavaScript?](https://www.greatfrontend.com/questions/quiz/explain-how-this-works-in-javascript?fpr=yangshun)\n"
  },
  {
    "path": "questions/difference-between-function-person-var-person-person-and-var-person-new-person/metadata.json",
    "content": "{\n  \"slug\": \"difference-between-function-person-var-person-person-and-var-person-new-person\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"high\",\n  \"ranking\": 140,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/difference-between-function-person-var-person-person-and-var-person-new-person/pt-BR.mdx",
    "content": "---\ntitle: 'Diferença entre: `function Person(){}`, `var person = Person()`, e `var person = new Person()`?'\n---\n\nEsta pergunta é muito vaga. Nossa melhor suposição sobre a intenção dessa pergunta é que ela está perguntando sobre construtores em JavaScript. Tecnicamente falando, `function Person(){}` é apenas uma declaração de função normal. A convenção é usar PascalCase para funções que se destinam a ser usadas como construtores.\n\n`var person = Person()` invoca o `Person` como uma função, e não como um construtor. Invocar como tal é um erro comum se a função pretende ser usada como um construtor. Normalmente, o construtor não devolve nada. Assim, invocando o construtor como uma função normal retornará `undefined` e que será atribuído à variável pretendida como a instância.\n\n`var person = new Person()` cria uma instância do objeto `Person` usando o operador `new`, que herda de `Person.prototype`. Uma alternativa seria usar `Object.create`, tais como: `Object.create(Person.prototype)`.\n\n```js\nfunction Person(name) {\n  this.name = name;\n}\n\nvar person = Person('John');\nconsole.log(person); // undefined\nconsole.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined\n\nvar person = new Person('John');\nconsole.log(person); // Person { name: \"John\" }\nconsole.log(person.name); // \"john\"\n```\n"
  },
  {
    "path": "questions/difference-between-function-person-var-person-person-and-var-person-new-person/zh-CN.mdx",
    "content": "---\ntitle: >-\n  JavaScript 中：`function Person(){}`、`const person = Person()` 和 `const person =\n  new Person()` 的区别？\n---\n\n## TL;DR\n\n* `function Person(){}`：JavaScript 中的函数声明。它可以作为常规函数或构造函数使用。\n* `const person = Person()`：将 `Person` 作为常规函数调用，而不是构造函数。如果 `Person` 旨在用作构造函数，这将导致意外行为。\n* `const person = new Person()`：创建 `Person` 的新实例，正确利用构造函数来初始化新对象。\n\n| 方面 | `function Person(){}` | `const person = Person()` | `const person = new Person()` |\n| --- | --- | --- | --- |\n| 类型 | 函数声明 | 函数调用 | 构造函数调用 |\n| 用法 | 定义一个函数 | 将 `Person` 作为常规函数调用 | 创建 `Person` 的新实例 |\n| 实例创建 | 未创建实例 | 未创建实例 | 创建新实例 |\n| 常见错误 | N/A | 误用作构造函数，导致 `undefined` | 无（正确使用时） |\n\n***\n\n## 函数声明\n\n`function Person(){}` 是 JavaScript 中的标准函数声明。当用 PascalCase 编写时，它遵循旨在用作构造函数的函数的约定。\n\n```js\nfunction Person(name) {\n  this.name = name;\n}\n```\n\n此代码定义了一个名为 `Person` 的函数，该函数接受一个参数 `name` 并将其分配给从此构造函数创建的对象的 `name` 属性。当在构造函数中使用 `this` 关键字时，它指的是新创建的对象。\n\n## 函数调用\n\n`const person = Person()` 只是调用该函数的代码。当您将 `Person` 作为常规函数调用（即，不使用 `new` 关键字）时，该函数的行为不像构造函数。相反，它执行其代码，如果未指定返回值，则返回 `undefined`，并将其分配给作为实例的变量。如果该函数旨在用作构造函数，则这样调用是一个常见的错误。\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person = Person('John'); // Throws error in strict mode\nconsole.log(person); // undefined\nconsole.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined\n```\n\n在这种情况下，`Person('John')` 不会创建新对象。`person` 变量被赋值为 `undefined`，因为 `Person` 函数没有显式返回值。尝试访问 `person.name` 会抛出错误，因为 `person` 是 `undefined`。\n\n## 构造函数调用\n\n`const person = new Person()` 使用 new 运算符创建 `Person` 对象的实例，该实例继承自 `Person.prototype`。另一种方法是使用 `Object.create`，例如：`Object.create(Person.prototype)` 和 `Person.call(person, 'John')` 初始化对象。\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person = new Person('John');\nconsole.log(person); // Person { name: 'John' }\nconsole.log(person.name); // 'John'\n\n// Alternative\nconst person1 = Object.create(Person.prototype);\nPerson.call(person1, 'John');\nconsole.log(person1); // Person { name: 'John' }\nconsole.log(person1.name); // 'John'\n```\n\n在这种情况下，`new Person('John')` 创建一个新对象，`Person` 中的 `this` 指的是这个新对象。`name` 属性在新对象上被正确设置。`person` 变量被分配了 `Person` 的新实例，其 name 属性设置为 `'John'`。对于备用对象创建，`Object.create(Person.prototype)` 创建一个新对象，并将 `Person.prototype` 作为其原型。`Person.call(person, 'John')` 初始化对象，设置 `name` 属性。\n\n## 后续问题\n\n* 函数构造函数和 ES6 类语法之间有什么区别？\n* `Object.create` 的一些常见用例是什么？\n\n## 延伸阅读\n\n* [MDN Web Docs: Object prototypes](https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Objects/Object_prototypes)\n* [Differences between Class and Function Constructors](https://www.greatfrontend.com/questions/quiz/what-are-the-differences-between-es6-class-and-es5-function-constructors?fpr=yangshun)\n* [How `this` keyword works in JavaScript?](https://www.greatfrontend.com/questions/quiz/explain-how-this-works-in-javascript?fpr=yangshun)\n"
  },
  {
    "path": "questions/explain-ajax-in-as-much-detail-as-possible/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"74a06a67\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"bf25ddb3\",\n        \"b76581cf\",\n        \"933366c8\",\n        \"792ac232\",\n        \"997ac64a\",\n        \"2a7816d0\",\n        \"cf7256bd\",\n        \"4911af41\",\n        \"43a448f1\",\n        \"74d90ce3\",\n        \"99d92485\",\n        \"933366c8\",\n        \"bf05c67b\",\n        \"67f1451\",\n        \"7923e2bf\",\n        \"997ac64a\",\n        \"5f9a1465\",\n        \"947370d5\",\n        \"f4042834\",\n        \"e5866039\",\n        \"6b08567a\",\n        \"67f96ccc\",\n        \"1f4770e5\",\n        \"1365d419\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"bf25ddb3\",\n        \"b76581cf\",\n        \"933366c8\",\n        \"792ac232\",\n        \"997ac64a\",\n        \"2a7816d0\",\n        \"cf7256bd\",\n        \"4911af41\",\n        \"43a448f1\",\n        \"74d90ce3\",\n        \"99d92485\",\n        \"933366c8\",\n        \"bf05c67b\",\n        \"67f1451\",\n        \"7923e2bf\",\n        \"997ac64a\",\n        \"5f9a1465\",\n        \"947370d5\",\n        \"f4042834\",\n        \"e5866039\",\n        \"6b08567a\",\n        \"67f96ccc\",\n        \"1f4770e5\",\n        \"1365d419\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-ajax-in-as-much-detail-as-possible/en-US.mdx",
    "content": "---\ntitle: Explain AJAX in as much detail as possible\n---\n\n## TL;DR\n\nAJAX (Asynchronous JavaScript and XML) facilitates asynchronous communication between the client and server, enabling dynamic updates to web pages without reloading. It uses techniques like `XMLHttpRequest` or the `fetch()` API to send and receive data in the background. In modern web applications, the `fetch()` API is more commonly used to implement AJAX.\n\n**Using `XMLHttpRequest`**\n\n```js live\nlet xhr = new XMLHttpRequest();\nxhr.onreadystatechange = function () {\n  if (xhr.readyState === XMLHttpRequest.DONE) {\n    if (xhr.status === 200) {\n      console.log(xhr.responseText);\n    } else {\n      console.error('Request failed: ' + xhr.status);\n    }\n  }\n};\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.send();\n```\n\n**Using `fetch()`**\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Fetch error:', error));\n```\n\n---\n\n## AJAX (Asynchronous JavaScript and XML)\n\nAJAX (asynchronous JavaScript and XML) is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. Unlike traditional web applications where every user interaction triggers a full page reload, with AJAX, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. By decoupling the data interchange layer from the presentation layer, AJAX allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page. In practice, modern implementations commonly use JSON instead of XML, due to the advantages of JSON being native to JavaScript.\n\nTraditionally, AJAX was implemented using the `XMLHttpRequest` API, but the `fetch()` API is more suitable and easier to use for modern web applications.\n\n## `XMLHttpRequest` API\n\nHere's a basic example of how it can be used:\n\n```js live\nlet xhr = new XMLHttpRequest();\nxhr.onreadystatechange = function () {\n  if (xhr.readyState === XMLHttpRequest.DONE) {\n    if (xhr.status === 200) {\n      console.log(xhr.responseText);\n    } else {\n      console.error('Request failed: ' + xhr.status);\n    }\n  }\n};\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.send();\n```\n\n## `fetch()` API\n\nAlternatively, the `fetch()` API provides a modern, promise-based approach to making AJAX requests. It is more commonly used in modern web applications.\n\nHere's how you can use it:\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Fetch error:', error));\n```\n\n## How does AJAX work?\n\nIn modern browsers, AJAX is done using the `fetch()` API instead of `XMLHTTPRequest`, so we will explain how the `fetch()` API works instead:\n\n1. **Making a request**: The [`fetch()` function](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) initiates an asynchronous request to fetch a resource from a URL. It takes one mandatory argument – the URL of the resource to fetch, and optionally accepts a second argument - an `options` object that allows configuring the HTTP request with options like the HTTP method, headers, body, etc.\n\n   ```js\n   fetch('https://api.example.com/data', {\n     method: 'GET', // or 'POST', 'PUT', 'DELETE', etc.\n     headers: {\n       'Content-Type': 'application/json',\n     },\n   });\n   ```\n\n2. **Return a promise**: The `fetch()` function returns a `Promise` that resolves to a [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object representing the response from the server. This `Promise needs` to be handled using `.then()` or `async/await`.\n3. **Handling the response**: The `Response` object provides methods to define how the body content should be handled, such as `.json()` for parsing JSON data, `.text()` for plain text, `.blob()` for binary data, etc.\n\n   ```js live\n   fetch('https://jsonplaceholder.typicode.com/todos/1')\n     .then((response) => response.json())\n     .then((data) => console.log(data))\n     .catch((error) => console.error('Error:', error));\n   ```\n\n4. **Asynchronous nature** The `fetch` API is asynchronous, allowing the browser to continue executing other tasks while waiting for the server response. This prevents blocking the main thread and provides a better user experience. The `then()` and `catch()` callbacks are put onto the microtask queue when executed as part of the [event loop](/questions/quiz/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue).\n5. **Request options** The optional second argument to `fetch()` allows configuring various aspects of the request, such as the HTTP method, headers, body, credentials, caching behavior, and more.\n6. **Error handling** Errors during the request, such as network failures or invalid responses, are caught and propagated through the Promise chain using the `.catch()` method or try/catch blocks with `async/await`.\n\nThe `fetch()` API provides a modern, Promise-based approach to making HTTP requests in JavaScript, replacing the older `XMLHttpRequest` API. It offers a simpler and more flexible way to interact with APIs and fetch resources from servers, while integrating advanced HTTP concepts like CORS and other extensions.\n\n## Advantages and disadvantages of AJAX\n\nWhile useful, using AJAX also comes with some considerations. Read more about the [advantages and disadvantages of AJAX](/questions/quiz/what-are-the-advantages-and-disadvantages-of-using-ajax).\n\n## Further reading\n\n- [AJAX | MDN](https://developer.mozilla.org/en-US/docs/Glossary/AJAX)\n- [Fetch API | MDN ](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)\n- [XMLHttpRequest | MDN](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)\n"
  },
  {
    "path": "questions/explain-ajax-in-as-much-detail-as-possible/metadata.json",
    "content": "{\n  \"slug\": \"explain-ajax-in-as-much-detail-as-possible\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"networking\"],\n  \"importance\": \"medium\",\n  \"ranking\": 270,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/explain-ajax-in-as-much-detail-as-possible/pt-BR.mdx",
    "content": "---\ntitle: Explique o Ajax com o máximo de detalhes possível.\n---\n\nAjax (asynchronous JavaScript and XML) é um conjunto de técnicas de desenvolvimento web que utilizam diversas tecnologias web no lado do cliente para criar aplicações web assíncronas. Com o Ajax, as aplicações web podem enviar dados para e receber do servidor de forma assíncrona (em segundo plano) sem interferir na exibição e comportamento da página existente. Ao separar a camada de intercâmbio de dados da camada de apresentação, o Ajax permite que páginas web, e por extensão, aplicações web, alterem o conteúdo dinamicamente sem precisar recarregar toda a página. Na prática, implementações modernas comumente usam JSON em vez de XML, devido às vantagens de o JSON ser nativo ao JavaScript.\n\nA API `XMLHttpRequest` é frequentemente usada para a comunicação assíncrona ou hoje em dia, a API fetch.\n"
  },
  {
    "path": "questions/explain-ajax-in-as-much-detail-as-possible/zh-CN.mdx",
    "content": "---\ntitle: 尽可能详细地解释 AJAX\n---\n\n## TL;DR\n\nAJAX（异步 JavaScript 和 XML）促进客户端和服务器之间的异步通信，无需重新加载即可实现对网页的动态更新。它使用 `XMLHttpRequest` 或 `fetch()` API 等技术在后台发送和接收数据。在现代 Web 应用程序中，`fetch()` API 更常用于实现 AJAX。\n\n**使用 `XMLHttpRequest`**\n\n```js live\nlet xhr = new XMLHttpRequest();\nxhr.onreadystatechange = function () {\n  if (xhr.readyState === XMLHttpRequest.DONE) {\n    if (xhr.status === 200) {\n      console.log(xhr.responseText);\n    } else {\n      console.error('Request failed: ' + xhr.status);\n    }\n  }\n};\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.send();\n```\n\n**使用 `fetch()`**\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Fetch error:', error));\n```\n\n***\n\n## AJAX（异步 JavaScript 和 XML）\n\nAJAX（异步 JavaScript 和 XML）是一组 Web 开发技术，在客户端使用许多 Web 技术来创建异步 Web 应用程序。与每次用户交互都会触发完全页面重新加载的传统 Web 应用程序不同，使用 AJAX，Web 应用程序可以异步地（在后台）向服务器发送数据并从服务器检索数据，而不会干扰现有页面的显示和行为。通过将数据交换层与表示层分离，AJAX 允许网页（以及扩展的 Web 应用程序）动态更改内容，而无需重新加载整个页面。实际上，由于 JSON 具有 JavaScript 原生的优势，现代实现通常使用 JSON 而不是 XML。\n\n传统上，AJAX 是使用 `XMLHttpRequest` API 实现的，但 `fetch()` API 更适合现代 Web 应用程序，也更容易使用。\n\n## `XMLHttpRequest` API\n\n以下是其使用方式的一个基本示例：\n\n```js live\nlet xhr = new XMLHttpRequest();\nxhr.onreadystatechange = function () {\n  if (xhr.readyState === XMLHttpRequest.DONE) {\n    if (xhr.status === 200) {\n      console.log(xhr.responseText);\n    } else {\n      console.error('Request failed: ' + xhr.status);\n    }\n  }\n};\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.send();\n```\n\n## `fetch()` API\n\n或者，`fetch()` API 提供了一种基于 Promise 的现代方法来发出 AJAX 请求。它在现代 Web 应用程序中更常用。\n\n以下是如何使用它：\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Fetch error:', error));\n```\n\n## AJAX 如何工作？\n\n在现代浏览器中，AJAX 使用 `fetch()` API 而不是 `XMLHTTPRequest` 完成，因此我们将解释 `fetch()` API 的工作原理：\n\n1. **发出请求**：[`fetch()` 函数](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)启动异步请求，从 URL 获取资源。它接受一个强制性参数——要获取的资源的 URL，并可以选择接受第二个参数——一个 `options` 对象，该对象允许使用 HTTP 方法、标头、正文等选项配置 HTTP 请求。\n\n   ```js\n   fetch('https://api.example.com/data', {\n     method: 'GET', // or 'POST', 'PUT', 'DELETE', etc.\n     headers: {\n       'Content-Type': 'application/json',\n     },\n   });\n   ```\n\n2. **返回一个 promise**：`fetch()` 函数返回一个 `Promise`，该 `Promise` 解析为表示来自服务器的响应的 [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) 对象。此 `Promise` 需要使用 `.then()` 或 `async/await` 进行处理。\n\n3. **处理响应**：`Response` 对象提供定义如何处理正文内容的方法，例如 `.json()` 用于解析 JSON 数据，`.text()` 用于纯文本，`.blob()` 用于二进制数据等。\n\n   ```js live\n   fetch('https://jsonplaceholder.typicode.com/todos/1')\n     .then((response) => response.json())\n     .then((data) => console.log(data))\n     .catch((error) => console.error('Error:', error));\n   ```\n\n4. **异步性质** `fetch` API 是异步的，允许浏览器在等待服务器响应时继续执行其他任务。这可以防止阻塞主线程并提供更好的用户体验。当作为[事件循环](/questions/quiz/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue)的一部分执行时，`then()` 和 `catch()` 回调被放入微任务队列中。\n\n5. **请求选项** `fetch()` 的可选第二个参数允许配置请求的各个方面，例如 HTTP 方法、标头、正文、凭据、缓存行为等。\n\n6. **错误处理** 请求期间的错误（例如网络故障或无效响应）通过使用 `.catch()` 方法或带有 `async/await` 的 try/catch 块在 Promise 链中捕获并传播。\n\n`fetch()` API 提供了一种基于 Promise 的现代方法，用于在 JavaScript 中发出 HTTP 请求，取代了旧的 `XMLHttpRequest` API。它提供了一种更简单、更灵活的方式来与 API 交互并从服务器获取资源，同时集成了 CORS 等高级 HTTP 概念和其他扩展。\n\n## AJAX 的优缺点\n\n虽然 AJAX 很有用，但使用它也有一些需要考虑的地方。阅读更多关于 [AJAX 的优缺点](/questions/quiz/what-are-the-advantages-and-disadvantages-of-using-ajax)。\n\n## 延伸阅读\n\n* [AJAX | MDN](https://developer.mozilla.org/en-US/docs/Glossary/AJAX)\n* [Fetch API | MDN ](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)\n* [XMLHttpRequest | MDN](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)\n"
  },
  {
    "path": "questions/explain-event-delegation/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"36f29cf7\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"6d7004ca\",\n        \"33a79d62\",\n        \"9705614a\",\n        \"51d92a31\",\n        \"70951c03\",\n        \"2a7816d0\",\n        \"3818abba\",\n        \"c1c1be40\",\n        \"7c9a41b0\",\n        \"823e3d15\",\n        \"c60d6309\",\n        \"485a1648\",\n        \"1d712abb\",\n        \"3e16f4d8\",\n        \"7c299c53\",\n        \"f4fb21ad\",\n        \"c81ac723\",\n        \"9091bb3f\",\n        \"fb27e876\",\n        \"a27219d8\",\n        \"d97425a1\",\n        \"b5905a85\",\n        \"4688282c\",\n        \"5afea3bd\",\n        \"68b07c90\",\n        \"cd5dd65b\",\n        \"b8ab38ac\",\n        \"dc2a84da\",\n        \"fe9b15aa\",\n        \"2670c799\",\n        \"c7a88171\",\n        \"1f4770e5\",\n        \"b4e3453b\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"6d7004ca\",\n        \"33a79d62\",\n        \"9705614a\",\n        \"51d92a31\",\n        \"70951c03\",\n        \"2a7816d0\",\n        \"3818abba\",\n        \"c1c1be40\",\n        \"7c9a41b0\",\n        \"823e3d15\",\n        \"c60d6309\",\n        \"485a1648\",\n        \"1d712abb\",\n        \"3e16f4d8\",\n        \"7c299c53\",\n        \"f4fb21ad\",\n        \"c81ac723\",\n        \"9091bb3f\",\n        \"fb27e876\",\n        \"a27219d8\",\n        \"d97425a1\",\n        \"b5905a85\",\n        \"4688282c\",\n        \"5afea3bd\",\n        \"68b07c90\",\n        \"cd5dd65b\",\n        \"b8ab38ac\",\n        \"dc2a84da\",\n        \"fe9b15aa\",\n        \"2670c799\",\n        \"c7a88171\",\n        \"1f4770e5\",\n        \"b4e3453b\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-event-delegation/en-US.mdx",
    "content": "---\ntitle: Explain event delegation in JavaScript\n---\n\n## TL;DR\n\nEvent delegation is a technique in JavaScript where a single event listener is attached to a parent element instead of attaching event listeners to multiple child elements. When an event occurs on a child element, the event bubbles up the DOM tree, and the parent element's event listener handles the event based on the target element.\n\nEvent delegation provides the following benefits:\n\n- **Improved performance**: Attaching a single event listener is more efficient than attaching multiple event listeners to individual elements, especially for large or dynamic lists. This reduces memory usage and improves overall performance.\n- **Simplified event handling**: With event delegation, you only need to write the event handling logic once in the parent element's event listener. This makes the code more maintainable and easier to update.\n- **Dynamic element support**: Event delegation automatically handles events for dynamically added or removed elements within the parent element. There's no need to manually attach or remove event listeners when the DOM structure changes\n\nHowever, do note that:\n\n- It is important to identify the target element that triggered the event.\n- Not all events can be delegated because they are not bubbled. Non-bubbling events include: `focus`, `blur`, `scroll`, `mouseenter`, `mouseleave`, `resize`, etc.\n\n---\n\n## Event delegation\n\nEvent delegation is a design pattern in JavaScript used to efficiently manage and handle events on multiple child elements by attaching a single event listener to a common ancestor element. This pattern is particularly valuable in scenarios where you have a large number of similar elements, such as list items, and want to optimize event handling.\n\n## How event delegation works\n\n1. **Attach a listener to a common ancestor**: Instead of attaching individual event listeners to each child element, you attach a single event listener to a common ancestor element higher in the DOM hierarchy.\n1. **Event bubbling**: When an event occurs on a child element, it bubbles up through the DOM tree to the common ancestor element. During this propagation, the event listener on the common ancestor can intercept and handle the event.\n1. **Determine the target**: Within the event listener, you can inspect the event object to identify the actual target of the event (the child element that triggered the event). You can use properties like `event.target` or `event.currentTarget` to determine which specific child element was interacted with.\n1. **Perform action based on target**: Based on the target element, you can perform the desired action or execute code specific to that element. This allows you to handle events for multiple child elements with a single event listener.\n\n## Benefits of event delegation\n\n1. **Efficiency**: Event delegation reduces the number of event listeners, improving memory usage and performance, especially when dealing with a large number of elements.\n1. **Dynamic elements**: It works seamlessly with dynamically added or removed child elements, as the common ancestor continues to listen for events on them.\n\n## Example\n\nHere's a simple example:\n\n```js\n// HTML:\n// <ul id=\"item-list\">\n//   <li>Item 1</li>\n//   <li>Item 2</li>\n//   <li>Item 3</li>\n// </ul>\n\nconst itemList = document.getElementById('item-list');\n\nitemList.addEventListener('click', (event) => {\n  if (event.target.tagName === 'LI') {\n    console.log(`Clicked on ${event.target.textContent}`);\n  }\n});\n```\n\nIn this example, a single click event listener is attached to the `<ul>` element. When a click event occurs on an `<li>` element, the event bubbles up to the `<ul>` element, where the event listener checks the target's tag name to identify whether a list item was clicked. It's crucial to check the identity of the `event.target` as there can be other kinds of elements in the DOM tree.\n\n## Use cases\n\nEvent delegation is commonly used in scenarios like:\n\n### Handling dynamic content in single-page applications\n\n```js\n// HTML:\n// <div id=\"button-container\">\n//   <button>Button 1</button>\n//   <button>Button 2</button>\n// </div>\n// <button id=\"add-button\">Add Button</button>\n\nconst buttonContainer = document.getElementById('button-container');\nconst addButton = document.getElementById('add-button');\n\nbuttonContainer.addEventListener('click', (event) => {\n  if (event.target.tagName === 'BUTTON') {\n    console.log(`Clicked on ${event.target.textContent}`);\n  }\n});\n\naddButton.addEventListener('click', () => {\n  const newButton = document.createElement('button');\n  newButton.textContent = `Button ${buttonContainer.children.length + 1}`;\n  buttonContainer.appendChild(newButton);\n});\n```\n\nIn this example, a `click` event listener is attached to the `<div>` container. When a new button is added dynamically and clicked, the event listener on the container handles the click event.\n\n### Simplifying code by avoiding the need to attach and remove event listeners for elements that change\n\n```js\n// HTML:\n// <form id=\"user-form\">\n//   <input type=\"text\" name=\"username\" placeholder=\"Username\">\n//   <input type=\"email\" name=\"email\" placeholder=\"Email\">\n//   <input type=\"password\" name=\"password\" placeholder=\"Password\">\n// </form>\n\nconst userForm = document.getElementById('user-form');\n\nuserForm.addEventListener('input', (event) => {\n  const { name, value } = event.target;\n  console.log(`Changed ${name}: ${value}`);\n});\n```\n\nIn this example, a single input event listener is attached to the form element. It can respond to input changes for all child input elements, simplifying the code by eliminating the need for individual listeners on each `<input>` element.\n\n## Pitfalls\n\nDo note that event delegation come with certain pitfalls:\n\n- **Incorrect target handling:** Ensure correct identification of the event target to avoid unintended actions.\n- **Not all events can be delegated/bubbled**: Not all events can be delegated because they are not bubbled. Non-bubbling events include: `focus`, `blur`, `scroll`, `mouseenter`, `mouseleave`, `resize`, etc.\n- **Event overhead:** While event delegation is generally more efficient, there needs to be complex logic written within the root event listener to identify the triggering element and respond appropriately. This can introduce overhead and can be potentially more complex if not managed properly.\n\n## Event delegation in JavaScript frameworks\n\nIn [React](https://react.dev/), event handlers are attached to the React root's DOM container into which the React tree is rendered. Even though `onClick` is added to child elements, the actual event listeners are attached to the root DOM node, leveraging event delegation to optimize event handling and improve performance.\n\nWhen an event occurs, React's event listener captures it and determines which React component rendered the target element based on its internal bookkeeping. React then dispatches the event to the appropriate component's event handler by calling the handler function with a synthetic event object. This synthetic event object wraps the native browser event, providing a consistent interface across different browsers and capturing information about the event.\n\nBy using event delegation, React avoids attaching individual event handlers to each component instance, which would create significant overhead, especially for large component trees. Instead, React leverages the browser's native event bubbling mechanism to capture events at the root and distribute them to the appropriate components.\n\n## Further reading\n\n- [MDN Web Docs on Event Delegation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_delegation)\n- [JavaScript.info - Event Delegation](https://javascript.info/event-delegation)\n"
  },
  {
    "path": "questions/explain-event-delegation/metadata.json",
    "content": "{\n  \"slug\": \"explain-event-delegation\",\n  \"languages\": [],\n  \"companies\": [\"linkedin\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 50,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/explain-event-delegation/pt-BR.mdx",
    "content": "---\ntitle: Explique delegação do evento\n---\n\nA delegação de eventos é um conceito fundamental no desenvolvimento web que permite gerenciar e tratar eventos eficientemente em vários elementos filhos, anexando um único ouvinte de eventos a um elemento ancestral comum. Em vez de atribuir ouvintes de eventos a cada elemento filho individualmente, você delega a responsabilidade de lidar com eventos ao elemento pai ou ancestral, que intercepta os eventos à medida que eles sobem na árvore DOM e identifica o alvo do evento.\n\n## Benefícios da delegação de eventos\n\n1. **Eficiência**: A delegação de eventos reduz significativamente o número de ouvintes de eventos em seu código, tornando-o mais eficiente em termos de memória e melhorando o desempenho, especialmente ao lidar com um grande número de elementos semelhantes. Isso resulta em um código mais limpo e de fácil manutenção.\n\n2. **Elementos Dinâmicos**: A delegação de eventos funciona perfeitamente com elementos gerados ou removidos dinamicamente no DOM. Você não precisa anexar ou remover ouvintes de eventos toda vez que novos elementos são adicionados ou removidos. O ouvinte de eventos delegado os trata automaticamente.\n\n## Exemplo\n\nVamos ilustrar a delegação de eventos com um exemplo moderno usando a sintaxe do ES6:\n\n```js\n// HTML:\n// <ul id=\"item-list\">\n//   <li>Item 1</li>\n//   <li>Item 2</li>\n//   <li>Item 3</li>\n// </ul>\n\nconst itemList = document.getElementById('item-list');\n\nitemList.addEventListener('click', (event) => {\n  if (event.target.tagName === 'LI') {\n    console.log(`Clicou em ${event.target.textContent}`);\n  }\n});\n```\n\nNeste exemplo, um único ouvinte de eventos de clique é anexado ao elemento `<ul>`. Quando ocorre um evento de clique em um elemento `<li>`, o evento se propaga até o elemento `<ul>`, onde o ouvinte de eventos verifica o nome da tag do alvo para identificar qual item da lista foi clicado.\n\n## Casos de uso\n\nA delegação de eventos é comumente usada em várias situações, incluindo:\n\n1. Gerenciamento de listas, menus ou tabelas com muitos itens ou linhas.\n1. Manipulação de conteúdo dinâmico em aplicativos de página única.\n1. Simplificação do código, evitando a necessidade de anexar e remover ouvintes de eventos para elementos que mudam.\n\n## Recursos\n\n- [MDN Web Docs sobre Delegação de Eventos](https://developer.mozilla.org/pt-BR/docs/Learn/JavaScript/Building_blocks/Events#event_delegation)\n- [JavaScript.info - Delegação de Eventos](https://javascript.info/event-delegation)\n"
  },
  {
    "path": "questions/explain-event-delegation/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 中的事件委托\n---\n\n## TL;DR\n\n事件委托是 JavaScript 中的一种技术，它将单个事件监听器附加到父元素，而不是将事件监听器附加到多个子元素。当子元素上发生事件时，该事件会冒泡到 DOM 树中，父元素的事件监听器会根据目标元素处理该事件。\n\n事件委托具有以下优点：\n\n* **提高性能**：附加单个事件监听器比将多个事件监听器附加到各个元素更有效，尤其是在处理大型或动态列表时。这减少了内存使用并提高了整体性能。\n* **简化事件处理**：使用事件委托，您只需要在父元素的事件监听器中编写一次事件处理逻辑。这使得代码更易于维护和更新。\n* **动态元素支持**：事件委托会自动处理父元素中动态添加或删除元素的事件。当 DOM 结构发生变化时，无需手动附加或删除事件监听器\n\n但是，请注意：\n\n* 确定触发事件的目标元素非常重要。\n* 并非所有事件都可以被委托，因为它们不会冒泡。不冒泡的事件包括：`focus`、`blur`、`scroll`、`mouseenter`、`mouseleave`、`resize` 等。\n\n***\n\n## 事件委托\n\n事件委托是 JavaScript 中用于通过将单个事件监听器附加到公共祖先元素来有效管理和处理多个子元素上的事件的设计模式。此模式在您有大量相似元素（例如列表项）并希望优化事件处理的场景中特别有价值。\n\n## 事件委托的工作原理\n\n1. **将监听器附加到公共祖先**：您将单个事件监听器附加到 DOM 层次结构中较高的公共祖先元素，而不是将各个事件监听器附加到每个子元素。\n2. **事件冒泡**：当子元素上发生事件时，它会通过 DOM 树冒泡到公共祖先元素。在此传播过程中，公共祖先上的事件监听器可以拦截和处理该事件。\n3. **确定目标**：在事件监听器中，您可以检查事件对象以识别事件的实际目标（触发事件的子元素）。您可以使用 `event.target` 或 `event.currentTarget` 等属性来确定与哪个特定的子元素进行了交互。\n4. **根据目标执行操作**：根据目标元素，您可以执行所需的操作或执行特定于该元素的代码。这允许您使用单个事件监听器处理多个子元素的事件。\n\n## 事件委托的优点\n\n1. **效率**：事件委托减少了事件监听器的数量，从而提高了内存使用率和性能，尤其是在处理大量元素时。\n2. **动态元素**：它可以与动态添加或删除的子元素无缝协作，因为公共祖先会继续侦听它们的事件。\n\n## 例子\n\n这是一个简单的例子：\n\n```js\n// HTML:\n// <ul id=\"item-list\">\n//   <li>Item 1</li>\n//   <li>Item 2</li>\n//   <li>Item 3</li>\n// </ul>\n\nconst itemList = document.getElementById('item-list');\n\nitemList.addEventListener('click', (event) => {\n  if (event.target.tagName === 'LI') {\n    console.log(`Clicked on ${event.target.textContent}`);\n  }\n});\n```\n\n在此示例中，单个 click 事件监听器附加到 `<ul>` 元素。当 `<li>` 元素上发生 click 事件时，该事件会冒泡到 `<ul>` 元素，事件监听器会检查目标元素的标签名称以确定是否单击了列表项。检查 `event.target` 的身份至关重要，因为 DOM 树中可能存在其他类型的元素。\n\n## 用例\n\n事件委托通常用于以下场景：\n\n### 处理单页应用程序中的动态内容\n\n```js\n// HTML:\n// <div id=\"button-container\">\n//   <button>Button 1</button>\n//   <button>Button 2</button>\n// </div>\n// <button id=\"add-button\">Add Button</button>\n\nconst buttonContainer = document.getElementById('button-container');\nconst addButton = document.getElementById('add-button');\n\nbuttonContainer.addEventListener('click', (event) => {\n  if (event.target.tagName === 'BUTTON') {\n    console.log(`Clicked on ${event.target.textContent}`);\n  }\n});\n\naddButton.addEventListener('click', () => {\n  const newButton = document.createElement('button');\n  newButton.textContent = `Button ${buttonContainer.children.length + 1}`;\n  buttonContainer.appendChild(newButton);\n});\n```\n\n在此示例中，`click` 事件侦听器附加到 `<div>` 容器。 当动态添加并单击一个新按钮时，容器上的事件侦听器会处理 click 事件。\n\n### 通过避免为更改的元素附加和删除事件侦听器来简化代码\n\n```js\n// HTML:\n// <form id=\"user-form\">\n//   <input type=\"text\" name=\"username\" placeholder=\"Username\">\n//   <input type=\"email\" name=\"email\" placeholder=\"Email\">\n//   <input type=\"password\" name=\"password\" placeholder=\"Password\">\n// </form>\n\nconst userForm = document.getElementById('user-form');\n\nuserForm.addEventListener('input', (event) => {\n  const { name, value } = event.target;\n  console.log(`Changed ${name}: ${value}`);\n});\n```\n\n在这个例子中，单个输入事件监听器附加到表单元素。它可以响应所有子输入元素的输入更改，通过消除对每个`<input>`元素上单独监听器的需求来简化代码。\n\n## 陷阱\n\n请注意，事件委托会带来某些陷阱：\n\n* **目标处理不正确：** 确保正确识别事件目标，以避免意外操作。\n* **并非所有事件都可以委托/冒泡**：并非所有事件都可以委托，因为它们不会冒泡。 不冒泡的事件包括：`focus`、`blur`、`scroll`、`mouseenter`、`mouseleave`、`resize` 等。\n* **事件开销：** 虽然事件委托通常更有效，但需要在根事件侦听器中编写复杂的逻辑来识别触发元素并做出适当的响应。 如果管理不当，这可能会引入开销，并且可能更复杂。\n\n## JavaScript 框架中的事件委托\n\n在 [React](https://react.dev/) 中，事件处理程序附加到 React 根的 DOM 容器中，React 树被渲染到该容器中。 即使将 `onClick` 添加到子元素，实际的事件侦听器也会附加到根 DOM 节点，利用事件委托来优化事件处理并提高性能。\n\n当事件发生时，React 的事件侦听器会捕获它，并根据其内部簿记确定哪个 React 组件呈现了目标元素。 然后，React 通过使用合成事件对象调用处理程序函数，将事件分派给相应的组件的事件处理程序。 此合成事件对象包装了本机浏览器事件，提供了跨不同浏览器的一致接口，并捕获了有关事件的信息。\n\n通过使用事件委托，React 避免将单个事件处理程序附加到每个组件实例，这将产生巨大的开销，尤其对于大型组件树。 相反，React 利用浏览器的本机事件冒泡机制来捕获根处的事件并将它们分发到相应的组件。\n\n## 延伸阅读\n\n* [MDN Web Docs on Event Delegation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_delegation)\n* [JavaScript.info - Event Delegation](https://javascript.info/event-delegation)\n"
  },
  {
    "path": "questions/explain-function-prototype-bind/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"9152cbf3\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"b96bce3\",\n        \"68b9e64f\",\n        \"c6372431\",\n        \"2a7816d0\",\n        \"5a40ece9\",\n        \"2de811f4\",\n        \"d719bcd1\",\n        \"921441c1\",\n        \"a9925b37\",\n        \"3998cea5\",\n        \"c81ac723\",\n        \"f33c9db3\",\n        \"4e4dcd5f\",\n        \"b34abb70\",\n        \"74012c82\",\n        \"4958109e\",\n        \"cddb6bbf\",\n        \"426a14ba\",\n        \"b983455b\",\n        \"7945b3c\",\n        \"9bf3c015\",\n        \"a7dd80b8\",\n        \"55b481e7\",\n        \"45da4e57\",\n        \"6b60e315\",\n        \"ee9c1eea\",\n        \"4bd0132\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"b96bce3\",\n        \"68b9e64f\",\n        \"c6372431\",\n        \"2a7816d0\",\n        \"5a40ece9\",\n        \"2de811f4\",\n        \"d719bcd1\",\n        \"921441c1\",\n        \"a9925b37\",\n        \"3998cea5\",\n        \"c81ac723\",\n        \"f33c9db3\",\n        \"4e4dcd5f\",\n        \"b34abb70\",\n        \"74012c82\",\n        \"4958109e\",\n        \"cddb6bbf\",\n        \"426a14ba\",\n        \"b983455b\",\n        \"7945b3c\",\n        \"9bf3c015\",\n        \"a7dd80b8\",\n        \"55b481e7\",\n        \"45da4e57\",\n        \"6b60e315\",\n        \"ee9c1eea\",\n        \"4bd0132\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-function-prototype-bind/en-US.mdx",
    "content": "---\ntitle: Explain `Function.prototype.bind` in JavaScript\n---\n\n## TL;DR\n\n`Function.prototype.bind` is a method in JavaScript that allows you to create a new function with a specific `this` value and optional initial arguments. It's primary purpose is to:\n\n- **Binding `this` value to preserve context**: The primary purpose of `bind` is to bind the `this` value of a function to a specific object. When you call `func.bind(thisArg)`, it creates a new function with the same body as `func`, but with `this` permanently bound to `thisArg`.\n- **Partial application of arguments**: `bind` also allows you to pre-specify arguments for the new function. Any arguments passed to `bind` after `thisArg` will be prepended to the arguments list when the new function is called.\n- **Method borrowing**: `bind` allows you to borrow methods from one object and apply them to another object, even if they were not originally designed to work with that object.\n\nThe `bind` method is particularly useful in scenarios where you need to ensure that a function is called with a specific `this` context, such as in event handlers, callbacks, or method borrowing.\n\n---\n\n## `Function.prototype.bind`\n\n`Function.prototype.bind` allows you to create a new function with a specific `this` context and, optionally, preset arguments. `bind()` is most useful for preserving the value of `this` in methods of classes that you want to pass into other functions.\n\n`bind` was frequently used on legacy React class component methods which were not defined using arrow functions.\n\n```js live\nconst john = {\n  age: 42,\n  getAge: function () {\n    return this.age;\n  },\n};\n\nconsole.log(john.getAge()); // 42\n\nconst unboundGetAge = john.getAge;\nconsole.log(unboundGetAge()); // undefined\n\nconst boundGetAge = john.getAge.bind(john);\nconsole.log(boundGetAge()); // 42\n\nconst mary = { age: 21 };\nconst boundGetAgeMary = john.getAge.bind(mary);\nconsole.log(boundGetAgeMary()); // 21\n```\n\nIn the example above, when the `getAge` method is called without a calling object (as `unboundGetAge`), the value is `undefined` because the value of `this` within `getAge()` becomes the global object. `boundGetAge()` has its `this` bound to `john`, hence it is able to obtain the `age` of `john`.\n\nWe can even use `getAge` on another object which is not `john`! `boundGetAgeMary` returns the `age` of `mary`.\n\n## Use cases\n\nHere are some common scenarios where `bind` is frequently used:\n\n### Preserving context and fixing the `this` value in callbacks\n\nWhen you pass a function as a callback, the `this` value inside the function can be unpredictable because it is determined by the execution context. Using `bind()` helps ensure that the correct `this` value is maintained.\n\n```js live\nclass Person {\n  constructor(firstName) {\n    this.firstName = firstName;\n  }\n  greet() {\n    console.log(`Hello, my name is ${this.firstName}`);\n  }\n}\n\nconst john = new Person('John');\n\n// Without bind(), `this` inside the callback will be the global object\nsetTimeout(john.greet, 1000); // Output: \"Hello, my name is undefined\"\n\n// Using bind() to fix the `this` value\nsetTimeout(john.greet.bind(john), 2000); // Output: \"Hello, my name is John\"\n```\n\nYou can also use [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) to define class methods for this purpose instead of using `bind`. Arrow functions have the `this` value bound to its lexical context.\n\n```js live\nclass Person {\n  constructor(name) {\n    this.name = name;\n  }\n  greet = () => {\n    console.log(`Hello, my name is ${this.name}`);\n  };\n}\n\nconst john = new Person('John Doe');\nsetTimeout(john.greet, 1000); // Output: \"Hello, my name is John Doe\"\n```\n\n### Partial application of functions (currying)\n\n`bind` can be used to create a new function with some arguments pre-set. This is known as partial application or currying.\n\n```js live\nfunction multiply(a, b) {\n  return a * b;\n}\n\n// Using bind() to create a new function with some arguments pre-set\nconst multiplyBy5 = multiply.bind(null, 5);\nconsole.log(multiplyBy5(3)); // Output: 15\n```\n\n### Method borrowing\n\n`bind` allows you to borrow methods from one object and apply them to another object, even if they were not originally designed to work with that object. This can be handy when you need to reuse functionality across different objects\n\n```js live\nconst person = {\n  name: 'John',\n  greet: function () {\n    console.log(`Hello, ${this.name}!`);\n  },\n};\n\nconst greetPerson = person.greet.bind({ name: 'Alice' });\ngreetPerson(); // Output: Hello, Alice!\n```\n\n## Practice\n\nTry [implementing your own `Function.prototype.bind()` method](/questions/javascript/function-bind) on GreatFrontEnd.\n\n## Further Reading\n\n- [Function.prototype.bind() - JavaScript | MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind)\n- [Function Binding | javascript.info](https://javascript.info/bind)\n"
  },
  {
    "path": "questions/explain-function-prototype-bind/metadata.json",
    "content": "{\n  \"slug\": \"explain-function-prototype-bind\",\n  \"languages\": [],\n  \"companies\": [\"atlassian\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"high\",\n  \"ranking\": 110,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/explain-function-prototype-bind/pt-BR.mdx",
    "content": "---\ntitle: Explique `Function.prototype.bind`\n---\n\n> O método `bind()` cria uma nova função que, quando chamada, tem sua palavra-chave `this` definida para o valor fornecido, com uma determinada sequência de argumentos precedendo qualquer um fornecido quando a nova função é chamada.\n\n_Source: [Function.prototype.bind() - JavaScript | MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind)_\n\n`bind()` é mais útil para vincular o valor do `this` em métodos de classes que você quer passar para outras funções. Isso foi frequentemente feito em métodos de classe de componente React que não foram definidos usando arrow functions.\n\n```js\nconst john = {\n  age: 42,\n  getAge: function () {\n    return this.age;\n  },\n};\n\nconsole.log(john.getAge()); // 42\n\nconst unboundGetAge = john.getAge;\nconsole.log(unboundGetAge()); // undefined\n\nconst boundGetAge = john.getAge.bind(john);\nconsole.log(boundGetAge()); // 42\n\nconst mary = { age: 21 };\nconst boundGetAgeMary = john.getAge.bind(mary);\nconsole.log(boundGetAgeMary()); // 21\n```\n\nNo exemplo acima, quando o método `getAge` é chamado sem um objeto chamado (como `unboundGetAge`), o valor é 'indefinido' porque o valor 'this' dentro de `getAge()` se torna o objeto global. `boundGetAge()` tem seu `this` ligado a `john`, portanto pode obter o `idade` de `john`.\n\nPodemos até usar `getAge` em outro objeto que não é `john`! `boundGetAgeMary` retorna o `age` (idade) de `mary`.\n\n## Prática\n\nTente [implementar seu próprio método `Function.prototype.bind()`](/questions/javascript/function-bind) na Great Front End.\n\n## Referências\n\n- [Function.prototype.bind() - JavaScript | MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind)\n"
  },
  {
    "path": "questions/explain-function-prototype-bind/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 中的 `Function.prototype.bind`\n---\n\n## TL;DR\n\n`Function.prototype.bind` 是 JavaScript 中的一个方法，它允许你创建一个新函数，该函数具有特定的 `this` 值和可选的初始参数。它的主要目的是：\n\n* **绑定 `this` 值以保留上下文**：`bind` 的主要目的是将函数的 `this` 值绑定到特定的对象。当你调用 `func.bind(thisArg)` 时，它会创建一个与 `func` 具有相同主体的的新函数，但 `this` 永久绑定到 `thisArg`。\n* **部分应用参数**：`bind` 还允许你为新函数预先指定参数。传递给 `bind` 的任何参数（在 `thisArg` 之后）都将在调用新函数时添加到参数列表的前面。\n* **方法借用**：`bind` 允许你从一个对象借用方法并将其应用于另一个对象，即使它们最初并非设计为与该对象一起使用。\n\n`bind` 方法在需要确保使用特定的 `this` 上下文调用函数的情况下特别有用，例如在事件处理程序、回调或方法借用中。\n\n***\n\n## `Function.prototype.bind`\n\n`Function.prototype.bind` 允许你创建一个具有特定 `this` 上下文的新函数，以及可选的预设参数。`bind()` 对于在要传递给其他函数的类方法中保留 `this` 的值非常有用。\n\n`bind` 经常用于旧版 React 类组件方法，这些方法不是使用箭头函数定义的。\n\n```js live\nconst john = {\n  age: 42,\n  getAge: function () {\n    return this.age;\n  },\n};\n\nconsole.log(john.getAge()); // 42\n\nconst unboundGetAge = john.getAge;\nconsole.log(unboundGetAge()); // undefined\n\nconst boundGetAge = john.getAge.bind(john);\nconsole.log(boundGetAge()); // 42\n\nconst mary = { age: 21 };\nconst boundGetAgeMary = john.getAge.bind(mary);\nconsole.log(boundGetAgeMary()); // 21\n```\n\n在上面的例子中，当 `getAge` 方法在没有调用对象（作为 `unboundGetAge`）的情况下被调用时，该值为 `undefined`，因为 `getAge()` 中的 `this` 的值变为全局对象。`boundGetAge()` 的 `this` 绑定到 `john`，因此它能够获取 `john` 的 `age`。\n\n我们甚至可以在另一个不是 `john` 的对象上使用 `getAge`！`boundGetAgeMary` 返回 `mary` 的 `age`。\n\n## 用例\n\n以下是经常使用 `bind` 的一些常见场景：\n\n### 在回调中保留上下文并修复 `this` 值\n\n当你将一个函数作为回调传递时，函数内部的 `this` 值可能无法预测，因为它由执行上下文决定。使用 `bind()` 有助于确保维护正确的 `this` 值。\n\n```js live\nclass Person {\n  constructor(firstName) {\n    this.firstName = firstName;\n  }\n  greet() {\n    console.log(`Hello, my name is ${this.firstName}`);\n  }\n}\n\nconst john = new Person('John');\n\n// Without bind(), `this` inside the callback will be the global object\nsetTimeout(john.greet, 1000); // Output: \"Hello, my name is undefined\"\n\n// Using bind() to fix the `this` value\nsetTimeout(john.greet.bind(john), 2000); // Output: \"Hello, my name is John\"\n```\n\n你也可以使用 [箭头函数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) 来定义类方法，而不是使用 `bind`。箭头函数将 `this` 值绑定到其词法上下文。\n\n```js live\nclass Person {\n  constructor(name) {\n    this.name = name;\n  }\n  greet = () => {\n    console.log(`Hello, my name is ${this.name}`);\n  };\n}\n\nconst john = new Person('John Doe');\nsetTimeout(john.greet, 1000); // Output: \"Hello, my name is John Doe\"\n```\n\n### 函数的部分应用（柯里化）\n\n`bind` 可以用来创建一个新函数，其中预先设置了一些参数。这被称为部分应用或柯里化。\n\n```js live\nfunction multiply(a, b) {\n  return a * b;\n}\n\n// 使用 bind() 创建一个新函数，其中预先设置了一些参数\nconst multiplyBy5 = multiply.bind(null, 5);\nconsole.log(multiplyBy5(3)); // Output: 15\n```\n\n### 方法借用\n\n`bind` 允许你从一个对象借用方法并将它们应用于另一个对象，即使它们最初不是为该对象设计的。当你需要在不同对象之间重用功能时，这会很有用\n\n```js live\nconst person = {\n  name: 'John',\n  greet: function () {\n    console.log(`Hello, ${this.name}!`);\n  },\n};\n\nconst greetPerson = person.greet.bind({ name: 'Alice' });\ngreetPerson(); // Output: Hello, Alice!\n```\n\n## 练习\n\n尝试在 GreatFrontEnd 上[实现你自己的 `Function.prototype.bind()` 方法](/questions/javascript/function-bind)。\n\n## 延伸阅读\n\n* [Function.prototype.bind() - JavaScript | MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind)\n* [Function Binding | javascript.info](https://javascript.info/bind)\n"
  },
  {
    "path": "questions/explain-hoisting/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"aeb58a5c\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"804794dd\",\n        \"168e6e39\",\n        \"316af5e0\",\n        \"d4eff71f\",\n        \"2a7816d0\",\n        \"7763dd73\",\n        \"b2550f45\",\n        \"840fdb2\",\n        \"c6d7bc32\",\n        \"d695a243\",\n        \"a7ad58ab\",\n        \"dbb12e59\",\n        \"18386894\",\n        \"e57f0051\",\n        \"ad972e07\",\n        \"3cc2814c\",\n        \"f5aa5b10\",\n        \"52cda30a\",\n        \"3b2df69c\",\n        \"e377b469\",\n        \"359e36e6\",\n        \"bff451a8\",\n        \"128d61d8\",\n        \"55a4f808\",\n        \"7ef0aca3\",\n        \"788be196\",\n        \"5113831d\",\n        \"d37a8add\",\n        \"63a6f868\",\n        \"240cdb8a\",\n        \"3174b2f2\",\n        \"41433774\",\n        \"cd4660b2\",\n        \"133cc421\",\n        \"7933da41\",\n        \"282a9481\",\n        \"11487978\",\n        \"b1f06233\",\n        \"b9a03b4e\",\n        \"c314f8b\",\n        \"1f4770e5\",\n        \"8d801c81\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"804794dd\",\n        \"168e6e39\",\n        \"316af5e0\",\n        \"d4eff71f\",\n        \"2a7816d0\",\n        \"7763dd73\",\n        \"b2550f45\",\n        \"840fdb2\",\n        \"c6d7bc32\",\n        \"d695a243\",\n        \"a7ad58ab\",\n        \"dbb12e59\",\n        \"18386894\",\n        \"e57f0051\",\n        \"ad972e07\",\n        \"3cc2814c\",\n        \"f5aa5b10\",\n        \"52cda30a\",\n        \"3b2df69c\",\n        \"e377b469\",\n        \"359e36e6\",\n        \"bff451a8\",\n        \"128d61d8\",\n        \"55a4f808\",\n        \"7ef0aca3\",\n        \"788be196\",\n        \"5113831d\",\n        \"d37a8add\",\n        \"63a6f868\",\n        \"240cdb8a\",\n        \"3174b2f2\",\n        \"41433774\",\n        \"cd4660b2\",\n        \"133cc421\",\n        \"7933da41\",\n        \"282a9481\",\n        \"11487978\",\n        \"b1f06233\",\n        \"b9a03b4e\",\n        \"c314f8b\",\n        \"1f4770e5\",\n        \"8d801c81\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-hoisting/en-US.mdx",
    "content": "---\ntitle: Explain the concept of \"hoisting\" in JavaScript\n---\n\n## TL;DR\n\nHoisting is a JavaScript mechanism where variable and function declarations are moved (\"hoisted\") to the top of their containing scope during the compile phase.\n\n- **Variable declarations (`var`)**: Declarations are hoisted, but not initializations. The value of the variable is `undefined` if accessed before initialization.\n- **Variable declarations (`let` and `const`)**: Declarations are hoisted, but not initialized. Accessing them results in `ReferenceError` until the actual declaration is encountered.\n- **Function expressions (`var`)**: Declarations are hoisted, but not initializations. The value of the variable is `undefined` if accessed before initialization.\n- **Function declarations (`function`)**: Both declaration and definition are fully hoisted.\n- **Class declarations (`class`)**: Declarations are hoisted, but not initialized. Accessing them results in `ReferenceError` until the actual declaration is encountered.\n- **Import declarations (`import`)**: Declarations are hoisted, and side effects of importing the module are executed before the rest of the code.\n\nThe following behavior summarizes the result of accessing the variables before they are declared.\n\n| Declaration                    | Accessing before declaration |\n| ------------------------------ | ---------------------------- |\n| `var foo`                      | `undefined`                  |\n| `let foo`                      | `ReferenceError`             |\n| `const foo`                    | `ReferenceError`             |\n| `class Foo`                    | `ReferenceError`             |\n| `var foo = function() { ... }` | `undefined`                  |\n| `function foo() { ... }`       | Normal                       |\n| `import`                       | Normal                       |\n\n---\n\n## Hoisting\n\nHoisting is a term used to explain the behavior of variable declarations in JavaScript code.\n\nVariables declared or initialized with the `var` keyword will have their declaration \"moved\" up to the top of their containing scope during compilation, which we refer to as hoisting.\n\nOnly the declaration is hoisted, the initialization/assignment (if there is one), will stay where it is. Note that the declaration is not actually moved – the JavaScript engine parses the declarations during compilation and becomes aware of variables and their scopes, but it is easier to understand this behavior by visualizing the declarations as being \"hoisted\" to the top of their scope.\n\nLet's explain with a few code samples. Note that the code for these examples should be executed within a module scope instead of being entered line by line into a REPL like the browser console.\n\n### Hoisting of variables declared using `var`\n\nHoisting is seen in action here as even though `foo` is declared and initialized after the first `console.log()`, the first `console.log()` prints the value of `foo` as `undefined`.\n\n```js live\nconsole.log(foo); // undefined\nvar foo = 1;\nconsole.log(foo); // 1\n```\n\nYou can visualize the code as:\n\n```js live\nvar foo;\nconsole.log(foo); // undefined\nfoo = 1;\nconsole.log(foo); // 1\n```\n\n### Hoisting of variables declared using `let`, `const`, and `class`\n\nVariables declared via `let`, `const`, and `class` are hoisted as well. However, unlike `var` and `function`, they are not initialized and accessing them before the declaration will result in a `ReferenceError` exception. The variable is in a \"temporal dead zone\" from the start of the block until the declaration is processed.\n\n```js live\ny; // ReferenceError: Cannot access 'y' before initialization\nlet y = 'local';\n```\n\n```js live\nz; // ReferenceError: Cannot access 'z' before initialization\nconst z = 'local';\n```\n\n```js live\nFoo; // ReferenceError: Cannot access 'Foo' before initialization\n\nclass Foo {\n  constructor() {}\n}\n```\n\n### Hoisting of function expressions\n\nFunction expressions are functions written in the form of variable declarations. Since they are also declared using `var`, only the variable declaration is hoisted.\n\n```js live\nconsole.log(bar); // undefined\nbar(); // Uncaught TypeError: bar is not a function\n\nvar bar = function () {\n  console.log('BARRRR');\n};\n```\n\n### Hoisting of function declarations\n\nFunction declarations use the `function` keyword. Unlike function expressions, function declarations have both the declaration and definition hoisted, thus they can be called even before they are declared.\n\n```js live\nconsole.log(foo); // [Function: foo]\nfoo(); // 'FOOOOO'\n\nfunction foo() {\n  console.log('FOOOOO');\n}\n```\n\nThe same applies to generators (`function*`), async functions (`async function`), and async function generators (`async function*`).\n\n### Hoisting of `import` statements\n\nImport declarations are hoisted. The identifiers the imports introduce are available in the entire module scope, and their side effects are produced before the rest of the module's code runs.\n\n```js\nfoo.doSomething(); // Works normally.\n\nimport foo from './modules/foo';\n```\n\n## Under the hood\n\nIn reality, JavaScript creates all variables in the current scope before it even tries to execute the code. Variables created using `var` keyword will have the value of `undefined` where variables created using `let` and `const` keywords will be marked as `<value unavailable>`. Thus, accessing them will cause a `ReferenceError` preventing you to access them before initialization.\n\nIn ECMAScript specifications `let` and `const` declarations are [explained as below](https://tc39.es/ecma262/#sec-let-and-const-declarations):\n\n> The variables are created when their containing Environment Record is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated.\n\nHowever, this statement is [a little different for the `var` keyword](https://tc39.es/ecma262/#sec-variable-statement):\n\n> Var variables are created when their containing Environment Record is instantiated and are initialized to `undefined` when created.\n\n## Modern practices\n\nIn practice, modern code bases avoid using `var` and use `let` and `const` exclusively. It is recommended to declare and initialize your variables and import statements at the top of the containing scope/module to eliminate the mental overhead of tracking when a variable can be used.\n\nESLint is a static code analyzer that can find violations of such cases with the following rules:\n\n- [`no-use-before-define`](https://eslint.org/docs/latest/rules/no-use-before-define): This rule will warn when it encounters a reference to an identifier that has not yet been declared.\n- [`no-undef`](https://eslint.org/docs/latest/rules/no-undef): This rule will warn when it encounters a reference to an identifier that has not yet been declared.\n\n## Further reading\n\n- [Hoisting | MDN](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)\n- [What is Hoisting in JavaScript?](https://www.freecodecamp.org/news/what-is-hoisting-in-javascript)\n"
  },
  {
    "path": "questions/explain-hoisting/metadata.json",
    "content": "{\n  \"slug\": \"explain-hoisting\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 10,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/explain-hoisting/pt-BR.mdx",
    "content": "---\ntitle: Explique \"hoisting\"\n---\n\nHoisting é um termo usado para explicar o comportamento de declarações variáveis em seu código. Variáveis declaradas ou inicializadas com a palavra-chave `var` terão sua declaração \"movida\" até o topo do escopo do módulo/função do escopo, a que chamamos de hoisting. No entanto, apenas a declaração está hoisted, a atribuição (se houver uma), ficará onde está.\n\nObserve que a declaração não é realmente movida - o motor de JavaScript analisa as declarações durante a compilação e torna-se ciente das declarações e dos seus âmbitos. É mais fácil compreender este comportamento, visualizando as declarações como sendo hoisted até ao topo do seu escopo. Vamos explicar com alguns exemplos.\n\n```js\nconsole.log(foo); // indefinido\nvar foo = 1;\nconsole.log(foo); // 1\n```\n\nAs declarações de função têm o corpo hoisted enquanto as expressões da função (escritas na forma de declarações variáveis) só tem a declaração da variável hoisted.\n\n```js\n// Declaração de função\nconsole.log(foo); // [Function: foo]\nfoo(); // 'FOOOOO'\nfunction foo() {\n  console.log('FOOOOO');\n}\nconsole.log(foo); // [Function: foo]\n\n// Function Expression\nconsole.log(bar); // undefined\nbar(); // Uncaught TypeError: bar is not a function\nvar bar = function () {\n  console.log('BARRRR');\n};\nconsole.log(bar); // [Function: bar]\n```\n\nVariáveis declaradas via `let` e `const` também sofrem o hoisted. No entanto, ao contrário de `var` e `function`, eles não são inicializados e acessá-los antes que a declaração resulte em uma exceção `ReferenceError`. A variável está em uma \"zona temporária morta\" desde o início do bloco até que a declaração seja processada.\n\n```js\nx; // undefined; // Erro de referência: y não está definido\n\nvar x = 'local';\nlet y = 'local';\n```\n"
  },
  {
    "path": "questions/explain-hoisting/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 中的“hoisting”（变量提升）概念\n---\n\n## TL;DR\n\nHoisting（变量提升）是一种 JavaScript 机制，在编译阶段，变量和函数声明会被“提升”到其包含作用域的顶部。\n\n* **变量声明 (`var`)**：声明被提升，但未初始化。如果在使用前访问变量，则变量的值为 `undefined`。\n* **变量声明 (`let` 和 `const`)**：声明被提升，但未初始化。访问它们会导致 `ReferenceError`，直到遇到实际的声明。\n* **函数表达式 (`var`)**：声明被提升，但未初始化。如果在使用前访问变量，则变量的值为 `undefined`。\n* **函数声明 (`function`)**：声明和定义都被完全提升。\n* **类声明 (`class`)**：声明被提升，但未初始化。访问它们会导致 `ReferenceError`，直到遇到实际的声明。\n* **导入声明 (`import`)**：声明被提升，并且在执行其余代码之前，会执行导入模块的副作用。\n\n以下行为总结了在声明变量之前访问变量的结果。\n\n| 声明 | 在声明之前访问 |\n| ------------------------------ | ---------------------------- |\n| `var foo` | `undefined` |\n| `let foo` | `ReferenceError` |\n| `const foo` | `ReferenceError` |\n| `class Foo` | `ReferenceError` |\n| `var foo = function() { ... }` | `undefined` |\n| `function foo() { ... }` | 正常 |\n| `import` | 正常 |\n\n***\n\n## Hoisting（变量提升）\n\nHoisting（变量提升）是一个术语，用于解释 JavaScript 代码中变量声明的行为。\n\n使用 `var` 关键字声明或初始化的变量将在编译期间将其声明“移动”到其包含作用域的顶部，我们将其称为变量提升。\n\n只有声明被提升，初始化/赋值（如果存在）将保留在原来的位置。请注意，声明实际上并没有移动——JavaScript 引擎在编译期间会解析声明，并了解变量及其作用域，但是通过将声明可视化为“提升”到其作用域的顶部，更容易理解这种行为。\n\n让我们用几个代码示例来解释。请注意，这些示例的代码应该在模块作用域内执行，而不是像浏览器控制台那样逐行输入到 REPL 中。\n\n### 使用 `var` 声明的变量的变量提升\n\n在这里可以看到变量提升的实际效果，即使在第一个 `console.log()` 之后才声明和初始化 `foo`，第一个 `console.log()` 也会将 `foo` 的值打印为 `undefined`。\n\n```js live\nconsole.log(foo); // undefined\nvar foo = 1;\nconsole.log(foo); // 1\n```\n\n您可以将代码可视化为：\n\n```js live\nvar foo;\nconsole.log(foo); // undefined\nfoo = 1;\nconsole.log(foo); // 1\n```\n\n### 使用 `let`、`const` 和 `class` 声明的变量的变量提升\n\n通过 `let`、`const` 和 `class` 声明的变量也会被提升。但是，与 `var` 和 `function` 不同，它们没有被初始化，在声明之前访问它们将导致 `ReferenceError` 异常。该变量处于一个“暂时性死区”，从块的开始到声明被处理。\n\n```js live\ny; // ReferenceError: Cannot access 'y' before initialization\nlet y = 'local';\n```\n\n```js live\nz; // ReferenceError: Cannot access 'z' before initialization\nconst z = 'local';\n```\n\n```js live\nFoo; // ReferenceError: Cannot access 'Foo' before initialization\n\nclass Foo {\n  constructor() {}\n}\n```\n\n### 函数表达式的提升\n\n函数表达式是以变量声明的形式编写的函数。由于它们也是使用 `var` 声明的，因此只有变量声明被提升。\n\n```js live\nconsole.log(bar); // undefined\nbar(); // Uncaught TypeError: bar is not a function\n\nvar bar = function () {\n  console.log('BARRRR');\n};\n```\n\n### 函数声明的提升\n\n函数声明使用 `function` 关键字。与函数表达式不同，函数声明同时提升声明和定义，因此即使在声明之前也可以调用它们。\n\n```js live\nconsole.log(foo); // [Function: foo]\nfoo(); // 'FOOOOO'\n\nfunction foo() {\n  console.log('FOOOOO');\n}\n```\n\n这同样适用于生成器 (`function*`)、异步函数 (`async function`) 和异步函数生成器 (`async function*`)。\n\n### `import` 语句的提升\n\nImport 声明被提升。import 引入的标识符在整个模块范围内都可用，并且它们产生的副作用在模块的其余代码运行之前产生。\n\n```js\nfoo.doSomething(); // Works normally.\n\nimport foo from './modules/foo';\n```\n\n## 幕后\n\n实际上，JavaScript 在尝试执行代码之前，会在当前作用域中创建所有变量。使用 `var` 关键字创建的变量的值将为 `undefined`，而使用 `let` 和 `const` 关键字创建的变量将被标记为 `<value unavailable>`。因此，在初始化之前访问它们将导致 `ReferenceError`，从而阻止您在初始化之前访问它们。\n\n在 ECMAScript 规范中，`let` 和 `const` 声明[解释如下](https://tc39.es/ecma262/#sec-let-and-const-declarations)：\n\n> 当它们包含的 Environment Record 被实例化时，变量被创建，但在变量的 LexicalBinding 被求值之前，可能无法以任何方式访问它们。\n\n但是，对于 `var` 关键字，此语句[略有不同](https://tc39.es/ecma262/#sec-variable-statement)：\n\n> 当它们包含的 Environment Record 被实例化时，Var 变量被创建，并在创建时被初始化为 `undefined`。\n\n## 现代实践\n\n在实践中，现代代码库避免使用 `var`，并且仅使用 `let` 和 `const`。建议在包含范围/模块的顶部声明和初始化变量和 import 语句，以消除跟踪何时可以使用变量的心理负担。\n\nESLint 是一个静态代码分析器，可以发现违反此类情况，使用以下规则：\n\n* [`no-use-before-define`](https://eslint.org/docs/latest/rules/no-use-before-define): 当遇到对尚未声明的标识符的引用时，此规则将发出警告。\n* [`no-undef`](https://eslint.org/docs/latest/rules/no-undef): 当遇到对尚未声明的标识符的引用时，此规则将发出警告。\n\n## 延伸阅读\n\n* [Hoisting | MDN](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)\n* [What is Hoisting in JavaScript?](https://www.freecodecamp.org/news/what-is-hoisting-in-javascript)\n"
  },
  {
    "path": "questions/explain-how-jsonp-works-and-how-its-not-really-ajax/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"4c1c525c\",\n        \"2a7816d0\",\n        \"a094b193\",\n        \"c01a4a78\",\n        \"282ab080\",\n        \"b0aaf596\",\n        \"98ceba85\",\n        \"da738909\",\n        \"9920f083\",\n        \"92c0c419\",\n        \"8c93a3b\",\n        \"8839d5cc\",\n        \"971fcc89\",\n        \"f9fa7113\",\n        \"4f06bc53\",\n        \"1f4770e5\",\n        \"d45e7c5b\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4c1c525c\",\n        \"2a7816d0\",\n        \"a094b193\",\n        \"c01a4a78\",\n        \"282ab080\",\n        \"b0aaf596\",\n        \"98ceba85\",\n        \"da738909\",\n        \"9920f083\",\n        \"92c0c419\",\n        \"8c93a3b\",\n        \"8839d5cc\",\n        \"971fcc89\",\n        \"f9fa7113\",\n        \"4f06bc53\",\n        \"1f4770e5\",\n        \"d45e7c5b\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"c1693c5a\"\n  }\n}\n"
  },
  {
    "path": "questions/explain-how-jsonp-works-and-how-its-not-really-ajax/en-US.mdx",
    "content": "---\ntitle: Explain how JSONP works (and how it's not really Ajax)\n---\n\n## TL;DR\n\nJSONP (JSON with Padding) is a technique used to overcome the same-origin policy in web browsers, allowing you to request data from a server in a different domain. It works by dynamically creating a `<script>` tag and setting its `src` attribute to the URL of the data source. The server responds with a script that calls a predefined callback function with the data as its argument. Unlike Ajax, JSONP does not use the XMLHttpRequest object and is limited to GET requests.\n\n---\n\n## How JSONP works (and how it's not really Ajax)\n\n### What is JSONP?\n\nJSONP stands for JSON with Padding. It is a technique used to bypass the same-origin policy in web browsers, which restricts web pages from making requests to a different domain than the one that served the web page.\n\n### How JSONP works\n\n1. **Dynamic script tag creation**: A `<script>` tag is dynamically created and its `src` attribute is set to the URL of the data source, including a callback function name as a query parameter.\n2. **Server response**: The server responds with a script that calls the callback function, passing the data as an argument.\n3. **Callback execution**: The browser executes the script, invoking the callback function with the data.\n\nHere is a simple example:\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>JSONP Example</title>\n    <script>\n      function handleResponse(data) {\n        console.log(data);\n      }\n\n      function fetchData() {\n        var script = document.createElement('script');\n        script.src = 'https://example.com/data?callback=handleResponse';\n        document.body.appendChild(script);\n      }\n    </script>\n  </head>\n  <body>\n    <button onclick=\"fetchData()\">Fetch Data</button>\n  </body>\n</html>\n```\n\nIn this example, when the button is clicked, a `<script>` tag is created with the `src` attribute set to `https://example.com/data?callback=handleResponse`. The server at `example.com` responds with a script like this:\n\n```javascript\nhandleResponse({\n  name: 'John',\n  age: 30,\n});\n```\n\n### How JSONP is different from Ajax\n\n- **Transport mechanism**: JSONP uses the `<script>` tag to fetch data, whereas Ajax uses the XMLHttpRequest object.\n- **Request type**: JSONP is limited to GET requests, while Ajax can use various HTTP methods like GET, POST, PUT, DELETE, etc.\n- **Same-origin policy**: JSONP can bypass the same-origin policy, while Ajax requests are subject to it unless CORS (Cross-Origin Resource Sharing) is used.\n- **Error handling**: JSONP has limited error handling capabilities compared to Ajax.\n\n### Limitations of JSONP\n\n- **Security risks**: JSONP can expose your application to cross-site scripting (XSS) attacks if the external server is compromised or malicious.\n- **Limited to GET requests**: JSONP cannot be used for POST requests or other HTTP methods.\n- **Error handling**: JSONP lacks robust error handling mechanisms compared to Ajax.\n\n## Further reading\n\n- [W3Schools: JSONP](https://www.w3schools.com/js/js_json_jsonp.asp)\n- [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)\n- [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)\n"
  },
  {
    "path": "questions/explain-how-jsonp-works-and-how-its-not-really-ajax/metadata.json",
    "content": "{\n  \"slug\": \"explain-how-jsonp-works-and-how-its-not-really-ajax\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": false,\n  \"topics\": [\"javascript\", \"networking\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/explain-how-jsonp-works-and-how-its-not-really-ajax/pt-BR.mdx",
    "content": "---\ntitle: Explique como o JSONP funciona (e como ele não é Ajax)\n---\n\nO JSONP (JSON com padding) é um método comumente utilizado para contornar as políticas de domínio cruzado em navegadores web, porque solicitações Ajax da página atual para um domínio de origem cruzada não são permitidas.\n\nO JSONP funciona fazendo uma solicitação a um domínio cross-origin através de uma tag `<script>` e geralmente com um parâmetro de consulta `callback`, por exemplo: `https://example O?callback=printData`. O servidor irá, então, encapsular os dados em uma função chamada printData e enviá-la de volta ao cliente.\n\n```html\n<!-- https://mydomain.com -->\n<script>\n  function printData(data) {\n    console.log(`My name is ${data.name}!`);\n  }\n</script>\n\n<script src=\"https://example.com?callback=printData\"></script>\n```\n\n```js\n// Arquivo carregado de https://example.com?callback=printData\nprintData({ name: 'John Doe' });\n```\n\nO cliente deve ter a função `printData` no seu escopo global e a função será executada pelo cliente quando a resposta do domínio de origem cruzada for recebida.\n\nO JSONP pode ser inseguro e tem algumas implicações de segurança. Como o JSONP é JavaScript, ele pode fazer tudo o que o JavaScript pode fazer, então você precisa confiar no provedor dos dados JSONP.\n\nHoje em dia, [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) é a abordagem recomendada, e a JSONP é vista como um hack.\n"
  },
  {
    "path": "questions/explain-how-jsonp-works-and-how-its-not-really-ajax/zh-CN.mdx",
    "content": "---\ntitle: 解释 JSONP 的工作原理（以及它实际上并非 Ajax）\n---\n\n## TL;DR\n\nJSONP（带填充的 JSON）是一种用于克服 Web 浏览器中的同源策略的技术，允许您从不同域的服务器请求数据。它的工作原理是动态创建 `<script>` 标签，并将其 `src` 属性设置为数据源的 URL。服务器使用一个脚本进行响应，该脚本使用数据作为其参数调用预定义的 callback 函数。与 Ajax 不同，JSONP 不使用 XMLHttpRequest 对象，并且仅限于 GET 请求。\n\n***\n\n## JSONP 的工作原理（以及它实际上并非 Ajax）\n\n### 什么是 JSONP？\n\nJSONP 代表带填充的 JSON。它是一种用于绕过 Web 浏览器中的同源策略的技术，该策略限制网页向提供该网页的域以外的域发出请求。\n\n### JSONP 的工作原理\n\n1. **动态脚本标签创建**：动态创建 `<script>` 标签，并将其 `src` 属性设置为数据源的 URL，包括回调函数名称作为查询参数。\n2. **服务器响应**：服务器使用一个脚本进行响应，该脚本调用回调函数，并将数据作为参数传递。\n3. **回调执行**：浏览器执行脚本，使用数据调用回调函数。\n\n这是一个简单的例子：\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>JSONP Example</title>\n    <script>\n      function handleResponse(data) {\n        console.log(data);\n      }\n\n      function fetchData() {\n        var script = document.createElement('script');\n        script.src = 'https://example.com/data?callback=handleResponse';\n        document.body.appendChild(script);\n      }\n    </script>\n  </head>\n  <body>\n    <button onclick=\"fetchData()\">Fetch Data</button>\n  </body>\n</html>\n```\n\n在此示例中，当单击该按钮时，将创建一个 `<script>` 标签，其 `src` 属性设置为 `https://example.com/data?callback=handleResponse`。`example.com` 上的服务器将使用如下脚本进行响应：\n\n```javascript\nhandleResponse({\n  name: 'John',\n  age: 30,\n});\n```\n\n### JSONP 与 Ajax 的区别\n\n* **传输机制**：JSONP 使用 `<script>` 标签来获取数据，而 Ajax 使用 XMLHttpRequest 对象。\n* **请求类型**：JSONP 仅限于 GET 请求，而 Ajax 可以使用各种 HTTP 方法，如 GET、POST、PUT、DELETE 等。\n* **同源策略**：JSONP 可以绕过同源策略，而 Ajax 请求受其约束，除非使用 CORS（跨域资源共享）。\n* **错误处理**：与 Ajax 相比，JSONP 的错误处理能力有限。\n\n### JSONP 的局限性\n\n* **安全风险**：如果外部服务器受到破坏或恶意攻击，JSONP 可能会使您的应用程序面临跨站点脚本 (XSS) 攻击。\n* **仅限于 GET 请求**：JSONP 不能用于 POST 请求或其他 HTTP 方法。\n* **错误处理**：与 Ajax 相比，JSONP 缺乏强大的错误处理机制。\n\n## 延伸阅读\n\n* [W3Schools: JSONP](https://www.w3schools.com/js/js_json_jsonp.asp)\n* [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)\n* [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)\n"
  },
  {
    "path": "questions/explain-how-prototypal-inheritance-works/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"e48dcbd3\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"4912ac0\",\n        \"446d0998\",\n        \"95701010\",\n        \"1df4e2\",\n        \"ec4d1007\",\n        \"4066d9a9\",\n        \"eb8295dd\",\n        \"2a7816d0\",\n        \"4e4b421d\",\n        \"19bb87c5\",\n        \"a3376f34\",\n        \"be2d34c4\",\n        \"b52ddf94\",\n        \"1dc60677\",\n        \"6b3b6f34\",\n        \"92a0271d\",\n        \"3b5a819f\",\n        \"dae7e089\",\n        \"2b6d6fd1\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4912ac0\",\n        \"446d0998\",\n        \"95701010\",\n        \"1df4e2\",\n        \"ec4d1007\",\n        \"4066d9a9\",\n        \"eb8295dd\",\n        \"2a7816d0\",\n        \"4e4b421d\",\n        \"19bb87c5\",\n        \"a3376f34\",\n        \"be2d34c4\",\n        \"b52ddf94\",\n        \"1dc60677\",\n        \"6b3b6f34\",\n        \"92a0271d\",\n        \"3b5a819f\",\n        \"dae7e089\",\n        \"2b6d6fd1\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-how-prototypal-inheritance-works/en-US.mdx",
    "content": "---\ntitle: Explain how prototypal inheritance works in JavaScript\n---\n\n## TL;DR\n\nPrototypical inheritance in JavaScript is a way for objects to inherit properties and methods from other objects. Every JavaScript object has a special hidden property called `[[Prototype]]` (commonly accessed via `__proto__` or using `Object.getPrototypeOf()`) that is a reference to another object, which is called the object's \"prototype\".\n\nWhen a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's `__proto__`, and the `__proto__`'s `__proto__` and so on, until it finds the property defined on one of the `__proto__`s or until it reaches the end of the prototype chain.\n\nThis behavior simulates classical inheritance, but it is really more of [delegation than inheritance](https://davidwalsh.name/javascript-objects).\n\nHere's an example of prototypal inheritance:\n\n```js live\n// Parent object constructor.\nfunction Animal(name) {\n  this.name = name;\n}\n\n// Add a method to the parent object's prototype.\nAnimal.prototype.makeSound = function () {\n  console.log('The ' + this.constructor.name + ' makes a sound.');\n};\n\n// Child object constructor.\nfunction Dog(name) {\n  Animal.call(this, name); // Call the parent constructor.\n}\n\n// Set the child object's prototype to be the parent's prototype.\nObject.setPrototypeOf(Dog.prototype, Animal.prototype);\n\n// Add a method to the child object's prototype.\nDog.prototype.bark = function () {\n  console.log('Woof!');\n};\n\n// Create a new instance of Dog.\nconst bolt = new Dog('Bolt');\n\n// Call methods on the child object.\nconsole.log(bolt.name); // \"Bolt\"\nbolt.makeSound(); // \"The Dog makes a sound.\"\nbolt.bark(); // \"Woof!\"\n```\n\nThings to note are:\n\n- `.makeSound` is not defined on `Dog`, so the JavaScript engine goes up the prototype chain and finds `.makeSound` on the inherited `Animal`.\n- Using `Object.create()` to build the inheritance chain is no longer recommended. Use `Object.setPrototypeOf()` instead.\n\n---\n\n## Prototypical Inheritance in Javascript\n\nPrototypical inheritance is a feature in JavaScript used to create objects that inherit properties and methods from other objects. Instead of a class-based inheritance model, JavaScript uses a prototype-based model, where objects can directly inherit from other objects.\n\n### Key Concepts\n\n1. **Prototypes** : Every object in Javascript has a prototype, which is another object. When you create an object using an object literal or a constructor function, the new object is linked to the prototype of its constructor function or the `Object.prototype` if no prototype is specified. This is commonly referenced using `__proto__` or `[[Prototype]]`. You can also get the prototype by using inbuilt method `Object.getPrototypeOf()` and you can set the prototype of an object via `Object.setPrototypeOf()`.\n\n```js live\n// Define a constructor function\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\n// Add a method to the prototype\nPerson.prototype.sayHello = function () {\n  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);\n};\n\n// Create a new object using the constructor function\nlet john = new Person('John', 30);\n\n// The new object has access to the methods defined on the prototype\njohn.sayHello(); // \"Hello, my name is John and I am 30 years old.\"\n\n// The prototype of the new object is the prototype of the constructor function\nconsole.log(john.__proto__ === Person.prototype); // true\n\n// You can also get the prototype using Object.getPrototypeOf()\nconsole.log(Object.getPrototypeOf(john) === Person.prototype); // true\n\n// You can set the prototype of an object using Object.setPrototypeOf()\nlet newProto = {\n  sayGoodbye: function () {\n    console.log(`Goodbye, my name is ${this.name}`);\n  },\n};\n\nObject.setPrototypeOf(john, newProto);\n\n// Now john has access to the methods defined on the new prototype\njohn.sayGoodbye(); // \"Goodbye, my name is John\"\n\n// But no longer has access to the methods defined on the old prototype\nconsole.log(john.sayHello); // undefined\n```\n\n2. **Prototype chain**: When a property or method is accessed on an object, JavaScript first looks for it on the object itself. If it doesn't find it there, it looks at the object's prototype, and then the prototype's prototype, and so on, until it either finds the property or reaches the end of the chain (i.e., `null`).\n\n3. **Constructor functions**: JavaScript provides constructor functions to create objects. When a function is used as a constructor with the new keyword, the new object's prototype (`[[Prototype]]`) is set to the constructor's prototype property.\n\n```js live\n// Define a constructor function\nfunction Animal(name) {\n  this.name = name;\n}\n\n// Add a method to the prototype\nAnimal.prototype.sayName = function () {\n  console.log(`My name is ${this.name}`);\n};\n\n// Define a new constructor function\nfunction Dog(name, breed) {\n  Animal.call(this, name);\n  this.breed = breed;\n}\n\n// Set the prototype of Dog to inherit from Animal's prototype\nObject.setPrototypeOf(Dog.prototype, Animal.prototype);\n\n// Add a method to the Dog prototype\nDog.prototype.bark = function () {\n  console.log('Woof!');\n};\n\n// Create a new object using the Dog constructor function\nlet fido = new Dog('Fido', 'Labrador');\n\n// The new object has access to the methods defined on its own prototype and the Animal prototype\nfido.bark(); // \"Woof!\"\nfido.sayName(); // \"My name is Fido\"\n\n// If we try to access a method that doesn't exist on the Dog prototype or the Animal prototype, JavaScript will return undefined\nconsole.log(fido.fly); // undefined\n```\n\n4. **`Object.create()`**: This method creates a new object whose internal `[[Prototype]]` is directly linked to the specified prototype object. It's the most direct way to create an object that inherits from another specific object, without involving constructor functions. If you create a object via `Object.create(null)` it will not inherit any properties from `Object.prototype`. This means the object will not have any built-in properties or methods like `toString()`, `hasOwnProperty()`,\n\n```js live\n// Define a prototype object\nlet proto = {\n  greet: function () {\n    console.log(`Hello, my name is ${this.name}`);\n  },\n};\n\n// Use `Object.create()` to create a new object with the specified prototype\nlet person = Object.create(proto);\nperson.name = 'John';\n\n// The new object has access to the methods defined on the prototype\nperson.greet(); // \"Hello, my name is John\"\n\n// Check if the object has a property\nconsole.log(person.hasOwnProperty('name')); // true\n\n// Create an object that does not inherit from Object.prototype\nlet animal = Object.create(null);\nanimal.name = 'Rocky';\n\n// The new object does not have any built-in properties or methods\nconsole.log(animal.toString); // undefined\nconsole.log(animal.hasOwnProperty); // undefined\n\n// But you can still add and access custom properties\nanimal.describe = function () {\n  console.log(`Name of the animal is ${this.name}`);\n};\n\nanimal.describe(); // \"Name of the animal is Rocky\"\n```\n\n## Resources\n\n- [Inheritance and the prototype chain | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\n- [JavaScript Visualized: Prototypal Inheritance](https://dev.to/lydiahallie/javascript-visualized-prototypal-inheritance-47co)\n"
  },
  {
    "path": "questions/explain-how-prototypal-inheritance-works/metadata.json",
    "content": "{\n  \"slug\": \"explain-how-prototypal-inheritance-works\",\n  \"languages\": [],\n  \"companies\": [\"apple\", \"microsoft\", \"linkedin\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"high\",\n  \"ranking\": 130,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/explain-how-prototypal-inheritance-works/pt-BR.mdx",
    "content": "---\ntitle: Explique como funciona a herança de protótipos\n---\n\nEssa é uma pergunta extremamente comum em entrevistas de JavaScript. Todos os objetos JavaScript têm uma propriedade `__proto__` com exceção de objetos criados com `object.create(null)`, ou seja, uma referência a outro objeto, que é chamado de \"protótipo\" do objeto. Quando uma propriedade é acessada em um objeto e se a propriedade não é encontrada nesse objeto, o motor de JavaScript olha para o objeto `__proto__`, e o `__proto__` do `__proto__` e assim por diante, até que encontre a propriedade definida em um dos `__proto__`s ou até chegar ao final da cadeia de protótipos. Este comportamento simula a herança clássica, mas é realmente mais de [delegação do que herança](https://davidwalsh.name/javascript-objects).\n\n## Exemplo de Herança de Protótipos\n\n```js\n// Construtor de objeto pai.\nfunction Animal(name) {\n  this.name = name;\n}\n\n// Adiciona um método ao protótipo do objeto pai.\nAnimal.prototype.makeSound = function () {\n  console.log('O ' + this.constructor.name + ' faz um som.');\n};\n\n// Construtor filho.\nfunction Dog(name) {\n  Animal.call(this, name); // Chama o construtor pai.\n}\n\n// Set the child object's prototype to be the parent's prototype.\nObject.setPrototypeOf(Dog.prototype, Animal.prototype);\n\n// Adiciona um método ao protótipo do objeto filho.\nDog.prototype.bark = function () {\n  console.log('Woof!');\n};\n\n// Criar uma nova instância do Cachorro.\nconst bolt = new Dog('Bolt');\n\n// Chama métodos no objeto filho.\nconsole.log(bolt.name); // \"Bolt\"\nbolt.makeSound(); // \"O Dog faz um som.\"\nbolt.bark(); // \"Woof!\"\n```\n\nAs coisas a observar são:\n\n- `.makeSound` não está definido em `Dog`, então o navegador aumenta a cadeia de protótipos e encontra `.makeSound` para fora do `Animal` herdado.\n- Using `Object.create` to build the inheritance chain is no longer recommended. Use `Object.setPrototypeOf` instead.\n\n## Resources\n\n- [Inheritance and the prototype chain | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\n"
  },
  {
    "path": "questions/explain-how-prototypal-inheritance-works/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 中原型继承的工作原理\n---\n\n## TL;DR\n\nJavaScript 中的原型继承是对象从其他对象继承属性和方法的一种方式。每个 JavaScript 对象都有一个名为 `[[Prototype]]` 的特殊隐藏属性（通常通过 `__proto__` 或使用 `Object.getPrototypeOf()` 访问），它引用另一个对象，该对象被称为对象的“原型”。\n\n当访问对象的属性，并且在该对象上找不到该属性时，JavaScript 引擎会查看对象的 `__proto__`，以及 `__proto__` 的 `__proto__`，依此类推，直到它在其中一个 `__proto__` 上找到定义的属性，或者直到它到达原型链的末尾。\n\n这种行为模拟了经典继承，但实际上它更像是[委托而不是继承](https://davidwalsh.name/javascript-objects)。\n\n以下是原型继承的示例：\n\n```js live\n// Parent object constructor.\nfunction Animal(name) {\n  this.name = name;\n}\n\n// Add a method to the parent object's prototype.\nAnimal.prototype.makeSound = function () {\n  console.log('The ' + this.constructor.name + ' makes a sound.');\n};\n\n// Child object constructor.\nfunction Dog(name) {\n  Animal.call(this, name); // Call the parent constructor.\n}\n\n// Set the child object's prototype to be the parent's prototype.\nObject.setPrototypeOf(Dog.prototype, Animal.prototype);\n\n// Add a method to the child object's prototype.\nDog.prototype.bark = function () {\n  console.log('Woof!');\n};\n\n// Create a new instance of Dog.\nconst bolt = new Dog('Bolt');\n\n// Call methods on the child object.\nconsole.log(bolt.name); // \"Bolt\"\nbolt.makeSound(); // \"The Dog makes a sound.\"\nbolt.bark(); // \"Woof!\"\n```\n\n需要注意的是：\n\n* `.makeSound` 未在 `Dog` 上定义，因此 JavaScript 引擎会向上查找原型链，并在继承的 `Animal` 上找到 `.makeSound`。\n* 不再推荐使用 `Object.create()` 来构建继承链。请改用 `Object.setPrototypeOf()`。\n\n***\n\n## Javascript 中的原型继承\n\n原型继承是 JavaScript 中用于创建从其他对象继承属性和方法对象的特性。JavaScript 使用基于原型的模型，而不是基于类的继承模型，对象可以直接从其他对象继承。\n\n### 关键概念\n\n1. **原型**：JavaScript 中的每个对象都有一个原型，它也是一个对象。当您使用对象字面量或构造函数创建对象时，新对象将链接到其构造函数的原型，如果未指定原型，则链接到 `Object.prototype`。这通常使用 `__proto__` 或 `[[Prototype]]` 引用。您还可以使用内置方法 `Object.getPrototypeOf()` 获取原型，并且可以通过 `Object.setPrototypeOf()` 设置对象的原型。\n\n```js live\n// Define a constructor function\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\n// Add a method to the prototype\nPerson.prototype.sayHello = function () {\n  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);\n};\n\n// Create a new object using the constructor function\nlet john = new Person('John', 30);\n\n// The new object has access to the methods defined on the prototype\njohn.sayHello(); // \"Hello, my name is John and I am 30 years old.\"\n\n// The prototype of the new object is the prototype of the constructor function\nconsole.log(john.__proto__ === Person.prototype); // true\n\n// You can also get the prototype using Object.getPrototypeOf()\nconsole.log(Object.getPrototypeOf(john) === Person.prototype); // true\n\n// You can set the prototype of an object using Object.setPrototypeOf()\nlet newProto = {\n  sayGoodbye: function () {\n    console.log(`Goodbye, my name is ${this.name}`);\n  },\n};\n\nObject.setPrototypeOf(john, newProto);\n\n// Now john has access to the methods defined on the new prototype\njohn.sayGoodbye(); // \"Goodbye, my name is John\"\n\n// But no longer has access to the methods defined on the old prototype\nconsole.log(john.sayHello); // undefined\n```\n\n2. **原型链**：当访问对象的属性或方法时，JavaScript 首先在对象本身上查找它。如果找不到，它会查看对象的原型，然后是原型的原型，依此类推，直到找到该属性或到达链的末尾（即 `null`）。\n\n3. **构造函数**：JavaScript 提供了构造函数来创建对象。当一个函数与 new 关键字一起用作构造函数时，新对象的原型 (`[[Prototype]]`) 将设置为构造函数 的原型属性。\n\n```js live\n// 定义一个构造函数\nfunction Animal(name) {\n  this.name = name;\n}\n\n// 将一个方法添加到原型上\nAnimal.prototype.sayName = function () {\n  console.log(`我的名字是 ${this.name}`);\n};\n\n// 定义一个新的构造函数\nfunction Dog(name, breed) {\n  Animal.call(this, name);\n  this.breed = breed;\n}\n\n// 设置 Dog 的原型以继承自 Animal 的原型\nObject.setPrototypeOf(Dog.prototype, Animal.prototype);\n\n// 将一个方法添加到 Dog 的原型上\nDog.prototype.bark = function () {\n  console.log('汪！');\n};\n\n// 使用 Dog 构造函数创建一个新对象\nlet fido = new Dog('Fido', 'Labrador');\n\n// 新对象可以访问在其自身原型和 Animal 原型上定义的方法\nfido.bark(); // \"汪！\"\nfido.sayName(); // \"我的名字是 Fido\"\n\n// 如果我们尝试访问 Dog 原型或 Animal 原型上不存在的方法，JavaScript 将返回 undefined\nconsole.log(fido.fly); // undefined\n```\n\n4. **`Object.create()`**: 此方法创建一个新对象，其内部 `[[Prototype]]` 直接链接到指定的原型对象。这是创建从另一个特定对象继承的对象的最直接方法，无需涉及构造函数。如果通过 `Object.create(null)` 创建一个对象，它将不会从 `Object.prototype` 继承任何属性。这意味着该对象将没有任何内置属性或方法，如 `toString()`、`hasOwnProperty()`,\n\n```js live\n// Define a prototype object\nlet proto = {\n  greet: function () {\n    console.log(`Hello, my name is ${this.name}`);\n  },\n};\n\n// Use `Object.create()` to create a new object with the specified prototype\nlet person = Object.create(proto);\nperson.name = 'John';\n\n// The new object has access to the methods defined on the prototype\nperson.greet(); // \"Hello, my name is John\"\n\n// Check if the object has a property\nconsole.log(person.hasOwnProperty('name')); // true\n\n// Create an object that does not inherit from Object.prototype\nlet animal = Object.create(null);\nanimal.name = 'Rocky';\n\n// The new object does not have any built-in properties or methods\nconsole.log(animal.toString); // undefined\nconsole.log(animal.hasOwnProperty); // undefined\n\n// But you can still add and access custom properties\nanimal.describe = function () {\n  console.log(`Name of the animal is ${this.name}`);\n};\n\nanimal.describe(); // \"Name of the animal is Rocky\"\n```\n\n## 资源\n\n* [Inheritance and the prototype chain | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\n* [JavaScript Visualized: Prototypal Inheritance](https://dev.to/lydiahallie/javascript-visualized-prototypal-inheritance-47co)\n"
  },
  {
    "path": "questions/explain-how-this-works-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"609c51e2\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"d5beaf35\",\n        \"6ac7163a\",\n        \"9dc36583\",\n        \"fd54d294\",\n        \"2a7816d0\",\n        \"9f0fe69f\",\n        \"cc40d86\",\n        \"59175592\",\n        \"d36decea\",\n        \"f0118c1e\",\n        \"b7456387\",\n        \"3f0d3ea6\",\n        \"e38f71e6\",\n        \"3f421e0b\",\n        \"4f360376\",\n        \"f8480c9e\",\n        \"e8879987\",\n        \"205121fd\",\n        \"a17f23b8\",\n        \"345ed5a0\",\n        \"7580adc9\",\n        \"2295bef7\",\n        \"98444efa\",\n        \"b63b6687\",\n        \"47469115\",\n        \"1509e0b7\",\n        \"23699213\",\n        \"9eb5dc0b\",\n        \"a7030dd3\",\n        \"6ad9cdd9\",\n        \"2bf68e83\",\n        \"b854f8ca\",\n        \"8c5b27ca\",\n        \"71a6b122\",\n        \"dfac6653\",\n        \"5968c5a9\",\n        \"183f3bc9\",\n        \"8799f8c9\",\n        \"edb8b937\",\n        \"d5137db5\",\n        \"827f3281\",\n        \"fdec9eb8\",\n        \"9c48121d\",\n        \"8641d96e\",\n        \"c03c3989\",\n        \"f6206c2d\",\n        \"1f4770e5\",\n        \"f97fcd35\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d5beaf35\",\n        \"6ac7163a\",\n        \"9dc36583\",\n        \"fd54d294\",\n        \"2a7816d0\",\n        \"9f0fe69f\",\n        \"cc40d86\",\n        \"59175592\",\n        \"d36decea\",\n        \"f0118c1e\",\n        \"b7456387\",\n        \"3f0d3ea6\",\n        \"e38f71e6\",\n        \"3f421e0b\",\n        \"4f360376\",\n        \"f8480c9e\",\n        \"e8879987\",\n        \"205121fd\",\n        \"a17f23b8\",\n        \"345ed5a0\",\n        \"7580adc9\",\n        \"2295bef7\",\n        \"98444efa\",\n        \"b63b6687\",\n        \"47469115\",\n        \"1509e0b7\",\n        \"23699213\",\n        \"9eb5dc0b\",\n        \"a7030dd3\",\n        \"6ad9cdd9\",\n        \"2bf68e83\",\n        \"b854f8ca\",\n        \"8c5b27ca\",\n        \"71a6b122\",\n        \"dfac6653\",\n        \"5968c5a9\",\n        \"183f3bc9\",\n        \"8799f8c9\",\n        \"edb8b937\",\n        \"d5137db5\",\n        \"827f3281\",\n        \"fdec9eb8\",\n        \"9c48121d\",\n        \"8641d96e\",\n        \"c03c3989\",\n        \"f6206c2d\",\n        \"1f4770e5\",\n        \"f97fcd35\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-how-this-works-in-javascript/en-US.mdx",
    "content": "---\ntitle: Explain how `this` works in JavaScript\n---\n\n## TL;DR\n\nThere's no simple explanation for `this`; it is one of the most confusing concepts in JavaScript because it's behavior differs from many other programming languages. The one-liner explanation of the `this` keyword is that it is a dynamic reference to the context in which a function is executed.\n\nA longer explanation is that `this` follows these rules:\n\n1. If the `new` keyword is used when calling the function, meaning the function was used as a function constructor, the `this` inside the function is the newly-created object instance.\n2. If `this` is used in a `class` `constructor`, the `this` inside the `constructor` is the newly-created object instance.\n3. If `apply()`, `call()`, or `bind()` is used to call/create a function, `this` inside the function is the object that is passed in as the argument.\n4. If a function is called as a method (e.g. `obj.method()`) — `this` is the object that the function is a property of.\n5. If a function is invoked as a free function invocation, meaning it was invoked without any of the conditions present above, `this` is the global object. In the browser, the global object is the `window` object. If in strict mode (`'use strict';`), `this` will be `undefined` instead of the global object.\n6. If multiple of the above rules apply, the rule that is higher wins and will set the `this` value.\n7. If the function is an ES2015 arrow function, it ignores all the rules above and receives the `this` value of its surrounding scope at the time it is created.\n\nFor an in-depth explanation, do check out [Arnav Aggrawal's article on Medium](https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3).\n\n---\n\n## `this` keyword\n\nIn JavaScript, `this` is a keyword that refers to the current execution context of a function or script. It's a fundamental concept in JavaScript, and understanding how `this` works is crucial for building robust and maintainable applications.\n\n### Used globally\n\nIn the global scope, `this` refers to the global object, which is the `window` object in a web browser or the `global` object in a Node.js environment.\n\n```js\nconsole.log(this); // In a browser, this will log the window object (for non-strict mode).\n```\n\n### Within a regular function call\n\nWhen a function is called in the global context or as a standalone function, `this` refers to the global object (in non-strict mode) or `undefined` (in strict mode).\n\n```js\nfunction showThis() {\n  console.log(this);\n}\n\nshowThis(); // In non-strict mode: Window (global object). In strict mode: undefined.\n```\n\n### Within a method call\n\nWhen a function is called as a method of an object, `this` refers to the object that the method is called on.\n\n```js live\nconst obj = {\n  name: 'John',\n  showThis: function () {\n    console.log(this);\n  },\n};\n\nobj.showThis(); // { name: 'John', showThis: ƒ }\n```\n\nNote that if you do the following, it is as good as a regular function call and not a method call. `this` has lost its context and no longer points to `obj`.\n\n```js\nconst obj = {\n  name: 'John',\n  showThis: function () {\n    console.log(this);\n  },\n};\n\nconst showThisStandalone = obj.showThis;\nshowThisStandalone(); // In non-strict mode: Window (global object). In strict mode: undefined.\n```\n\n### Within a function constructor\n\nWhen a function is used as a constructor (called with the `new` keyword), `this` refers to the newly-created instance. In the following example, `this` refers to the `Person` object being created, and the `name` property is set on that object.\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person = new Person('John');\nconsole.log(person.name); // \"John\"\n```\n\n### Within class constructor and methods\n\nIn ES2015 classes, `this` behaves as it does in object methods. It refers to the instance of the class.\n\n```js live\nclass Person {\n  constructor(name) {\n    this.name = name;\n  }\n\n  showThis() {\n    console.log(this);\n  }\n}\n\nconst person = new Person('John');\nperson.showThis(); // Person {name: 'John'}\n\nconst showThisStandalone = person.showThis;\nshowThisStandalone(); // `undefined` because in JavaScript class bodies, all methods are strict mode by default, even if you don't add 'use strict'\n```\n\n### Explicitly binding `this`\n\nYou can use `bind()`, `call()`, or `apply()` to explicitly set the value of `this` for a function.\n\nUsing the `call()` and `apply()` methods allow you to explicitly set the value of `this` when calling the function.\n\n```js live\nfunction showThis() {\n  console.log(this);\n}\nconst obj = { name: 'John' };\n\nshowThis.call(obj); // { name: 'John' }\nshowThis.apply(obj); // { name: 'John' }\n```\n\nThe `bind()` method creates a new function with `this` bound to the specified value.\n\n```js live\nfunction showThis() {\n  console.log(this);\n}\nconst obj = { name: 'John' };\n\nconst boundFunc = showThis.bind(obj);\nboundFunc(); // { name: 'John' }\n```\n\n### Within arrow functions\n\nArrow functions do not have their own `this` context. Instead, the `this` is lexically scoped, which means it inherits the `this` value from its surrounding scope at the time they are defined.\n\nIn this example, `this` refers to the global object (window or global), because the arrow function is not bound to the `person` object.\n\n```js live\nconst person = {\n  firstName: 'John',\n  sayHello: () => {\n    console.log(`Hello, my name is ${this.firstName}!`);\n  },\n};\n\nperson.sayHello(); // \"Hello, my name is undefined!\"\n```\n\nIn the following example, the `this` in the arrow function will be the `this` value of its enclosing context, so it depends on how `showThis()` is called.\n\n```js\nconst obj = {\n  name: 'John',\n  showThis: function () {\n    const arrowFunc = () => {\n      console.log(this);\n    };\n    arrowFunc();\n  },\n};\n\nobj.showThis(); // { name: 'John', showThis: ƒ }\n\nconst showThisStandalone = obj.showThis;\nshowThisStandalone(); // In non-strict mode: Window (global object). In strict mode: undefined.\n```\n\nTherefore, the `this` value in arrow functions cannot be set by `bind()`, `apply()` or `call()` methods, nor does it point to the current object in object methods.\n\n```js\nconst obj = {\n  name: 'Alice',\n  regularFunction: function () {\n    console.log('Regular function:', this.name);\n  },\n  arrowFunction: () => {\n    console.log('Arrow function:', this.name);\n  },\n};\n\nconst anotherObj = {\n  name: 'Bob',\n};\n\n// Using call/apply/bind with a regular function\nobj.regularFunction.call(anotherObj); // Regular function: Bob\nobj.regularFunction.apply(anotherObj); // Regular function: Bob\nconst boundRegularFunction = obj.regularFunction.bind(anotherObj);\nboundRegularFunction(); // Regular function: Bob\n\n// Using call/apply/bind with an arrow function, `this` refers to the global scope and cannot be modified.\nobj.arrowFunction.call(anotherObj); // Arrow function: window/undefined (depending if strict mode)\nobj.arrowFunction.apply(anotherObj); // Arrow function: window/undefined (depending if strict mode)\nconst boundArrowFunction = obj.arrowFunction.bind(anotherObj);\nboundArrowFunction(); // Arrow function: window/undefined (depending if strict mode)\n```\n\n### Within event handlers\n\nWhen a function is called as a DOM event handler, `this` refers to the element that triggered the event. In this example, `this` refers to the `<button>` element that was clicked.\n\n```html\n<button id=\"my-button\" onclick=\"console.log(this)\">Click me</button>\n<!-- Logs the button element -->\n```\n\nWhen setting an event handler using JavaScript, this also refers to the element that received the event.\n\n```js\ndocument.getElementById('my-button').addEventListener('click', function () {\n  console.log(this); // Logs the button element\n});\n```\n\nAs mentioned above, ES2015 introduces [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) which uses the [enclosing lexical scope](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this). This is usually convenient, but does prevent the caller from defining the `this` context via `.call`/`.apply`/`.bind`. One of the consequences is that DOM event handlers will not properly bind `this` in your event handler functions if you define the callback parameters to `.addEventListener()` using arrow functions.\n\n```js\ndocument.getElementById('my-button').addEventListener('click', () => {\n  console.log(this); // Window / undefined (depending on whether strict mode) instead of the button element.\n});\n```\n\nIn summary, `this` in JavaScript refers to the current execution context of a function or script, and its value can change depending on the context in which it is used. Understanding how `this` works is essential for building robust and maintainable JavaScript applications.\n\n## Further reading\n\n- [this - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\n- [The Simple Rules to `this` in Javascript](https://medium.com/m/global-identity-2?redirectUrl=https%3A%2F%2Fcodeburst.io%2Fthe-simple-rules-to-this-in-javascript-35d97f31bde3)\n"
  },
  {
    "path": "questions/explain-how-this-works-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"explain-how-this-works-in-javascript\",\n  \"languages\": [],\n  \"companies\": [\"linkedin\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"high\",\n  \"ranking\": 60,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/explain-how-this-works-in-javascript/pt-BR.mdx",
    "content": "---\ntitle: Explique como `this` funciona em JavaScript\n---\n\nNão há uma explicação simples para `this`; ela é um dos conceitos mais confusos do JavaScript. Uma explicação superficial é que o valor do `this` depende de como a função é chamada. Tendo lido muitas explicações sobre `this` online, [Arnav Aggrawal](https://medium.com/@arnav_aggarwal) é a explicação que foi mais clara. As seguintes regras se aplicam:\n\n1.  Se a palavra-chave `new` é usada ao chamar a função, `new` dentro da função é um objeto totalmente novo.\n2.  Se `apply`, `call`, ou `bind` forem usados para chamar/criar uma função, `this` dentro da função é o objeto passado como o argumento.\n3.  Se uma função é chamada como um método, como `obj.method()` — `this` é o objeto do qual a função é uma propriedade.\n4.  Se uma função é chamada como uma chamada de função livre, significando que ele foi invocado sem nenhuma das condições presentes acima, `this` é o objeto global. Em um navegador, é o objeto `window`. Se em modo estrito (`'use strict'`), `this` será `undefined` em vez do objeto global.\n5.  Se se aplicarem múltiplas das regras acima, a regra que é maior ganha e definirá o valor `this`.\n6.  Se a função é uma arrow function ES2015, ela ignora todas as regras acima e recebe o valor `this` do seu escopo circundante no momento em que ele é criado.\n\nPara uma explicação aprofundada, confira o [artigo na Medium](https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3).\n\n#### Você pode dar um exemplo de uma das maneiras como o trabalho com \"this\" mudou no ES2015?\n\nES2015 permite que você use [arrow functions](http://2ality.com/2017/12/alternate-this.html#arrow-functions) que usa o [enclosing lexical scope](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this). Isso geralmente é conveniente, mas impede quem chamou de controlar o contexto através de `.call` ou `.apply`—as consequências são que uma biblioteca como `jQuery` não irá vincular corretamente o `this` em suas funções de manipulador de eventos. Portanto, é importante ter isso em mente ao refatorar grandes aplicações legadas.\n"
  },
  {
    "path": "questions/explain-how-this-works-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 中 `this` 的工作原理\n---\n\n## TL;DR\n\n`this` 没有简单的解释；它是 JavaScript 中最令人困惑的概念之一，因为它的行为与其他许多编程语言不同。`this` 关键字的单行解释是，它是一个对函数执行上下文的动态引用。\n\n更长的解释是，`this` 遵循以下规则：\n\n1. 如果在调用函数时使用了 `new` 关键字，这意味着该函数被用作函数构造函数，则函数内部的 `this` 是新创建的对象实例。\n2. 如果在 `class` `constructor` 中使用了 `this`，则 `constructor` 内部的 `this` 是新创建的对象实例。\n3. 如果使用 `apply()`、`call()` 或 `bind()` 调用/创建函数，则函数内部的 `this` 是作为参数传入的对象。\n4. 如果一个函数被调用为一个方法（例如 `obj.method()`）——`this` 是该函数所属的对象。\n5. 如果一个函数被调用为自由函数调用，这意味着它是在没有任何上述条件的情况下被调用的，`this` 是全局对象。在浏览器中，全局对象是 `window` 对象。如果在严格模式 (`'use strict';`) 中，`this` 将是 `undefined` 而不是全局对象。\n6. 如果应用了多个上述规则，则优先级较高的规则将获胜并设置 `this` 的值。\n7. 如果该函数是 ES2015 箭头函数，它会忽略上述所有规则，并在创建时接收其周围作用域的 `this` 值。\n\n如需深入解释，请查看 [Arnav Aggrawal 在 Medium 上的文章](https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3)。\n\n***\n\n## `this` 关键字\n\n在 JavaScript 中，`this` 是一个关键字，它引用函数或脚本的当前执行上下文。这是 JavaScript 中的一个基本概念，理解 `this` 的工作原理对于构建健壮且可维护的应用程序至关重要。\n\n### 全局使用\n\n在全局范围内，`this` 引用全局对象，在 Web 浏览器中是 `window` 对象，在 Node.js 环境中是 `global` 对象。\n\n```js\nconsole.log(this); // 在浏览器中，这将记录 window 对象（对于非严格模式）。\n```\n\n### 在常规函数调用中\n\n当一个函数在全局上下文中或作为独立函数被调用时，`this` 引用全局对象（在非严格模式下）或 `undefined`（在严格模式下）。\n\n```js\nfunction showThis() {\n  console.log(this);\n}\n\nshowThis(); // 在非严格模式下：Window（全局对象）。在严格模式下：undefined。\n```\n\n### 在方法调用中\n\n当一个函数作为对象的方法被调用时，`this` 引用该方法被调用的对象。\n\n```js live\nconst obj = {\n  name: 'John',\n  showThis: function () {\n    console.log(this);\n  },\n};\n\nobj.showThis(); // { name: 'John', showThis: ƒ }\n```\n\n请注意，如果你这样做，它就和常规函数调用一样，而不是方法调用。`this` 已经失去了它的上下文，不再指向 `obj`。\n\n```js\nconst obj = {\n  name: 'John',\n  showThis: function () {\n    console.log(this);\n  },\n};\n\nconst showThisStandalone = obj.showThis;\nshowThisStandalone(); // 在非严格模式下：Window（全局对象）。在严格模式下：undefined。\n```\n\n### 在函数构造器中\n\n当一个函数被用作构造器（使用 `new` 关键字调用）时，`this` 指的是新创建的实例。在下面的例子中，`this` 指的是正在创建的 `Person` 对象，并且 `name` 属性是在该对象上设置的。\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person = new Person('John');\nconsole.log(person.name); // \"John\"\n```\n\n### 在类构造函数和方法中\n\n在 ES2015 类中，`this` 的行为与在对象方法中一样。它指的是类的实例。\n\n```js live\nclass Person {\n  constructor(name) {\n    this.name = name;\n  }\n\n  showThis() {\n    console.log(this);\n  }\n}\n\nconst person = new Person('John');\nperson.showThis(); // Person {name: 'John'}\n\nconst showThisStandalone = person.showThis;\nshowThisStandalone(); // `undefined` because in JavaScript class bodies, all methods are strict mode by default, even if you don't add 'use strict'\n```\n\n### 显式绑定 `this`\n\n你可以使用 `bind()`、`call()` 或 `apply()` 来显式设置函数的 `this` 的值。\n\n使用 `call()` 和 `apply()` 方法允许您在调用函数时显式设置 `this` 的值。\n\n```js live\nfunction showThis() {\n  console.log(this);\n}\nconst obj = { name: 'John' };\n\nshowThis.call(obj); // { name: 'John' }\nshowThis.apply(obj); // { name: 'John' }\n```\n\n`bind()` 方法创建一个新函数，并将 `this` 绑定到指定的值。\n\n```js live\nfunction showThis() {\n  console.log(this);\n}\nconst obj = { name: 'John' };\n\nconst boundFunc = showThis.bind(obj);\nboundFunc(); // { name: 'John' }\n```\n\n### 在箭头函数中\n\n箭头函数没有自己的 `this` 上下文。相反，`this` 是词法作用域的，这意味着它继承了定义时周围作用域的 `this` 值。\n\n在这个例子中，`this` 指的是全局对象（window 或 global），因为箭头函数没有绑定到 `person` 对象。\n\n```js live\nconst person = {\n  firstName: 'John',\n  sayHello: () => {\n    console.log(`Hello, my name is ${this.firstName}!`);\n  },\n};\n\nperson.sayHello(); // \"Hello, my name is undefined!\"\n```\n\n在下面的例子中，箭头函数中的 `this` 将是其封闭上下文的 `this` 值，因此它取决于 `showThis()` 的调用方式。\n\n```js\nconst obj = {\n  name: 'John',\n  showThis: function () {\n    const arrowFunc = () => {\n      console.log(this);\n    };\n    arrowFunc();\n  },\n};\n\nobj.showThis(); // { name: 'John', showThis: ƒ }\n\nconst showThisStandalone = obj.showThis;\nshowThisStandalone(); // 在非严格模式下：Window（全局对象）。在严格模式下：undefined。\n```\n\n因此，箭头函数中的 `this` 值不能通过 `bind()`、`apply()` 或 `call()` 方法设置，它也不会指向对象方法中的当前对象。\n\n```js\nconst obj = {\n  name: 'Alice',\n  regularFunction: function () {\n    console.log('Regular function:', this.name);\n  },\n  arrowFunction: () => {\n    console.log('Arrow function:', this.name);\n  },\n};\n\nconst anotherObj = {\n  name: 'Bob',\n};\n\n// 使用 call/apply/bind 和常规函数\nobj.regularFunction.call(anotherObj); // Regular function: Bob\nobj.regularFunction.apply(anotherObj); // Regular function: Bob\nconst boundRegularFunction = obj.regularFunction.bind(anotherObj);\nboundRegularFunction(); // Regular function: Bob\n\n// 使用 call/apply/bind 和箭头函数，`this` 指的是全局作用域，并且不能被修改。\nobj.arrowFunction.call(anotherObj); // Arrow function: window/undefined (depending if strict mode)\nobj.arrowFunction.apply(anotherObj); // Arrow function: window/undefined (depending if strict mode)\nconst boundArrowFunction = obj.arrowFunction.bind(anotherObj);\nboundArrowFunction(); // Arrow function: window/undefined (depending if strict mode)\n```\n\n### 在事件处理程序中\n\n当一个函数被调用为 DOM 事件处理程序时，`this` 指的是触发该事件的元素。在这个例子中，`this` 指的是被点击的 `<button>` 元素。\n\n```html\n<button id=\"my-button\" onclick=\"console.log(this)\">Click me</button>\n<!-- Logs the button element -->\n```\n\n使用 JavaScript 设置事件处理程序时，`this` 也指的是接收事件的元素。\n\n```js\ndocument.getElementById('my-button').addEventListener('click', function () {\n  console.log(this); // Logs the button element\n});\n```\n\n如上所述，ES2015 引入了 [箭头函数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)，它使用 [封闭的词法范围](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_separate_this)。这通常很方便，但确实阻止了调用者通过 `.call`/`.apply`/`.bind` 定义 `this` 上下文。其中一个后果是，如果您使用箭头函数定义 `.addEventListener()` 的回调参数，DOM 事件处理程序将无法在您的事件处理程序函数中正确绑定 `this`。\n\n```js\ndocument.getElementById('my-button').addEventListener('click', () => {\n  console.log(this); // Window / undefined (depending on whether strict mode) instead of the button element.\n});\n```\n\n总而言之，JavaScript 中的 `this` 指的是函数或脚本的当前执行上下文，其值可以根据使用它的上下文而改变。理解 `this` 的工作方式对于构建健壮且可维护的 JavaScript 应用程序至关重要。\n\n## 延伸阅读\n\n* [this - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\n* [The Simple Rules to `this` in Javascript](https://medium.com/m/global-identity-2?redirectUrl=https%3A%2F%2Fcodeburst.io%2Fthe-simple-rules-to-this-in-javascript-35d97f31bde3)\n"
  },
  {
    "path": "questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"eeba62ba\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"980a7499\",\n        \"b7f83130\",\n        \"2a7816d0\",\n        \"d31d76ad\",\n        \"abc5b4e7\",\n        \"27a18226\",\n        \"5b0269a4\",\n        \"a48a2faf\",\n        \"fc625159\",\n        \"e293bbc3\",\n        \"88ad3fd9\",\n        \"9912c3a1\",\n        \"d8cf8c74\",\n        \"8fd6ee72\",\n        \"5de61f04\",\n        \"cac9a1fb\",\n        \"1f4770e5\",\n        \"8e223077\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"980a7499\",\n        \"b7f83130\",\n        \"2a7816d0\",\n        \"d31d76ad\",\n        \"abc5b4e7\",\n        \"27a18226\",\n        \"5b0269a4\",\n        \"a48a2faf\",\n        \"fc625159\",\n        \"e293bbc3\",\n        \"88ad3fd9\",\n        \"9912c3a1\",\n        \"d8cf8c74\",\n        \"8fd6ee72\",\n        \"5de61f04\",\n        \"cac9a1fb\",\n        \"1f4770e5\",\n        \"8e223077\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/en-US.mdx",
    "content": "---\ntitle: Explain the concept of a callback function in asynchronous operations\n---\n\n## TL;DR\n\nA callback function is a function passed as an argument to another function, which is then invoked inside the outer function to complete some kind of routine or action. In asynchronous operations, callbacks are used to handle tasks that take time to complete, such as network requests or file I/O, without blocking the execution of the rest of the code. For example:\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John', age: 30 };\n    callback(data);\n  }, 1000);\n}\n\nfetchData((data) => {\n  console.log(data);\n});\n```\n\n---\n\n## What is a callback function?\n\nA callback function is a function that is passed as an argument to another function and is executed after some operation has been completed. This is particularly useful in asynchronous programming, where operations like network requests, file I/O, or timers need to be handled without blocking the main execution thread.\n\n### Synchronous vs. asynchronous callbacks\n\n- **Synchronous callbacks** are executed immediately within the function they are passed to. They are blocking and the code execution waits for them to complete.\n- **Asynchronous callbacks** are executed after a certain event or operation has been completed. They are non-blocking and allow the code execution to continue while waiting for the operation to finish.\n\n### Example of a synchronous callback\n\n```js live\nfunction greet(name, callback) {\n  console.log('Hello ' + name);\n  callback();\n}\n\nfunction sayGoodbye() {\n  console.log('Goodbye!');\n}\n\ngreet('Alice', sayGoodbye);\n// Output:\n// Hello Alice\n// Goodbye!\n```\n\n### Example of an asynchronous callback\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John', age: 30 };\n    callback(data);\n  }, 1000);\n}\n\nfetchData((data) => {\n  console.log(data);\n});\n// Output after 1 second:\n// { name: 'John', age: 30 }\n```\n\n### Common use cases\n\n- **Network requests**: Fetching data from an API\n- **File I/O**: Reading or writing files\n- **Timers**: Delaying execution using `setTimeout` or `setInterval`\n- **Event handling**: Responding to user actions like clicks or key presses\n\n### Handling errors in callbacks\n\nWhen dealing with asynchronous operations, it's important to handle errors properly. A common pattern is to use the first argument of the callback function to pass an error object, if any.\n\n```js live\nfunction fetchData(callback) {\n  // assume asynchronous operation to fetch data\n  const { data, error } = { data: { name: 'John', age: 30 }, error: null };\n  callback(error, data);\n}\n\nfetchData((error, data) => {\n  if (error) {\n    console.error('An error occurred:', error);\n  } else {\n    console.log(data);\n  }\n});\n```\n\n## Further reading\n\n- [MDN Web Docs: Callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function)\n- [JavaScript.info: Callbacks](https://javascript.info/callbacks)\n- [Node.js: Asynchronous programming and callbacks](https://nodejs.org/en/learn/asynchronous-work/javascript-asynchronous-programming-and-callbacks)\n"
  },
  {
    "path": "questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-a-callback-function-in-asynchronous-operations\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"async\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Asynchronous JavaScript\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-a-callback-function-in-asynchronous-operations/zh-CN.mdx",
    "content": "---\ntitle: 解释异步操作中回调函数的概念\n---\n\n## TL;DR\n\n回调函数是作为参数传递给另一个函数的函数，然后在外部函数中调用该函数以完成某种例程或操作。在异步操作中，回调用于处理需要时间才能完成的任务，例如网络请求或文件 I/O，而不会阻塞其余代码的执行。例如：\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John', age: 30 };\n    callback(data);\n  }, 1000);\n}\n\nfetchData((data) => {\n  console.log(data);\n});\n```\n\n***\n\n## 什么是回调函数？\n\n回调函数是作为参数传递给另一个函数并在完成某些操作后执行的函数。这在异步编程中特别有用，其中需要处理网络请求、文件 I/O 或计时器等操作，而不会阻塞主执行线程。\n\n### 同步与异步回调\n\n* **同步回调** 在传递给它们的函数中立即执行。它们是阻塞的，代码执行会等待它们完成。\n* **异步回调** 在完成某个事件或操作后执行。它们是非阻塞的，允许代码执行在等待操作完成的同时继续进行。\n\n### 同步回调示例\n\n```js live\nfunction greet(name, callback) {\n  console.log('Hello ' + name);\n  callback();\n}\n\nfunction sayGoodbye() {\n  console.log('Goodbye!');\n}\n\ngreet('Alice', sayGoodbye);\n// Output:\n// Hello Alice\n// Goodbye!\n```\n\n### 异步回调示例\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John', age: 30 };\n    callback(data);\n  }, 1000);\n}\n\nfetchData((data) => {\n  console.log(data);\n});\n// Output after 1 second:\n// { name: 'John', age: 30 }\n```\n\n### 常见用例\n\n* **网络请求**：从 API 获取数据\n* **文件 I/O**：读取或写入文件\n* **计时器**：使用 `setTimeout` 或 `setInterval` 延迟执行\n* **事件处理**：响应用户操作，如单击或按键\n\n### 在回调中处理错误\n\n处理异步操作时，正确处理错误非常重要。一个常见的模式是使用回调函数的第一个参数来传递一个错误对象（如果有）。\n\n```js live\nfunction fetchData(callback) {\n  // assume asynchronous operation to fetch data\n  const { data, error } = { data: { name: 'John', age: 30 }, error: null };\n  callback(error, data);\n}\n\nfetchData((error, data) => {\n  if (error) {\n    console.error('An error occurred:', error);\n  } else {\n    console.log(data);\n  }\n});\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function)\n* [JavaScript.info: Callbacks](https://javascript.info/callbacks)\n* [Node.js: Asynchronous programming and callbacks](https://nodejs.org/en/learn/asynchronous-work/javascript-asynchronous-programming-and-callbacks)\n"
  },
  {
    "path": "questions/explain-the-concept-of-a-microtask-queue/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"6e9360d9\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"9f8c52e9\",\n        \"2a7816d0\",\n        \"f88269dc\",\n        \"df8b5bba\",\n        \"7193af21\",\n        \"59a78bb1\",\n        \"eb130ea5\",\n        \"9b5019f0\",\n        \"d44d00ca\",\n        \"b52ffac3\",\n        \"11ea2a26\",\n        \"a956cc42\",\n        \"670df17e\",\n        \"a74d8261\",\n        \"6dd3b324\",\n        \"7cf0f039\",\n        \"1f4770e5\",\n        \"3096a863\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"9f8c52e9\",\n        \"2a7816d0\",\n        \"f88269dc\",\n        \"df8b5bba\",\n        \"7193af21\",\n        \"59a78bb1\",\n        \"eb130ea5\",\n        \"9b5019f0\",\n        \"d44d00ca\",\n        \"b52ffac3\",\n        \"11ea2a26\",\n        \"a956cc42\",\n        \"670df17e\",\n        \"a74d8261\",\n        \"6dd3b324\",\n        \"7cf0f039\",\n        \"1f4770e5\",\n        \"3096a863\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-a-microtask-queue/en-US.mdx",
    "content": "---\ntitle: Explain the concept of a microtask queue\n---\n\n## TL;DR\n\nThe microtask queue is a queue of tasks that need to be executed after the currently executing script and before any other task. Microtasks are typically used for tasks that need to be executed immediately after the current operation, such as promise callbacks. The microtask queue is processed before the macrotask queue, ensuring that microtasks are executed as soon as possible.\n\n---\n\n## The concept of a microtask queue\n\n### What is a microtask queue?\n\nThe microtask queue is a part of the JavaScript event loop mechanism. It is a queue that holds tasks that need to be executed immediately after the currently executing script and before any other task in the macrotask queue. Microtasks are typically used for operations that need to be executed as soon as possible, such as promise callbacks and `MutationObserver` callbacks.\n\n### How does the microtask queue work?\n\n1. **Execution order**: The microtask queue is processed after the currently executing script and before the macrotask queue. This means that microtasks are given higher priority over macrotasks.\n2. **Event loop**: During each iteration of the event loop, the JavaScript engine first processes all the microtasks in the microtask queue before moving on to the macrotask queue.\n3. **Adding microtasks**: Microtasks can be added to the microtask queue using methods like `Promise.resolve().then()` and `queueMicrotask()`.\n\n### Example\n\nHere is an example to illustrate how the microtask queue works:\n\n```js live\nconsole.log('Script start');\n\nsetTimeout(() => {\n  console.log('setTimeout');\n}, 0);\n\nPromise.resolve()\n  .then(() => {\n    console.log('Promise 1');\n  })\n  .then(() => {\n    console.log('Promise 2');\n  });\n\nconsole.log('Script end');\n```\n\nOutput:\n\n```\nScript start\nScript end\nPromise 1\nPromise 2\nsetTimeout\n```\n\nIn this example:\n\n- The synchronous code (`console.log('Script start')` and `console.log('Script end')`) is executed first.\n- The promise callbacks (`Promise 1` and `Promise 2`) are added to the microtask queue and executed next.\n- The `setTimeout` callback is added to the macrotask queue and executed last.\n\n### Use cases\n\n1. **Promise callbacks**: Microtasks are commonly used for promise callbacks to ensure they are executed as soon as possible after the current operation.\n2. **MutationObserver**: The `MutationObserver` API uses microtasks to notify changes in the DOM.\n\n## Further reading\n\n- [MDN Web Docs: Microtask](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide)\n- [JavaScript Event Loop Explained](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop)\n- [Understanding the JavaScript Microtask Queue](https://javascript.info/microtask-queue)\n"
  },
  {
    "path": "questions/explain-the-concept-of-a-microtask-queue/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-a-microtask-queue\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"async\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Asynchronous JavaScript\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-a-microtask-queue/zh-CN.mdx",
    "content": "---\ntitle: 解释微任务队列的概念\n---\n\n## TL;DR\n\n微任务队列是一个任务队列，需要在当前执行的脚本之后和任何其他任务之前执行。微任务通常用于需要紧接在当前操作之后执行的任务，例如 promise 回调。微任务队列在宏任务队列之前处理，确保微任务尽快执行。\n\n***\n\n## 微任务队列的概念\n\n### 什么是微任务队列？\n\n微任务队列是 JavaScript 事件循环机制的一部分。它是一个队列，用于保存需要在当前执行的脚本之后和宏任务队列中的任何其他任务之前执行的任务。微任务通常用于需要尽快执行的操作，例如 promise 回调和 `MutationObserver` 回调。\n\n### 微任务队列如何工作？\n\n1. **执行顺序**：微任务队列在当前执行的脚本之后和宏任务队列之前处理。这意味着微任务的优先级高于宏任务。\n2. **事件循环**：在事件循环的每次迭代期间，JavaScript 引擎首先处理微任务队列中的所有微任务，然后再转到宏任务队列。\n3. **添加微任务**：可以使用 `Promise.resolve().then()` 和 `queueMicrotask()` 等方法将微任务添加到微任务队列中。\n\n### 例子\n\n这里有一个例子来说明微任务队列的工作原理：\n\n```js live\nconsole.log('Script start');\n\nsetTimeout(() => {\n  console.log('setTimeout');\n}, 0);\n\nPromise.resolve()\n  .then(() => {\n    console.log('Promise 1');\n  })\n  .then(() => {\n    console.log('Promise 2');\n  });\n\nconsole.log('Script end');\n```\n\n输出：\n\n```\nScript start\nScript end\nPromise 1\nPromise 2\nsetTimeout\n```\n\n在这个例子中：\n\n* 同步代码（`console.log('Script start')` 和 `console.log('Script end')`）首先执行。\n* promise 回调（`Promise 1` 和 `Promise 2`）被添加到微任务队列中，然后执行。\n* `setTimeout` 回调被添加到宏任务队列中，最后执行。\n\n### 用例\n\n1. **Promise 回调**：微任务通常用于 promise 回调，以确保它们在当前操作之后尽快执行。\n2. **MutationObserver**：`MutationObserver` API 使用微任务来通知 DOM 中的更改。\n\n## 延伸阅读\n\n* [MDN Web 文档：微任务](https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide)\n* [JavaScript 事件循环解释](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop)\n* [理解 JavaScript 微任务队列](https://javascript.info/microtask-queue)\n"
  },
  {
    "path": "questions/explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"c319828f\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"ef12deaa\",\n        \"2a7816d0\",\n        \"1f4647e1\",\n        \"b37a3266\",\n        \"407a0694\",\n        \"a3cd695d\",\n        \"24ce942e\",\n        \"6713c940\",\n        \"a4184ac7\",\n        \"a8313a18\",\n        \"46c46edc\",\n        \"b63a5de5\",\n        \"a3119474\",\n        \"76d52f4f\",\n        \"baef3852\",\n        \"9e416e41\",\n        \"837073c9\",\n        \"9408fe7b\",\n        \"6a91f2ea\",\n        \"cc9c3f80\",\n        \"f8e26a92\",\n        \"2727d1ce\",\n        \"5e1cd08a\",\n        \"928b5db7\",\n        \"8a9928c8\",\n        \"aabd55a0\",\n        \"1f4770e5\",\n        \"4a178175\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"ef12deaa\",\n        \"2a7816d0\",\n        \"1f4647e1\",\n        \"b37a3266\",\n        \"407a0694\",\n        \"a3cd695d\",\n        \"24ce942e\",\n        \"6713c940\",\n        \"a4184ac7\",\n        \"a8313a18\",\n        \"46c46edc\",\n        \"b63a5de5\",\n        \"a3119474\",\n        \"76d52f4f\",\n        \"baef3852\",\n        \"9e416e41\",\n        \"837073c9\",\n        \"9408fe7b\",\n        \"6a91f2ea\",\n        \"cc9c3f80\",\n        \"f8e26a92\",\n        \"2727d1ce\",\n        \"5e1cd08a\",\n        \"928b5db7\",\n        \"8a9928c8\",\n        \"aabd55a0\",\n        \"1f4770e5\",\n        \"4a178175\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance/en-US.mdx",
    "content": "---\ntitle: Explain the concept of caching and how it can be used to improve performance\n---\n\n## TL;DR\n\nCaching is a technique used to store copies of files or data in a temporary storage location to reduce the time it takes to access them. It improves performance by reducing the need to fetch data from the original source repeatedly. In front end development, caching can be implemented using browser cache, service workers, and HTTP headers like `Cache-Control`.\n\n---\n\n## The concept of caching and how it can be used to improve performance\n\n### What is caching?\n\nCaching is a technique used to store copies of files or data in a temporary storage location, known as a cache, to reduce the time it takes to access them. The primary goal of caching is to improve performance by minimizing the need to fetch data from the original source repeatedly.\n\n### Types of caching\n\n#### Browser cache\n\nThe browser cache stores copies of web pages, images, and other resources locally on the user's device. When a user revisits a website, the browser can load these resources from the cache instead of fetching them from the server, resulting in faster load times.\n\n#### Service workers\n\nService workers are scripts that run in the background and can intercept network requests. They can cache resources and serve them from the cache, even when the user is offline. This can significantly improve performance and provide a better user experience.\n\n#### HTTP caching\n\nHTTP caching involves using HTTP headers to control how and when resources are cached. Common headers include `Cache-Control`, `Expires`, and `ETag`.\n\n### How caching improves performance\n\n#### Reduced latency\n\nBy storing frequently accessed data closer to the user, caching reduces the time it takes to retrieve that data. This results in faster load times and a smoother user experience.\n\n#### Reduced server load\n\nCaching reduces the number of requests made to the server, which can help decrease server load and improve overall performance.\n\n#### Offline access\n\nWith service workers, cached resources can be served even when the user is offline, providing a seamless experience.\n\n### Implementing caching\n\n#### Browser cache example\n\n```html\n<head>\n  <link rel=\"stylesheet\" href=\"styles.css\" />\n  <script src=\"app.js\"></script>\n</head>\n```\n\n#### Service worker example\n\n```js\nself.addEventListener('install', (event) => {\n  event.waitUntil(\n    caches.open('v1').then((cache) => {\n      return cache.addAll(['/index.html', '/styles.css', '/app.js']);\n    }),\n  );\n});\n\nself.addEventListener('fetch', (event) => {\n  event.respondWith(\n    caches.match(event.request).then((response) => {\n      return response || fetch(event.request);\n    }),\n  );\n});\n```\n\n#### HTTP caching example\n\n```http\nCache-Control: max-age=3600\n```\n\n## Further reading\n\n- [MDN Web Docs: HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching)\n- [Google Developers: The offline cookbook](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook)\n- [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers)\n"
  },
  {
    "path": "questions/explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"performance\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Performance Optimization\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-caching-and-how-it-can-be-used-to-improve-performance/zh-CN.mdx",
    "content": "---\ntitle: 解释缓存的概念以及如何使用它来提高性能\n---\n\n## TL;DR\n\n缓存是一种用于存储文件或数据的副本的临时存储技术，以减少访问它们所需的时间。它通过减少重复从原始来源获取数据的需要来提高性能。在前端开发中，可以使用浏览器缓存、service workers 和 HTTP 标头（如 `Cache-Control`）来实现缓存。\n\n***\n\n## 缓存的概念以及如何使用它来提高性能\n\n### 什么是缓存？\n\n缓存是一种用于将文件或数据的副本存储在临时存储位置（称为缓存）中的技术，以减少访问它们所需的时间。缓存的主要目标是通过最大限度地减少重复从原始来源获取数据的需要来提高性能。\n\n### 缓存的类型\n\n#### 浏览器缓存\n\n浏览器缓存将网页、图像和其他资源的副本存储在用户设备的本地。当用户重新访问网站时，浏览器可以从缓存中加载这些资源，而不是从服务器获取它们，从而加快加载时间。\n\n#### Service workers\n\nService workers 是在后台运行的脚本，可以拦截网络请求。它们可以缓存资源并从缓存中提供它们，即使在用户离线时也是如此。这可以显著提高性能并提供更好的用户体验。\n\n#### HTTP 缓存\n\nHTTP 缓存涉及使用 HTTP 标头来控制如何以及何时缓存资源。常见的标头包括 `Cache-Control`、`Expires` 和 `ETag`。\n\n### 缓存如何提高性能\n\n#### 减少延迟\n\n通过将经常访问的数据存储在更靠近用户的位置，缓存减少了检索该数据所需的时间。这可以加快加载时间并提供更流畅的用户体验。\n\n#### 减少服务器负载\n\n缓存减少了向服务器发出的请求数量，这有助于减少服务器负载并提高整体性能。\n\n#### 离线访问\n\n通过 Service Worker，即使在用户离线时也可以提供缓存的资源，从而提供无缝体验。\n\n### 实现缓存\n\n#### 浏览器缓存示例\n\n```html\n<head>\n  <link rel=\"stylesheet\" href=\"styles.css\" />\n  <script src=\"app.js\"></script>\n</head>\n```\n\n#### Service worker 示例\n\n```js\nself.addEventListener('install', (event) => {\n  event.waitUntil(\n    caches.open('v1').then((cache) => {\n      return cache.addAll(['/index.html', '/styles.css', '/app.js']);\n    }),\n  );\n});\n\nself.addEventListener('fetch', (event) => {\n  event.respondWith(\n    caches.match(event.request).then((response) => {\n      return response || fetch(event.request);\n    }),\n  );\n});\n```\n\n#### HTTP 缓存示例\n\n```http\nCache-Control: max-age=3600\n```\n\n## 延伸阅读\n\n* [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers)\n"
  },
  {
    "path": "questions/explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"5b42839e\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"172ffd1e\",\n        \"2a7816d0\",\n        \"29768a8e\",\n        \"baf6db58\",\n        \"5f376a2\",\n        \"7019970f\",\n        \"9b5019f0\",\n        \"5ab8d5da\",\n        \"44a93b82\",\n        \"3ac49af5\",\n        \"acf59446\",\n        \"a55554af\",\n        \"d76d861f\",\n        \"dbf5de9e\",\n        \"4d3c2eaf\",\n        \"63e37a1f\",\n        \"46ed72e3\",\n        \"a87ced2\",\n        \"1a83fd81\",\n        \"8795769d\",\n        \"2819c383\",\n        \"66e3a020\",\n        \"5fedbc8e\",\n        \"d4ed1627\",\n        \"1f4770e5\",\n        \"2293135e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"172ffd1e\",\n        \"2a7816d0\",\n        \"29768a8e\",\n        \"baf6db58\",\n        \"5f376a2\",\n        \"7019970f\",\n        \"9b5019f0\",\n        \"5ab8d5da\",\n        \"44a93b82\",\n        \"3ac49af5\",\n        \"acf59446\",\n        \"a55554af\",\n        \"d76d861f\",\n        \"dbf5de9e\",\n        \"4d3c2eaf\",\n        \"63e37a1f\",\n        \"46ed72e3\",\n        \"a87ced2\",\n        \"1a83fd81\",\n        \"8795769d\",\n        \"2819c383\",\n        \"66e3a020\",\n        \"5fedbc8e\",\n        \"d4ed1627\",\n        \"1f4770e5\",\n        \"2293135e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality/en-US.mdx",
    "content": "---\ntitle: Explain the concept of code coverage and how it can be used to assess test quality\n---\n\n## TL;DR\n\nCode coverage is a metric that measures the percentage of code that is executed when the test suite runs. It helps in assessing the quality of tests by identifying untested parts of the codebase. Higher code coverage generally indicates more thorough testing, but it doesn't guarantee the absence of bugs. Tools like Istanbul or Jest can be used to measure code coverage.\n\n---\n\n## What is code coverage?\n\nCode coverage is a software testing metric that determines the amount of code that is executed during automated tests. It provides insights into which parts of the codebase are being tested and which are not.\n\n### Types of code coverage\n\n1. **Statement coverage**: Measures the number of statements in the code that have been executed.\n2. **Branch coverage**: Measures whether each branch (e.g., `if` and `else` blocks) has been executed.\n3. **Function coverage**: Measures whether each function in the code has been called.\n4. **Line coverage**: Measures the number of lines of code that have been executed.\n5. **Condition coverage**: Measures whether each boolean sub-expression has been evaluated to both true and false.\n\n### Example\n\nConsider the following JavaScript function:\n\n```js\nfunction isEven(num) {\n  if (num % 2 === 0) {\n    return true;\n  } else {\n    return false;\n  }\n}\n```\n\nA test suite for this function might look like this:\n\n```js\ntest('isEven returns true for even numbers', () => {\n  expect(isEven(2)).toBe(true);\n});\n\ntest('isEven returns false for odd numbers', () => {\n  expect(isEven(3)).toBe(false);\n});\n```\n\nRunning code coverage tools on this test suite would show 100% statement, branch, function, and line coverage because all parts of the code are executed.\n\n## How to measure code coverage\n\n### Tools\n\n1. **Istanbul**: A popular JavaScript code coverage tool.\n2. **Jest**: A testing framework that includes built-in code coverage reporting.\n3. **Karma**: A test runner that can be configured to use Istanbul for code coverage.\n\n### Example with Jest\n\nTo measure code coverage with Jest, you can add the `--coverage` flag when running your tests:\n\n```bash\njest --coverage\n```\n\nThis will generate a coverage report that shows the percentage of code covered by your tests.\n\n## Assessing test quality with code coverage\n\n### Benefits\n\n- **Identifies untested code**: Helps in finding parts of the codebase that are not covered by tests.\n- **Improves test suite**: Encourages writing more comprehensive tests.\n- **Increases confidence**: Higher coverage can increase confidence in the stability of the code.\n\n### Limitations\n\n- **False sense of security**: High coverage does not guarantee the absence of bugs.\n- **Quality over quantity**: 100% coverage does not mean the tests are of high quality. Tests should also check for edge cases and potential errors.\n\n## Further reading\n\n- [Istanbul documentation](https://istanbul.js.org/)\n- [Jest code coverage](https://jestjs.io/docs/en/coverage)\n- [Karma coverage](https://karma-runner.github.io/6.3/intro/installation.html)\n"
  },
  {
    "path": "questions/explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"testing\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Testing\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-code-coverage-and-how-it-can-be-used-to-assess-test-quality/zh-CN.mdx",
    "content": "---\ntitle: 解释代码覆盖率的概念以及如何使用它来评估测试质量\n---\n\n## TL;DR\n\n代码覆盖率是一个衡量测试套件运行时执行代码百分比的指标。它通过识别代码库中未测试的部分来帮助评估测试的质量。较高的代码覆盖率通常表明测试更彻底，但并不能保证没有错误。可以使用 Istanbul 或 Jest 等工具来衡量代码覆盖率。\n\n***\n\n## 什么是代码覆盖率？\n\n代码覆盖率是一个软件测试指标，用于确定在自动化测试期间执行的代码量。它提供了关于代码库的哪些部分正在被测试以及哪些部分没有被测试的见解。\n\n### 代码覆盖率的类型\n\n1. **语句覆盖率**：衡量已执行的代码中的语句数量。\n2. **分支覆盖率**：衡量每个分支（例如，`if` 和 `else` 块）是否已被执行。\n3. **函数覆盖率**：衡量代码中每个函数是否已被调用。\n4. **行覆盖率**：衡量已执行的代码行数。\n5. **条件覆盖率**：衡量每个布尔子表达式是否已被评估为真和假。\n\n### 示例\n\n考虑以下 JavaScript 函数：\n\n```js\nfunction isEven(num) {\n  if (num % 2 === 0) {\n    return true;\n  } else {\n    return false;\n  }\n}\n```\n\n此函数的测试套件可能如下所示：\n\n```js\ntest('isEven returns true for even numbers', () => {\n  expect(isEven(2)).toBe(true);\n});\n\ntest('isEven returns false for odd numbers', () => {\n  expect(isEven(3)).toBe(false);\n});\n```\n\n在此测试套件上运行代码覆盖率工具将显示 100% 的语句、分支、函数和行覆盖率，因为代码的所有部分都已执行。\n\n## 如何衡量代码覆盖率\n\n### 工具\n\n1. **Istanbul**：一个流行的 JavaScript 代码覆盖率工具。\n2. **Jest**：一个测试框架，包含内置的代码覆盖率报告。\n3. **Karma**：一个测试运行器，可以配置为使用 Istanbul 进行代码覆盖率。\n\n### 使用 Jest 的示例\n\n要使用 Jest 衡量代码覆盖率，您可以在运行测试时添加 `--coverage` 标志：\n\n```bash\njest --coverage\n```\n\n这将生成一个覆盖率报告，显示测试覆盖代码的百分比。\n\n## 使用代码覆盖率评估测试质量\n\n### 优点\n\n* **识别未测试的代码**：帮助找到未被测试覆盖的代码库部分。\n* **改进测试套件**：鼓励编写更全面的测试。\n* **增加信心**：更高的覆盖率可以增加对代码稳定性的信心。\n\n### 局限性\n\n* **虚假的安全感**：高覆盖率并不能保证没有错误。\n* **质量胜于数量**：100% 的覆盖率并不意味着测试质量高。测试还应检查边缘情况和潜在错误。\n\n## 延伸阅读\n\n* [Istanbul documentation](https://istanbul.js.org/)\n* [Jest code coverage](https://jestjs.io/docs/en/coverage)\n* [Karma coverage](https://karma-runner.github.io/6.3/intro/installation.html)\n"
  },
  {
    "path": "questions/explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"448c8185\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"293595c9\",\n        \"e41980b\",\n        \"2a7816d0\",\n        \"ba31e354\",\n        \"6f16ff94\",\n        \"e1c74fc9\",\n        \"b50e2cf4\",\n        \"eebac08f\",\n        \"adec322a\",\n        \"e41980b\",\n        \"1aafcf07\",\n        \"e0339a0\",\n        \"e9f379fa\",\n        \"3e11ad53\",\n        \"e37344eb\",\n        \"8f8fc594\",\n        \"c8c62017\",\n        \"915e71f8\",\n        \"3a463542\",\n        \"6a4d595f\",\n        \"849eb731\",\n        \"1f4770e5\",\n        \"a2eeaa\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"293595c9\",\n        \"e41980b\",\n        \"2a7816d0\",\n        \"ba31e354\",\n        \"6f16ff94\",\n        \"e1c74fc9\",\n        \"b50e2cf4\",\n        \"eebac08f\",\n        \"adec322a\",\n        \"e41980b\",\n        \"1aafcf07\",\n        \"e0339a0\",\n        \"e9f379fa\",\n        \"3e11ad53\",\n        \"e37344eb\",\n        \"8f8fc594\",\n        \"c8c62017\",\n        \"915e71f8\",\n        \"3a463542\",\n        \"6a4d595f\",\n        \"849eb731\",\n        \"1f4770e5\",\n        \"a2eeaa\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security/en-US.mdx",
    "content": "---\ntitle: Explain the concept of Content Security Policy (CSP) and how it enhances security\n---\n\n## TL;DR\n\nContent Security Policy (CSP) is a security feature that helps prevent various types of attacks, such as Cross-Site Scripting (XSS) and data injection attacks, by specifying which content sources are trusted. It works by allowing developers to define a whitelist of trusted sources for content like scripts, styles, and images. This is done through HTTP headers or meta tags. For example, you can use the `Content-Security-Policy` header to specify that only scripts from your own domain should be executed:\n\n```http\nContent-Security-Policy: script-src 'self'\n```\n\n---\n\n## What is Content Security Policy (CSP)?\n\nContent Security Policy (CSP) is a security standard introduced to mitigate a range of attacks, including Cross-Site Scripting (XSS) and data injection attacks. CSP allows web developers to control the resources that a user agent is allowed to load for a given page. By specifying a whitelist of trusted content sources, CSP helps to prevent the execution of malicious content.\n\n### How CSP works\n\nCSP works by allowing developers to define a set of rules that specify which sources of content are considered trustworthy. These rules are delivered to the browser via HTTP headers or meta tags. When the browser loads a page, it checks the CSP rules and blocks any content that does not match the specified sources.\n\n### Example of a CSP header\n\nHere is an example of a simple CSP header that only allows scripts from the same origin:\n\n```http\nContent-Security-Policy: script-src 'self'\n```\n\nThis policy tells the browser to only execute scripts that are loaded from the same origin as the page itself.\n\n### Common directives\n\n- `default-src`: Serves as a fallback for other resource types when they are not explicitly defined.\n- `script-src`: Specifies valid sources for JavaScript.\n- `style-src`: Specifies valid sources for CSS.\n- `img-src`: Specifies valid sources for images.\n- `connect-src`: Specifies valid sources for AJAX, WebSocket, and EventSource connections.\n- `font-src`: Specifies valid sources for fonts.\n- `object-src`: Specifies valid sources for plugins like Flash.\n\n### Benefits of using CSP\n\n- **Mitigates XSS attacks**: By restricting the sources from which scripts can be loaded, CSP helps to prevent the execution of malicious scripts.\n- **Prevents data injection attacks**: CSP can block the loading of malicious resources that could be used to steal data or perform other harmful actions.\n- **Improves security posture**: Implementing CSP is a proactive measure that enhances the overall security of a web application.\n\n### Implementing CSP\n\nCSP can be implemented using HTTP headers or meta tags. The HTTP header approach is generally preferred because it is more secure and cannot be easily overridden by attackers.\n\n#### Using HTTP headers\n\n```http\nContent-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com\n```\n\n#### Using meta tags\n\n```html\n<meta\n  http-equiv=\"Content-Security-Policy\"\n  content=\"default-src 'self'; script-src 'self' https://trusted.cdn.com\" />\n```\n\n## Further reading\n\n- [MDN Web Docs: Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n- [OWASP: Content Security Policy](https://owasp.org/www-project-secure-headers/#content-security-policy)\n- [Google Developers: CSP: Content Security Policy](https://developers.google.com/web/fundamentals/security/csp)\n"
  },
  {
    "path": "questions/explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Security\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-content-security-policy-csp-and-how-it-enhances-security/zh-CN.mdx",
    "content": "---\ntitle: 解释内容安全策略 (CSP) 的概念以及它如何增强安全性\n---\n\n## 总结\n\n内容安全策略 (CSP) 是一项安全功能，通过指定受信任的内容来源，帮助防止各种类型的攻击，例如跨站点脚本 (XSS) 和数据注入攻击。它的工作原理是允许开发人员定义一个受信任的脚本、样式和图像等内容来源的白名单。这通过 HTTP 标头或 meta 标签完成。例如，您可以使用 `Content-Security-Policy` 标头来指定仅应执行来自您自己域的脚本：\n\n```http\nContent-Security-Policy: script-src 'self'\n```\n\n***\n\n## 什么是内容安全策略 (CSP)？\n\n内容安全策略 (CSP) 是一项安全标准，旨在缓解一系列攻击，包括跨站点脚本 (XSS) 和数据注入攻击。CSP 允许 Web 开发人员控制用户代理允许为给定页面加载的资源。通过指定受信任内容来源的白名单，CSP 有助于防止恶意内容的执行。\n\n### CSP 的工作原理\n\nCSP 的工作原理是允许开发人员定义一组规则，用于指定哪些内容来源被认为是可信的。这些规则通过 HTTP 标头或 meta 标签传递给浏览器。当浏览器加载页面时，它会检查 CSP 规则并阻止任何与指定来源不匹配的内容。\n\n### CSP 标头的示例\n\n以下是一个简单的 CSP 标头的示例，该标头仅允许来自同一来源的脚本：\n\n```http\nContent-Security-Policy: script-src 'self'\n```\n\n此策略告诉浏览器仅执行从与页面本身相同的来源加载的脚本。\n\n### 常用指令\n\n* `object-src`：指定 Flash 等插件的有效来源。\n\n### 使用 CSP 的好处\n\n* **提高安全态势**：实施 CSP 是一项积极措施，可增强 Web 应用程序的整体安全性。\n\n### 实施 CSP\n\n可以使用 HTTP 标头或 meta 标签来实现 CSP。通常首选 HTTP 标头方法，因为它更安全，并且不易被攻击者覆盖。\n\n#### 使用 HTTP 标头\n\n```http\nContent-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com\n```\n\n#### 使用 meta 标签\n\n```html\n<meta\n  http-equiv=\"Content-Security-Policy\"\n  content=\"default-src 'self'; script-src 'self' https://trusted.cdn.com\" />\n```\n\n## 延伸阅读\n\n* [Google Developers: CSP: Content Security Policy](https://developers.google.com/web/fundamentals/security/csp)\n"
  },
  {
    "path": "questions/explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"263ed28c\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"87635176\",\n        \"2a7816d0\",\n        \"2683cb4e\",\n        \"26674715\",\n        \"1c4ea590\",\n        \"6e8f2ac6\",\n        \"8ad02911\",\n        \"3c08d812\",\n        \"918297ff\",\n        \"716b84bd\",\n        \"e07ea3e9\",\n        \"f18f1c05\",\n        \"2b3416e4\",\n        \"3011309e\",\n        \"4633a4e8\",\n        \"185d59b4\",\n        \"1456e5c7\",\n        \"3ed327fb\",\n        \"2b3a8c8b\",\n        \"79360ef1\",\n        \"c835929b\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"87635176\",\n        \"2a7816d0\",\n        \"2683cb4e\",\n        \"26674715\",\n        \"1c4ea590\",\n        \"6e8f2ac6\",\n        \"8ad02911\",\n        \"3c08d812\",\n        \"918297ff\",\n        \"716b84bd\",\n        \"e07ea3e9\",\n        \"f18f1c05\",\n        \"2b3416e4\",\n        \"3011309e\",\n        \"4633a4e8\",\n        \"185d59b4\",\n        \"1456e5c7\",\n        \"3ed327fb\",\n        \"2b3a8c8b\",\n        \"79360ef1\",\n        \"c835929b\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques/en-US.mdx",
    "content": "---\ntitle: Explain the concept of Cross-Site Request Forgery (CSRF) and its mitigation techniques\n---\n\n## TL;DR\n\nCross-Site Request Forgery (CSRF) is an attack where a malicious website tricks a user's browser into making an unwanted request to another site where the user is authenticated. This can lead to unauthorized actions being performed on behalf of the user. Mitigation techniques include using anti-CSRF tokens, SameSite cookies, and ensuring proper CORS configurations.\n\n---\n\n## Cross-Site Request Forgery (CSRF) and its mitigation techniques\n\n### What is CSRF?\n\nCross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious website causes a user's browser to perform an unwanted action on a different site where the user is authenticated. This can lead to unauthorized actions such as changing account details, making purchases, or other actions that the user did not intend to perform.\n\n### How does CSRF work?\n\n1. **User authentication**: The user logs into a trusted website (e.g., a banking site) and receives an authentication cookie.\n2. **Malicious site**: The user visits a malicious website while still logged into the trusted site.\n3. **Unwanted request**: The malicious site contains code that makes a request to the trusted site, using the user's authentication cookie to perform actions on behalf of the user.\n\n### Mitigation techniques\n\n#### Anti-CSRF tokens\n\nOne of the most effective ways to prevent CSRF attacks is by using anti-CSRF tokens. These tokens are unique and unpredictable values that are generated by the server and included in forms or requests. The server then validates the token to ensure the request is legitimate.\n\n```html\n<form method=\"POST\" action=\"/update-profile\">\n  <input type=\"hidden\" name=\"csrf_token\" value=\"unique_token_value\" />\n  <!-- other form fields -->\n  <button type=\"submit\">Update Profile</button>\n</form>\n```\n\nOn the server side, the token is validated to ensure it matches the expected value.\n\n#### SameSite cookies\n\nThe `SameSite` attribute on cookies can help mitigate CSRF attacks by restricting how cookies are sent with cross-site requests. The `SameSite` attribute can be set to `Strict`, `Lax`, or `None`.\n\n```http\nSet-Cookie: sessionId=abc123; SameSite=Strict\n```\n\n- `Strict`: Cookies are only sent in a first-party context and not with requests initiated by third-party websites.\n- `Lax`: Cookies are not sent on normal cross-site subrequests (e.g., loading images), but are sent when a user navigates to the URL from an external site (e.g., following a link).\n- `None`: Cookies are sent in all contexts, including cross-origin requests.\n\n#### CORS (Cross-Origin Resource Sharing)\n\nProperly configuring CORS can help prevent CSRF attacks by ensuring that only trusted origins can make requests to your server. This involves setting appropriate headers on the server to specify which origins are allowed to access resources.\n\n```http\nAccess-Control-Allow-Origin: https://trustedwebsite.com\n```\n\n### Further reading\n\n- [OWASP CSRF Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)\n- [MDN Web Docs: SameSite cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite)\n- [MDN Web Docs: Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)\n"
  },
  {
    "path": "questions/explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"networking\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Security\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-cross-site-request-forgery-csrf-and-its-mitigation-techniques/zh-CN.mdx",
    "content": "---\ntitle: 解释跨站点请求伪造 (CSRF) 的概念及其缓解技术\n---\n\n## TL;DR\n\n跨站点请求伪造 (CSRF) 是一种攻击，恶意网站会诱骗用户的浏览器向用户已通过身份验证的另一个站点发出不需要的请求。这可能导致代表用户执行未经授权的操作。缓解技术包括使用反 CSRF 令牌、SameSite cookie 和确保适当的 CORS 配置。\n\n***\n\n## 跨站点请求伪造 (CSRF) 及其缓解技术\n\n### 什么是 CSRF？\n\n跨站点请求伪造 (CSRF) 是一种攻击类型，当恶意网站导致用户的浏览器在用户已通过身份验证的不同站点上执行不需要的操作时，就会发生这种攻击。这可能导致未经授权的操作，例如更改帐户详细信息、进行购买或其他用户无意执行的操作。\n\n### CSRF 如何工作？\n\n1. **用户身份验证**：用户登录到受信任的网站（例如，银行网站）并收到身份验证 cookie。\n2. **恶意网站**：用户在仍登录到受信任网站的情况下访问恶意网站。\n3. **不需要的请求**：恶意网站包含向受信任网站发出请求的代码，使用用户的身份验证 cookie 代表用户执行操作。\n\n### 缓解技术\n\n#### 反 CSRF 令牌\n\n防止 CSRF 攻击的最有效方法之一是使用反 CSRF 令牌。这些令牌是服务器生成的、包含在表单或请求中的唯一且不可预测的值。然后，服务器验证该令牌以确保请求是合法的。\n\n```html\n<form method=\"POST\" action=\"/update-profile\">\n  <input type=\"hidden\" name=\"csrf_token\" value=\"unique_token_value\" />\n  <!-- other form fields -->\n  <button type=\"submit\">Update Profile</button>\n</form>\n```\n\n在服务器端，验证令牌以确保它与预期值匹配。\n\n#### SameSite cookie\n\ncookie 上的 `SameSite` 属性可以通过限制 cookie 如何与跨站点请求一起发送来帮助缓解 CSRF 攻击。`SameSite` 属性可以设置为 `Strict`、`Lax` 或 `None`。\n\n```http\nSet-Cookie: sessionId=abc123; SameSite=Strict\n```\n\n* `Strict`：Cookie 仅在第一方上下文中发送，而不是与第三方网站发起的请求一起发送。\n* `Lax`：Cookie 不会通过正常的跨站点子请求（例如，加载图像）发送，但会在用户从外部站点导航到 URL 时发送（例如，点击链接）。\n* `None`：Cookie 在所有上下文中发送，包括跨源请求。\n\n#### CORS（跨源资源共享）\n\n正确配置 CORS 可以通过确保只有受信任的来源才能向您的服务器发出请求来帮助防止 CSRF 攻击。这涉及在服务器上设置适当的标头以指定允许访问资源的来源。\n\n```http\nAccess-Control-Allow-Origin: https://trustedwebsite.com\n```\n\n### 延伸阅读\n\n* [OWASP CSRF 预防备忘单](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)\n* [MDN Web 文档：SameSite cookies](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie/SameSite)\n* [MDN Web 文档：跨域资源共享 (CORS)](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS)\n"
  },
  {
    "path": "questions/explain-the-concept-of-debouncing-and-throttling/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"bdb54e0f\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"e0bf0fc6\",\n        \"8fe99b1c\",\n        \"b6ceacae\",\n        \"df0d9f8b\",\n        \"144aee45\",\n        \"2a7816d0\",\n        \"82338611\",\n        \"d5ddf6d9\",\n        \"9c54cfc4\",\n        \"9ba6aae0\",\n        \"c6877016\",\n        \"27dc1cb7\",\n        \"1d469c45\",\n        \"e0d93fc8\",\n        \"8f5e5605\",\n        \"9ba6aae0\",\n        \"8e8faeff\",\n        \"27dc1cb7\",\n        \"a188391e\",\n        \"1f4770e5\",\n        \"3eb83cab\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"e0bf0fc6\",\n        \"8fe99b1c\",\n        \"b6ceacae\",\n        \"df0d9f8b\",\n        \"144aee45\",\n        \"2a7816d0\",\n        \"82338611\",\n        \"d5ddf6d9\",\n        \"9c54cfc4\",\n        \"9ba6aae0\",\n        \"c6877016\",\n        \"27dc1cb7\",\n        \"1d469c45\",\n        \"e0d93fc8\",\n        \"8f5e5605\",\n        \"9ba6aae0\",\n        \"8e8faeff\",\n        \"27dc1cb7\",\n        \"a188391e\",\n        \"1f4770e5\",\n        \"3eb83cab\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-debouncing-and-throttling/en-US.mdx",
    "content": "---\ntitle: Explain the concept of debouncing and throttling\n---\n\n## TL;DR\n\nDebouncing and throttling are techniques used to control the rate at which a function is executed. Debouncing ensures that a function is only called after a specified delay has passed since the last time it was invoked. Throttling ensures that a function is called at most once in a specified time interval.\n\nDebouncing delays the execution of a function until a certain amount of time has passed since it was last called. This is useful for scenarios like search input fields where you want to wait until the user has stopped typing before making an API call.\n\n```js live\nfunction debounce(func, delay) {\n  let timeoutId;\n  return function (...args) {\n    clearTimeout(timeoutId);\n    timeoutId = setTimeout(() => func.apply(this, args), delay);\n  };\n}\n\nconst debouncedHello = debounce(() => console.log('Hello world!'), 2000);\ndebouncedHello(); // Prints 'Hello world!' after 2 seconds\n```\n\nThrottling ensures that a function is called at most once in a specified time interval. This is useful for scenarios like window resizing or scrolling where you want to limit the number of times a function is called.\n\n```js live\nfunction throttle(func, limit) {\n  let inThrottle;\n  return function (...args) {\n    if (!inThrottle) {\n      func.apply(this, args);\n      inThrottle = true;\n      setTimeout(() => (inThrottle = false), limit);\n    }\n  };\n}\n\nconst handleResize = throttle(() => {\n  // Update element positions\n  console.log('Window resized at', new Date().toLocaleTimeString());\n}, 2000);\n\n// Simulate rapid calls to handleResize every 100ms\nlet intervalId = setInterval(() => {\n  handleResize();\n}, 100);\n// 'Window resized' is outputted only every 2 seconds due to throttling\n```\n\n---\n\n## Debouncing and throttling\n\n### Debouncing\n\nDebouncing is a technique used to ensure that a function is only executed after a certain amount of time has passed since it was last invoked. This is particularly useful in scenarios where you want to limit the number of times a function is called, such as when handling user input events like keypresses or mouse movements.\n\n#### Example use case\n\nImagine you have a search input field and you want to make an API call to fetch search results. Without debouncing, an API call would be made every time the user types a character, which could lead to a large number of unnecessary calls. Debouncing ensures that the API call is only made after the user has stopped typing for a specified amount of time.\n\n#### Code example\n\n```js\nfunction debounce(func, delay) {\n  let timeoutId;\n  return function (...args) {\n    clearTimeout(timeoutId);\n    timeoutId = setTimeout(() => func.apply(this, args), delay);\n  };\n}\n\n// Usage\nconst handleSearch = debounce((query) => {\n  // Make API call\n  console.log('API call with query:', query);\n}, 300);\n\ndocument.getElementById('searchInput').addEventListener('input', (event) => {\n  handleSearch(event.target.value);\n});\n```\n\n### Throttling\n\nThrottling is a technique used to ensure that a function is called at most once in a specified time interval. This is useful in scenarios where you want to limit the number of times a function is called, such as when handling events like window resizing or scrolling.\n\n#### Example use case\n\nImagine you have a function that updates the position of elements on the screen based on the window size. Without throttling, this function could be called many times per second as the user resizes the window, leading to performance issues. Throttling ensures that the function is only called at most once in a specified time interval.\n\n#### Code example\n\n```js live\nfunction throttle(func, limit) {\n  let inThrottle;\n  return function (...args) {\n    if (!inThrottle) {\n      func.apply(this, args);\n      inThrottle = true;\n      setTimeout(() => (inThrottle = false), limit);\n    }\n  };\n}\n\n// Usage\nconst handleResize = throttle(() => {\n  // Update element positions\n  console.log('Window resized');\n}, 100);\n\nwindow.addEventListener('resize', handleResize);\n```\n\n## Further reading\n\n- [Debouncing and Throttling Explained Through Examples](https://css-tricks.com/debouncing-throttling-explained-examples/)\n- [Understanding the Difference Between Debounce and Throttle](https://www.freecodecamp.org/news/javascript-debounce-example/)\n- [Lodash Documentation for Debounce and Throttle](https://lodash.com/docs/4.17.15#debounce)\n"
  },
  {
    "path": "questions/explain-the-concept-of-debouncing-and-throttling/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-debouncing-and-throttling\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"async\", \"javascript\", \"performance\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Performance Optimization\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-debouncing-and-throttling/zh-CN.mdx",
    "content": "---\ntitle: 解释防抖和节流的概念\n---\n\n## 总结\n\n防抖和节流是用于控制函数执行速率的技术。防抖确保函数仅在自上次调用后经过指定的延迟后才被调用。节流确保函数在一个指定的时间间隔内最多被调用一次。\n\n防抖会延迟函数的执行，直到自上次调用后经过一定的时间。这对于搜索输入框等场景非常有用，在这些场景中，您希望在用户停止输入后才进行 API 调用。\n\n```js live\nfunction debounce(func, delay) {\n  let timeoutId;\n  return function (...args) {\n    clearTimeout(timeoutId);\n    timeoutId = setTimeout(() => func.apply(this, args), delay);\n  };\n}\n\nconst debouncedHello = debounce(() => console.log('Hello world!'), 2000);\ndebouncedHello(); // Prints 'Hello world!' after 2 seconds\n```\n\n节流确保函数在一个指定的时间间隔内最多被调用一次。这对于窗口调整大小或滚动等场景非常有用，在这些场景中，您希望限制函数被调用的次数。\n\n```js live\nfunction throttle(func, limit) {\n  let inThrottle;\n  return function (...args) {\n    if (!inThrottle) {\n      func.apply(this, args);\n      inThrottle = true;\n      setTimeout(() => (inThrottle = false), limit);\n    }\n  };\n}\n\nconst handleResize = throttle(() => {\n  // Update element positions\n  console.log('Window resized at', new Date().toLocaleTimeString());\n}, 2000);\n\n// Simulate rapid calls to handleResize every 100ms\nlet intervalId = setInterval(() => {\n  handleResize();\n}, 100);\n// 'Window resized' is outputted only every 2 seconds due to throttling\n```\n\n***\n\n## 防抖和节流\n\n### 防抖\n\n防抖是一种技术，用于确保函数仅在自上次调用后经过一定时间后才执行。这在您希望限制函数被调用次数的场景中特别有用，例如处理用户输入事件（如按键或鼠标移动）。\n\n#### 使用案例\n\n想象一下，您有一个搜索输入框，并且您想进行 API 调用来获取搜索结果。如果没有防抖，每次用户输入一个字符时都会进行 API 调用，这可能会导致大量不必要的调用。防抖确保仅在用户停止输入指定时间后才进行 API 调用。\n\n#### 代码示例\n\n```js\nfunction debounce(func, delay) {\n  let timeoutId;\n  return function (...args) {\n    clearTimeout(timeoutId);\n    timeoutId = setTimeout(() => func.apply(this, args), delay);\n  };\n}\n\n// Usage\nconst handleSearch = debounce((query) => {\n  // Make API call\n  console.log('API call with query:', query);\n}, 300);\n\ndocument.getElementById('searchInput').addEventListener('input', (event) => {\n  handleSearch(event.target.value);\n});\n```\n\n### 节流\n\n节流是一种技术，用于确保函数在一个指定的时间间隔内最多被调用一次。这在您希望限制函数被调用次数的场景中很有用，例如处理窗口调整大小或滚动等事件。\n\n#### 使用案例\n\n想象一下，您有一个函数，该函数根据窗口大小更新屏幕上元素的位置。如果没有节流，此函数可能会在用户调整窗口大小时每秒被调用多次，从而导致性能问题。节流确保该函数在一个指定的时间间隔内最多被调用一次。\n\n#### 代码示例\n\n```js live\nfunction throttle(func, limit) {\n  let inThrottle;\n  return function (...args) {\n    if (!inThrottle) {\n      func.apply(this, args);\n      inThrottle = true;\n      setTimeout(() => (inThrottle = false), limit);\n    }\n  };\n}\n\n// Usage\nconst handleResize = throttle(() => {\n  // Update element positions\n  console.log('Window resized');\n}, 100);\n\nwindow.addEventListener('resize', handleResize);\n```\n\n## 延伸阅读\n\n* [通过示例解释防抖和节流](https://css-tricks.com/debouncing-throttling-explained-examples/)\n* [了解防抖和节流之间的区别](https://www.freecodecamp.org/news/javascript-debounce-example/)\n* [Lodash 防抖和节流文档](https://lodash.com/docs/4.17.15#debounce)\n"
  },
  {
    "path": "questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"4343f7ff\",\n        \"d65dad60\",\n        \"2a7816d0\",\n        \"bd111846\",\n        \"44c43879\",\n        \"ee39f737\",\n        \"6b1f535a\",\n        \"14d9b8fe\",\n        \"72b08533\",\n        \"c383de16\",\n        \"22806766\",\n        \"f716cedc\",\n        \"84b9dad0\",\n        \"b029411\",\n        \"4f964001\",\n        \"60999da7\",\n        \"9b4f8c58\",\n        \"14d9b8fe\",\n        \"9d23190e\",\n        \"35444153\",\n        \"99a35ee6\",\n        \"e3490dde\",\n        \"84b9dad0\",\n        \"d2015ad4\",\n        \"7e957edf\",\n        \"10b4a84f\",\n        \"1530bb48\",\n        \"21ba8ff5\",\n        \"1f4770e5\",\n        \"7973f9b8\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4343f7ff\",\n        \"d65dad60\",\n        \"2a7816d0\",\n        \"bd111846\",\n        \"44c43879\",\n        \"ee39f737\",\n        \"6b1f535a\",\n        \"14d9b8fe\",\n        \"72b08533\",\n        \"c383de16\",\n        \"22806766\",\n        \"f716cedc\",\n        \"84b9dad0\",\n        \"b029411\",\n        \"4f964001\",\n        \"60999da7\",\n        \"9b4f8c58\",\n        \"14d9b8fe\",\n        \"9d23190e\",\n        \"35444153\",\n        \"99a35ee6\",\n        \"e3490dde\",\n        \"84b9dad0\",\n        \"d2015ad4\",\n        \"7e957edf\",\n        \"10b4a84f\",\n        \"1530bb48\",\n        \"21ba8ff5\",\n        \"1f4770e5\",\n        \"7973f9b8\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"faf08055\"\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/en-US.mdx",
    "content": "---\ntitle: Explain the concept of destructuring assignment for objects and arrays\n---\n\n## TL;DR\n\nDestructuring assignment is a syntax in JavaScript that allows you to unpack values from arrays or properties from objects into distinct variables. For arrays, you use square brackets, and for objects, you use curly braces. For example:\n\n```js live\n// Array destructuring\nconst [a, b] = [1, 2];\n\n// Object destructuring\nconst { name, age } = { name: 'John', age: 30 };\n```\n\n---\n\n## Destructuring assignment for objects and arrays\n\nDestructuring assignment is a convenient way to extract values from arrays and objects into separate variables. This can make your code more readable and concise.\n\n### Array destructuring\n\nArray destructuring allows you to unpack values from arrays into distinct variables using square brackets.\n\n#### Basic example\n\n```js live\nconst numbers = [1, 2, 3];\nconst [first, second, third] = numbers;\n\nconsole.log(first); // 1\nconsole.log(second); // 2\nconsole.log(third); // 3\n```\n\n#### Skipping values\n\nYou can skip values in the array by leaving an empty space between commas.\n\n```js live\nconst numbers = [1, 2, 3];\nconst [first, , third] = numbers;\n\nconsole.log(first); // 1\nconsole.log(third); // 3\n```\n\n#### Default values\n\nYou can assign default values in case the array does not have enough elements.\n\n```js live\nconst numbers = [1];\nconst [first, second = 2] = numbers;\n\nconsole.log(first); // 1\nconsole.log(second); // 2\n```\n\n### Object destructuring\n\nObject destructuring allows you to unpack properties from objects into distinct variables using curly braces.\n\n#### Basic example\n\n```js live\nconst person = { name: 'John', age: 30 };\nconst { name, age } = person;\n\nconsole.log(name); // John\nconsole.log(age); // 30\n```\n\n#### Renaming variables\n\nYou can rename the variables while destructuring.\n\n```js live\nconst person = { name: 'John', age: 30 };\nconst { name: personName, age: personAge } = person;\n\nconsole.log(personName); // John\nconsole.log(personAge); // 30\n```\n\n#### Default values\n\nYou can assign default values in case the property does not exist in the object.\n\n```js live\nconst person = { name: 'John' };\nconst { name, age = 25 } = person;\n\nconsole.log(name); // John\nconsole.log(age); // 25\n```\n\n#### Nested objects\n\nYou can destructure nested objects as well.\n\n```js live\nconst person = { name: 'John', address: { city: 'New York', zip: '10001' } };\nconst {\n  name,\n  address: { city, zip },\n} = person;\n\nconsole.log(name); // John\nconsole.log(city); // New York\nconsole.log(zip); // 10001\n```\n\n## Further reading\n\n- [MDN Web Docs: Destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)\n- [JavaScript.info: Destructuring assignment](https://javascript.info/destructuring-assignment)\n- [FreeCodeCamp: How Destructuring Works in JavaScript](https://www.freecodecamp.org/news/destructuring-in-javascript/)\n"
  },
  {
    "path": "questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-destructuring-assignment-for-objects-and-arrays\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-destructuring-assignment-for-objects-and-arrays/zh-CN.mdx",
    "content": "---\ntitle: 解释对象和数组的解构赋值概念\n---\n\n## 总结\n\n解构赋值是 JavaScript 中的一种语法，它允许您将数组中的值或对象中的属性解包到不同的变量中。对于数组，您使用方括号，对于对象，您使用花括号。例如：\n\n```js live\n// 数组解构\nconst [a, b] = [1, 2];\n\n// 对象解构\nconst { name, age } = { name: 'John', age: 30 };\n```\n\n***\n\n## 对象和数组的解构赋值\n\n解构赋值是一种方便的方法，用于将数组和对象中的值提取到单独的变量中。这可以使您的代码更具可读性和简洁性。\n\n### 数组解构\n\n数组解构允许您使用方括号将数组中的值解包到不同的变量中。\n\n#### 基本示例\n\n```js live\nconst numbers = [1, 2, 3];\nconst [first, second, third] = numbers;\n\nconsole.log(first); // 1\nconsole.log(second); // 2\nconsole.log(third); // 3\n```\n\n#### 跳过值\n\n您可以通过在逗号之间留一个空格来跳过数组中的值。\n\n```js live\nconst numbers = [1, 2, 3];\nconst [first, , third] = numbers;\n\nconsole.log(first); // 1\nconsole.log(third); // 3\n```\n\n#### 默认值\n\n如果数组没有足够的元素，您可以分配默认值。\n\n```js live\nconst numbers = [1];\nconst [first, second = 2] = numbers;\n\nconsole.log(first); // 1\nconsole.log(second); // 2\n```\n\n### 对象解构\n\n对象解构允许您使用花括号将对象中的属性解包到不同的变量中。\n\n#### 基本示例\n\n```js live\nconst person = { name: 'John', age: 30 };\nconst { name, age } = person;\n\nconsole.log(name); // John\nconsole.log(age); // 30\n```\n\n#### 重命名变量\n\n您可以在解构时重命名变量。\n\n```js live\nconst person = { name: 'John', age: 30 };\nconst { name: personName, age: personAge } = person;\n\nconsole.log(personName); // John\nconsole.log(personAge); // 30\n```\n\n#### 默认值\n\n如果属性在对象中不存在，您可以分配默认值。\n\n```js live\nconst person = { name: 'John' };\nconst { name, age = 25 } = person;\n\nconsole.log(name); // John\nconsole.log(age); // 25\n```\n\n#### 嵌套对象\n\n您也可以解构嵌套对象。\n\n```js live\nconst person = { name: 'John', address: { city: 'New York', zip: '10001' } };\nconst {\n  name,\n  address: { city, zip },\n} = person;\n\nconsole.log(name); // John\nconsole.log(city); // New York\nconsole.log(zip); // 10001\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)\n* [JavaScript.info: Destructuring assignment](https://javascript.info/destructuring-assignment)\n* [FreeCodeCamp: How Destructuring Works in JavaScript](https://www.freecodecamp.org/news/destructuring-in-javascript/)\n"
  },
  {
    "path": "questions/explain-the-concept-of-error-propagation-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"37957fe\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"5b167941\",\n        \"ec95b57b\",\n        \"2a7816d0\",\n        \"8bf53bd5\",\n        \"e3442fc5\",\n        \"2961888\",\n        \"57146e71\",\n        \"cc9d21f9\",\n        \"2e84b21e\",\n        \"ec95b57b\",\n        \"be1d8b9a\",\n        \"187fe163\",\n        \"7f09e7d6\",\n        \"3718cbbf\",\n        \"d58fc766\",\n        \"3365175a\",\n        \"3b882e5b\",\n        \"649d13f3\",\n        \"1f4770e5\",\n        \"b03a35bb\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"5b167941\",\n        \"ec95b57b\",\n        \"2a7816d0\",\n        \"8bf53bd5\",\n        \"e3442fc5\",\n        \"2961888\",\n        \"57146e71\",\n        \"cc9d21f9\",\n        \"2e84b21e\",\n        \"ec95b57b\",\n        \"be1d8b9a\",\n        \"187fe163\",\n        \"7f09e7d6\",\n        \"3718cbbf\",\n        \"d58fc766\",\n        \"3365175a\",\n        \"3b882e5b\",\n        \"649d13f3\",\n        \"1f4770e5\",\n        \"b03a35bb\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-error-propagation-in-javascript/en-US.mdx",
    "content": "---\ntitle: Explain the concept of error propagation in JavaScript\n---\n\n## TL;DR\n\nError propagation in JavaScript refers to how errors are passed through the call stack. When an error occurs in a function, it can be caught and handled using `try...catch` blocks. If not caught, the error propagates up the call stack until it is either caught or causes the program to terminate. For example:\n\n```js live\nfunction a() {\n  throw new Error('An error occurred');\n}\n\nfunction b() {\n  a();\n}\n\ntry {\n  b();\n} catch (e) {\n  console.error(e.message); // Outputs: An error occurred\n}\n```\n\n---\n\n## Error propagation in JavaScript\n\nError propagation in JavaScript is a mechanism that allows errors to be passed up the call stack until they are caught and handled. This is crucial for debugging and ensuring that errors do not cause the entire application to crash unexpectedly.\n\n### How errors propagate\n\nWhen an error occurs in a function, it can either be caught and handled within that function or propagate up the call stack to the calling function. If the calling function does not handle the error, it continues to propagate up the stack until it reaches the global scope, potentially causing the program to terminate.\n\n### Using `try...catch` blocks\n\nTo handle errors and prevent them from propagating further, you can use `try...catch` blocks. Here is an example:\n\n```js live\nfunction a() {\n  throw new Error('An error occurred');\n}\n\nfunction b() {\n  a();\n}\n\ntry {\n  b();\n} catch (e) {\n  console.error(e.message); // Outputs: An error occurred\n}\n```\n\nIn this example, the error thrown in function `a` propagates to function `b`, and then to the `try...catch` block where it is finally caught and handled.\n\n### Propagation with asynchronous code\n\nError propagation works differently with asynchronous code, such as promises and `async/await`. For promises, you can use `.catch()` to handle errors:\n\n```js live\nfunction a() {\n  return Promise.reject(new Error('An error occurred'));\n}\n\nfunction b() {\n  return a();\n}\n\nb().catch((e) => {\n  console.error(e.message); // Outputs: An error occurred\n});\n```\n\nFor `async/await`, you can use `try...catch` blocks:\n\n```js live\nasync function a() {\n  throw new Error('An error occurred');\n}\n\nasync function b() {\n  await a();\n}\n\n(async () => {\n  try {\n    await b();\n  } catch (e) {\n    console.error(e.message); // Outputs: An error occurred\n  }\n})();\n```\n\n### Best practices\n\n- Always handle errors at the appropriate level to prevent them from propagating unnecessarily.\n- Use `try...catch` blocks for synchronous code and `.catch()` or `try...catch` with `async/await` for asynchronous code.\n- Log errors to help with debugging and provide meaningful error messages to users.\n\n## Further reading\n\n- [MDN Web Docs: Error handling](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#exception_handling_statements)\n- [JavaScript.info: Error handling, \"try...catch\"](https://javascript.info/try-catch)\n- [Node.js Error Handling Best Practices](https://nodejs.dev/learn/error-handling-in-nodejs)\n"
  },
  {
    "path": "questions/explain-the-concept-of-error-propagation-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-error-propagation-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Error Handling\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-error-propagation-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 中的错误传播概念\n---\n\n## TL;DR\n\nJavaScript 中的错误传播指的是错误如何通过调用堆栈传递。当函数中发生错误时，可以使用 `try...catch` 块捕获和处理它。如果未捕获，错误会沿着调用堆栈向上冒泡，直到它被捕获或导致程序终止。例如：\n\n```js live\nfunction a() {\n  throw new Error('An error occurred');\n}\n\nfunction b() {\n  a();\n}\n\ntry {\n  b();\n} catch (e) {\n  console.error(e.message); // Outputs: An error occurred\n}\n```\n\n***\n\n## JavaScript 中的错误传播\n\nJavaScript 中的错误传播是一种机制，它允许错误沿着调用堆栈传递，直到它们被捕获和处理。这对于调试和确保错误不会导致整个应用程序意外崩溃至关重要。\n\n### 错误如何传播\n\n当函数中发生错误时，它可以在该函数内被捕获和处理，或者沿着调用堆栈传递到调用函数。如果调用函数不处理该错误，它会继续在堆栈上传播，直到它到达全局范围，这可能会导致程序终止。\n\n### 使用 `try...catch` 块\n\n为了处理错误并防止它们进一步传播，您可以使用 `try...catch` 块。这是一个例子：\n\n```js live\nfunction a() {\n  throw new Error('An error occurred');\n}\n\nfunction b() {\n  a();\n}\n\ntry {\n  b();\n} catch (e) {\n  console.error(e.message); // Outputs: An error occurred\n}\n```\n\n在这个例子中，函数 `a` 中抛出的错误传播到函数 `b`，然后传播到 `try...catch` 块，在那里它最终被捕获和处理。\n\n### 异步代码的传播\n\n错误传播在异步代码（如 promises 和 `async/await`）中的工作方式有所不同。对于 promises，您可以使用 `.catch()` 来处理错误：\n\n```js live\nfunction a() {\n  return Promise.reject(new Error('An error occurred'));\n}\n\nfunction b() {\n  return a();\n}\n\nb().catch((e) => {\n  console.error(e.message); // Outputs: An error occurred\n});\n```\n\n对于 `async/await`，您可以使用 `try...catch` 块：\n\n```js live\nasync function a() {\n  throw new Error('An error occurred');\n}\n\nasync function b() {\n  await a();\n}\n\n(async () => {\n  try {\n    await b();\n  } catch (e) {\n    console.error(e.message); // Outputs: An error occurred\n  }\n})();\n```\n\n### 最佳实践\n\n* 始终在适当的级别处理错误，以防止它们不必要地传播。\n* 对同步代码使用 `try...catch` 块，对异步代码使用 `.catch()` 或带有 `async/await` 的 `try...catch`。\n* 记录错误以帮助调试，并向用户提供有意义的错误消息。\n\n## 延伸阅读\n\n* [MDN Web Docs: Error handling](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#exception_handling_statements)\n* [JavaScript.info: Error handling, \"try...catch\"](https://javascript.info/try-catch)\n* [Node.js Error Handling Best Practices](https://nodejs.dev/learn/error-handling-in-nodejs)\n"
  },
  {
    "path": "questions/explain-the-concept-of-hoisting-with-regards-to-functions/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"20406206\",\n        \"aa51f1b9\",\n        \"2a7816d0\",\n        \"f5599169\",\n        \"ec2260d9\",\n        \"85382bd2\",\n        \"42425171\",\n        \"c8679fed\",\n        \"7dbb6573\",\n        \"ebef5ef0\",\n        \"c1dce1a9\",\n        \"d25cb4b\",\n        \"5e9e708\",\n        \"ee71a154\",\n        \"1f4770e5\",\n        \"fdf346f1\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"20406206\",\n        \"aa51f1b9\",\n        \"2a7816d0\",\n        \"f5599169\",\n        \"ec2260d9\",\n        \"85382bd2\",\n        \"42425171\",\n        \"c8679fed\",\n        \"7dbb6573\",\n        \"ebef5ef0\",\n        \"c1dce1a9\",\n        \"d25cb4b\",\n        \"5e9e708\",\n        \"ee71a154\",\n        \"1f4770e5\",\n        \"fdf346f1\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"13d50de\"\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-hoisting-with-regards-to-functions/en-US.mdx",
    "content": "---\ntitle: Explain the concept of hoisting with regards to functions\n---\n\n## TL;DR\n\nHoisting in JavaScript is a behavior where function declarations are moved to the top of their containing scope during the compile phase. This means you can call a function before it is defined in the code. However, this does not apply to function expressions or arrow functions, which are not hoisted in the same way.\n\n```js live\n// Function declaration\nhoistedFunction(); // Works fine\nfunction hoistedFunction() {\n  console.log('This function is hoisted');\n}\n\n// Function expression\nnonHoistedFunction(); // Throws an error\nvar nonHoistedFunction = function () {\n  console.log('This function is not hoisted');\n};\n```\n\n---\n\n## What is hoisting?\n\nHoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase. This allows functions to be called before they are defined in the code.\n\n### Function declarations\n\nFunction declarations are fully hoisted. This means you can call a function before its declaration in the code.\n\n```js live\nhoistedFunction(); // Works fine\n\nfunction hoistedFunction() {\n  console.log('This function is hoisted');\n}\n```\n\n### Function expressions\n\nFunction expressions, including arrow functions, are not hoisted in the same way. They are treated as variable assignments and are only hoisted as undefined.\n\n```js live\nnonHoistedFunction(); // Throws an error: TypeError: nonHoistedFunction is not a function\n\nvar nonHoistedFunction = function () {\n  console.log('This function is not hoisted');\n};\n```\n\n### Arrow functions\n\nArrow functions behave similarly to function expressions in terms of hoisting.\n\n```js live\narrowFunction(); // Throws an error: TypeError: arrowFunction is not a function\n\nvar arrowFunction = () => {\n  console.log('This arrow function is not hoisted');\n};\n```\n\n## Further reading\n\n- [MDN Web Docs on Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)\n- [MDN Web Docs on Function Declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)\n- [MDN Web Docs on Function Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)\n"
  },
  {
    "path": "questions/explain-the-concept-of-hoisting-with-regards-to-functions/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-hoisting-with-regards-to-functions\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Functions\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-hoisting-with-regards-to-functions/zh-CN.mdx",
    "content": "---\ntitle: 解释关于函数的提升概念\n---\n\n## TL;DR\n\nJavaScript 中的提升是一种行为，在编译阶段，函数声明会被移动到其包含作用域的顶部。这意味着你可以在代码中定义函数之前调用它。但是，这不适用于函数表达式或箭头函数，它们不会以相同的方式被提升。\n\n```js live\n// Function declaration\nhoistedFunction(); // Works fine\nfunction hoistedFunction() {\n  console.log('This function is hoisted');\n}\n\n// Function expression\nnonHoistedFunction(); // Throws an error\nvar nonHoistedFunction = function () {\n  console.log('This function is not hoisted');\n};\n```\n\n***\n\n## 什么是提升？\n\n提升是一种 JavaScript 机制，在编译阶段，变量和函数声明会被移动到其包含作用域的顶部。这允许在代码中定义函数之前调用它们。\n\n### 函数声明\n\n函数声明会被完全提升。这意味着你可以在代码中声明函数之前调用它。\n\n```js live\nhoistedFunction(); // Works fine\n\nfunction hoistedFunction() {\n  console.log('This function is hoisted');\n}\n```\n\n### 函数表达式\n\n函数表达式（包括箭头函数）不会以相同的方式被提升。它们被视为变量赋值，并且仅被提升为 undefined。\n\n```js live\nnonHoistedFunction(); // Throws an error: TypeError: nonHoistedFunction is not a function\n\nvar nonHoistedFunction = function () {\n  console.log('This function is not hoisted');\n};\n```\n\n### 箭头函数\n\n就提升而言，箭头函数的行为类似于函数表达式。\n\n```js live\narrowFunction(); // Throws an error: TypeError: arrowFunction is not a function\n\nvar arrowFunction = () => {\n  console.log('This arrow function is not hoisted');\n};\n```\n\n## 延伸阅读\n\n* [MDN Web Docs on Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)\n* [MDN Web Docs on Function Declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)\n* [MDN Web Docs on Function Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)\n"
  },
  {
    "path": "questions/explain-the-concept-of-inheritance-in-es2015-classes/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"528b315e\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"4dc5ca9f\",\n        \"5516c905\",\n        \"2a7816d0\",\n        \"3041a730\",\n        \"39ce6dd8\",\n        \"827ae944\",\n        \"a855c6b2\",\n        \"46758152\",\n        \"ba8ea597\",\n        \"c0179921\",\n        \"cfebc17e\",\n        \"c4db839b\",\n        \"3fa519d9\",\n        \"e37d3013\",\n        \"cc1df438\",\n        \"1f4770e5\",\n        \"c8e0edbf\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4dc5ca9f\",\n        \"5516c905\",\n        \"2a7816d0\",\n        \"3041a730\",\n        \"39ce6dd8\",\n        \"827ae944\",\n        \"a855c6b2\",\n        \"46758152\",\n        \"ba8ea597\",\n        \"c0179921\",\n        \"cfebc17e\",\n        \"c4db839b\",\n        \"3fa519d9\",\n        \"e37d3013\",\n        \"cc1df438\",\n        \"1f4770e5\",\n        \"c8e0edbf\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-inheritance-in-es2015-classes/en-US.mdx",
    "content": "---\ntitle: Explain the concept of inheritance in ES2015 classes\n---\n\n## TL;DR\n\nInheritance in ES2015 classes allows one class to extend another, enabling the child class to inherit properties and methods from the parent class. This is done using the `extends` keyword. The `super` keyword is used to call the constructor and methods of the parent class. Here's a quick example:\n\n```js live\nclass Animal {\n  constructor(name) {\n    this.name = name;\n  }\n\n  speak() {\n    console.log(`${this.name} makes a noise.`);\n  }\n}\n\nclass Dog extends Animal {\n  constructor(name, breed) {\n    super(name);\n    this.breed = breed;\n  }\n\n  speak() {\n    console.log(`${this.name} barks.`);\n  }\n}\n\nconst dog = new Dog('Rex', 'German Shepherd');\ndog.speak(); // Rex barks.\n```\n\n---\n\n## Inheritance in ES2015 classes\n\n### Basic concept\n\nInheritance in ES2015 classes allows a class (child class) to inherit properties and methods from another class (parent class). This promotes code reuse and a hierarchical class structure.\n\n### Using the `extends` keyword\n\nThe `extends` keyword is used to create a class that is a child of another class. The child class inherits all the properties and methods of the parent class.\n\n```js live\nclass ParentClass {\n  constructor() {\n    this.parentProperty = 'I am a parent property';\n  }\n\n  parentMethod() {\n    console.log('This is a parent method');\n  }\n}\n\nclass ChildClass extends ParentClass {\n  constructor() {\n    super(); // Calls the parent class constructor\n    this.childProperty = 'I am a child property';\n  }\n\n  childMethod() {\n    console.log('This is a child method');\n  }\n}\n\nconst child = new ChildClass();\nconsole.log(child.parentProperty); // I am a parent property\nchild.parentMethod(); // This is a parent method\n```\n\n### Using the `super` keyword\n\nThe `super` keyword is used to call the constructor of the parent class and to access its methods. This is necessary when you want to initialize the parent class properties in the child class.\n\n```js live\nclass Animal {\n  constructor(name) {\n    this.name = name;\n  }\n\n  speak() {\n    console.log(`${this.name} makes a noise.`);\n  }\n}\n\nclass Dog extends Animal {\n  constructor(name, breed) {\n    super(name); // Calls the parent class constructor\n    this.breed = breed;\n  }\n\n  speak() {\n    super.speak(); // Calls the parent class method\n    console.log(`${this.name} barks.`);\n  }\n}\n\nconst dog = new Dog('Rex', 'German Shepherd');\ndog.speak();\n// Rex makes a noise.\n// Rex barks.\n```\n\n### Method overriding\n\nChild classes can override methods from the parent class. This allows the child class to provide a specific implementation of a method that is already defined in the parent class.\n\n```js live\nclass Animal {\n  speak() {\n    console.log('Animal makes a noise.');\n  }\n}\n\nclass Dog extends Animal {\n  speak() {\n    console.log('Dog barks.');\n  }\n}\n\nconst dog = new Dog();\ndog.speak(); // Dog barks.\n```\n\n## Further reading\n\n- [MDN Web Docs: Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n- [MDN Web Docs: Inheritance](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\n- [JavaScript.info: Class inheritance](https://javascript.info/class-inheritance)\n"
  },
  {
    "path": "questions/explain-the-concept-of-inheritance-in-es2015-classes/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-inheritance-in-es2015-classes\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Prototypes & Inheritance\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-inheritance-in-es2015-classes/zh-CN.mdx",
    "content": "---\ntitle: 解释 ES2015 类中的继承概念\n---\n\n## TL;DR\n\nES2015 类中的继承允许一个类扩展另一个类，使子类能够从父类继承属性和方法。这是使用 `extends` 关键字完成的。`super` 关键字用于调用父类的构造函数和方法。这是一个快速示例：\n\n```js live\nclass Animal {\n  constructor(name) {\n    this.name = name;\n  }\n\n  speak() {\n    console.log(`${this.name} makes a noise.`);\n  }\n}\n\nclass Dog extends Animal {\n  constructor(name, breed) {\n    super(name);\n    this.breed = breed;\n  }\n\n  speak() {\n    console.log(`${this.name} barks.`);\n  }\n}\n\nconst dog = new Dog('Rex', 'German Shepherd');\ndog.speak(); // Rex barks.\n```\n\n***\n\n## ES2015 类中的继承\n\n### 基本概念\n\nES2015 类中的继承允许一个类（子类）从另一个类（父类）继承属性和方法。这促进了代码重用和分层类结构。\n\n### 使用 `extends` 关键字\n\n使用 `extends` 关键字可以创建一个作为另一个类子类的类。子类继承父类的所有属性和方法。\n\n```js live\nclass ParentClass {\n  constructor() {\n    this.parentProperty = 'I am a parent property';\n  }\n\n  parentMethod() {\n    console.log('This is a parent method');\n  }\n}\n\nclass ChildClass extends ParentClass {\n  constructor() {\n    super(); // Calls the parent class constructor\n    this.childProperty = 'I am a child property';\n  }\n\n  childMethod() {\n    console.log('This is a child method');\n  }\n}\n\nconst child = new ChildClass();\nconsole.log(child.parentProperty); // I am a parent property\nchild.parentMethod(); // This is a parent method\n```\n\n### 使用 `super` 关键字\n\n`super` 关键字用于调用父类的构造函数并访问其方法。当您想在子类中初始化父类属性时，这是必需的。\n\n```js live\nclass Animal {\n  constructor(name) {\n    this.name = name;\n  }\n\n  speak() {\n    console.log(`${this.name} makes a noise.`);\n  }\n}\n\nclass Dog extends Animal {\n  constructor(name, breed) {\n    super(name); // Calls the parent class constructor\n    this.breed = breed;\n  }\n\n  speak() {\n    super.speak(); // Calls the parent class method\n    console.log(`${this.name} barks.`);\n  }\n}\n\nconst dog = new Dog('Rex', 'German Shepherd');\ndog.speak();\n// Rex makes a noise.\n// Rex barks.\n```\n\n### 方法重写\n\n子类可以重写父类中的方法。这允许子类提供已经在父类中定义的方法的特定实现。\n\n```js live\nclass Animal {\n  speak() {\n    console.log('Animal makes a noise.');\n  }\n}\n\nclass Dog extends Animal {\n  speak() {\n    console.log('Dog barks.');\n  }\n}\n\nconst dog = new Dog();\ndog.speak(); // Dog barks.\n```\n\n## 延伸阅读\n\n* [MDN Web 文档：类](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes)\n* [MDN Web 文档：继承](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\n* [JavaScript.info：类继承](https://zh.javascript.info/class-inheritance)\n"
  },
  {
    "path": "questions/explain-the-concept-of-input-validation-and-its-importance-in-security/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"a0797bc2\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"b9b1fddb\",\n        \"2a7816d0\",\n        \"4c4db576\",\n        \"76990236\",\n        \"29cda8fc\",\n        \"7a23c7d5\",\n        \"6cdbb9c9\",\n        \"60ff0ed8\",\n        \"eeef6828\",\n        \"1bd4d65f\",\n        \"7ed5cd3e\",\n        \"2ac70d1f\",\n        \"1f4770e5\",\n        \"ff0e75d4\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"b9b1fddb\",\n        \"2a7816d0\",\n        \"4c4db576\",\n        \"76990236\",\n        \"29cda8fc\",\n        \"7a23c7d5\",\n        \"6cdbb9c9\",\n        \"60ff0ed8\",\n        \"eeef6828\",\n        \"1bd4d65f\",\n        \"7ed5cd3e\",\n        \"2ac70d1f\",\n        \"1f4770e5\",\n        \"ff0e75d4\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-input-validation-and-its-importance-in-security/en-US.mdx",
    "content": "---\ntitle: Explain the concept of input validation and its importance in security\n---\n\n## TL;DR\n\nInput validation is the process of ensuring that user input is correct, safe, and meets the application's requirements. It is crucial for security because it helps prevent attacks like SQL injection, cross-site scripting (XSS), and other forms of data manipulation. By validating input, you ensure that only properly formatted data enters your system, reducing the risk of malicious data causing harm.\n\n---\n\n## Input validation and its importance in security\n\n### What is input validation?\n\nInput validation is the process of verifying that the data provided by a user or other external sources meets the expected format, type, and constraints before it is processed by the application. This can include checking for:\n\n- Correct data type (e.g., string, number)\n- Proper format (e.g., email addresses, phone numbers)\n- Acceptable value ranges (e.g., age between 0 and 120)\n- Required fields being filled\n\n### Types of input validation\n\n1. **Client-side validation**: This occurs in the user's browser before the data is sent to the server. It provides immediate feedback to the user and can improve the user experience. However, it should not be solely relied upon for security purposes, as it can be easily bypassed.\n\n   ```html\n   <form>\n     <input type=\"text\" id=\"username\" required pattern=\"[A-Za-z0-9]{5,}\" />\n     <input type=\"submit\" />\n   </form>\n   ```\n\n2. **Server-side validation**: This occurs on the server after the data has been submitted. It is essential for security because it ensures that all data is validated regardless of the client's behavior.\n\n   ```js\n   const express = require('express');\n   const app = express();\n\n   app.post('/submit', (req, res) => {\n     const username = req.body.username;\n     if (!/^[A-Za-z0-9]{5,}$/.test(username)) {\n       return res.status(400).send('Invalid username');\n     }\n     // Proceed with processing the valid input\n   });\n   ```\n\n### Importance of input validation in security\n\n1. **Preventing SQL injection**: By validating and sanitizing input, you can prevent attackers from injecting malicious SQL code into your database queries.\n\n   ```js\n   const username = req.body.username;\n   const query = 'SELECT * FROM users WHERE username = ?';\n   db.query(query, [username], (err, results) => {\n     // Handle results\n   });\n   ```\n\n2. **Preventing cross-site scripting (XSS)**: Input validation helps ensure that user input does not contain malicious scripts that could be executed in the browser.\n\n   ```js\n   const sanitizeHtml = require('sanitize-html');\n   const userInput = req.body.comment;\n   const sanitizedInput = sanitizeHtml(userInput);\n   ```\n\n3. **Preventing buffer overflow attacks**: By validating the length of input data, you can prevent attackers from sending excessively large inputs that could cause buffer overflows and crash your application.\n\n4. **Ensuring data integrity**: Input validation helps maintain the integrity of your data by ensuring that only properly formatted and expected data is processed and stored.\n\n### Best practices for input validation\n\n- Always validate input on the server side, even if you also validate on the client side\n- Use built-in validation functions and libraries where possible\n- Sanitize input to remove or escape potentially harmful characters\n- Implement whitelisting (allowing only known good input) rather than blacklisting (blocking known bad input)\n- Regularly update and review your validation rules to address new security threats\n\n## Further reading\n\n- [OWASP Input Validation Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html)\n- [MDN Web Docs: Client-side form validation](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation)\n- [Sanitize-html library](https://www.npmjs.com/package/sanitize-html)\n"
  },
  {
    "path": "questions/explain-the-concept-of-input-validation-and-its-importance-in-security/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-input-validation-and-its-importance-in-security\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Security\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-input-validation-and-its-importance-in-security/zh-CN.mdx",
    "content": "---\ntitle: 解释输入验证的概念及其在安全中的重要性\n---\n\n## TL;DR\n\n输入验证是确保用户输入正确、安全并满足应用程序要求的过程。它对安全至关重要，因为它有助于防止 SQL 注入、跨站点脚本 (XSS) 和其他形式的数据操纵等攻击。通过验证输入，您可以确保只有格式正确的数据才能进入您的系统，从而降低恶意数据造成损害的风险。\n\n***\n\n## 输入验证及其在安全中的重要性\n\n### 什么是输入验证？\n\n输入验证是验证用户或其他外部来源提供的数据在应用程序处理之前是否满足预期格式、类型和约束的过程。这可以包括检查：\n\n* 正确的数据类型（例如，字符串、数字）\n* 适当的格式（例如，电子邮件地址、电话号码）\n* 可接受的数值范围（例如，年龄在 0 到 120 岁之间）\n* 必填字段已填写\n\n### 输入验证的类型\n\n1. **客户端验证**：这发生在用户将数据发送到服务器之前，在用户的浏览器中进行。它向用户提供即时反馈，并可以改善用户体验。但是，不应仅依赖它来实现安全目的，因为它很容易被绕过。\n\n   ```html\n   <form>\n     <input type=\"text\" id=\"username\" required pattern=\"[A-Za-z0-9]{5,}\" />\n     <input type=\"submit\" />\n   </form>\n   ```\n\n2. **服务器端验证**：这发生在数据提交到服务器之后。它对于安全至关重要，因为它确保所有数据都经过验证，而不管客户端的行为如何。\n\n   ```js\n   const express = require('express');\n   const app = express();\n\n   app.post('/submit', (req, res) => {\n     const username = req.body.username;\n     if (!/^[A-Za-z0-9]{5,}$/.test(username)) {\n       return res.status(400).send('Invalid username');\n     }\n     // Proceed with processing the valid input\n   });\n   ```\n\n### 输入验证在安全中的重要性\n\n1. **防止 SQL 注入**：通过验证和清理输入，您可以防止攻击者将恶意 SQL 代码注入到您的数据库查询中。\n\n   ```js\n   const username = req.body.username;\n   const query = 'SELECT * FROM users WHERE username = ?';\n   db.query(query, [username], (err, results) => {\n     // Handle results\n   });\n   ```\n\n2. **防止跨站点脚本 (XSS)**：输入验证有助于确保用户输入不包含可能在浏览器中执行的恶意脚本。\n\n   ```js\n   const sanitizeHtml = require('sanitize-html');\n   const userInput = req.body.comment;\n   const sanitizedInput = sanitizeHtml(userInput);\n   ```\n\n3. **防止缓冲区溢出攻击**：通过验证输入数据的长度，您可以防止攻击者发送过大的输入，从而导致缓冲区溢出并使您的应用程序崩溃。\n\n4. **确保数据完整性**：输入验证通过确保仅处理和存储格式正确且预期的数据来帮助维护数据的完整性。\n\n### 输入验证的最佳实践\n\n* 始终在服务器端验证输入，即使您也在客户端进行验证\n* 尽可能使用内置验证函数和库\n* 清理输入以删除或转义潜在的有害字符\n* 实施白名单（仅允许已知的良好输入）而不是黑名单（阻止已知的错误输入）\n* 定期更新和审查您的验证规则以应对新的安全威胁\n\n## 延伸阅读\n\n* [OWASP 输入验证备忘单](https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html)\n* [MDN Web 文档：客户端表单验证](https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation)\n* [Sanitize-html 库](https://www.npmjs.com/package/sanitize-html)\n"
  },
  {
    "path": "questions/explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"36eddc8b\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"fd619192\",\n        \"4c8a3360\",\n        \"2a7816d0\",\n        \"2340e89e\",\n        \"3d01798d\",\n        \"7038ddb2\",\n        \"4e293a7f\",\n        \"a018c5c8\",\n        \"d61b86fa\",\n        \"3f1f84eb\",\n        \"1a5baa2\",\n        \"234b720\",\n        \"70533076\",\n        \"4c8a3360\",\n        \"689611e9\",\n        \"1387dbc5\",\n        \"83cbe7fe\",\n        \"9adb5bbb\",\n        \"1f4770e5\",\n        \"825318bc\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"fd619192\",\n        \"4c8a3360\",\n        \"2a7816d0\",\n        \"2340e89e\",\n        \"3d01798d\",\n        \"7038ddb2\",\n        \"4e293a7f\",\n        \"a018c5c8\",\n        \"d61b86fa\",\n        \"3f1f84eb\",\n        \"1a5baa2\",\n        \"234b720\",\n        \"70533076\",\n        \"4c8a3360\",\n        \"689611e9\",\n        \"1387dbc5\",\n        \"83cbe7fe\",\n        \"9adb5bbb\",\n        \"1f4770e5\",\n        \"825318bc\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance/en-US.mdx",
    "content": "---\ntitle: Explain the concept of lazy loading and how it can improve performance\n---\n\n## TL;DR\n\nLazy loading is a design pattern that delays the loading of resources until they are actually needed. This can significantly improve performance by reducing initial load times and conserving bandwidth. For example, images on a webpage can be lazy-loaded so that they only load when they come into the viewport. This can be achieved using the `loading=\"lazy\"` attribute in HTML or by using JavaScript libraries.\n\n```html\n<img src=\"image.jpg\" loading=\"lazy\" alt=\"Lazy loaded image\" />\n```\n\n---\n\n## The concept of lazy loading and how it can improve performance\n\n### What is lazy loading?\n\nLazy loading is a design pattern used to defer the initialization of an object until the point at which it is needed. This can be applied to various types of resources such as images, videos, scripts, and even data fetched from APIs.\n\n### How does lazy loading work?\n\nLazy loading works by delaying the loading of resources until they are actually needed. For example, images on a webpage can be lazy-loaded so that they only load when they come into the viewport. This can be achieved using the `loading=\"lazy\"` attribute in HTML or by using JavaScript libraries.\n\n### Benefits of lazy loading\n\n- **Improved performance**: By loading only the necessary resources initially, the page load time is reduced, leading to a faster and more responsive user experience.\n- **Reduced bandwidth usage**: Lazy loading helps in conserving bandwidth by loading resources only when they are needed.\n- **Better user experience**: Users can start interacting with the content faster as the initial load time is reduced.\n\n### Implementing lazy loading\n\n#### Using the `loading` attribute in HTML\n\nThe simplest way to implement lazy loading for images is by using the `loading` attribute in HTML.\n\n```html\n<img src=\"image.jpg\" loading=\"lazy\" alt=\"Lazy loaded image\" />\n```\n\n#### Using JavaScript\n\nFor more complex scenarios, you can use JavaScript to implement lazy loading. Here is an example using the Intersection Observer API:\n\n```js\ndocument.addEventListener('DOMContentLoaded', function () {\n  const lazyImages = document.querySelectorAll('img.lazy');\n\n  const imageObserver = new IntersectionObserver((entries, observer) => {\n    entries.forEach((entry) => {\n      if (entry.isIntersecting) {\n        const img = entry.target;\n        img.src = img.dataset.src;\n        img.classList.remove('lazy');\n        observer.unobserve(img);\n      }\n    });\n  });\n\n  lazyImages.forEach((image) => {\n    imageObserver.observe(image);\n  });\n});\n```\n\nIn this example, images with the class `lazy` will only load when they come into the viewport.\n\n## Further reading\n\n- [MDN Web Docs: Lazy loading](https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading)\n- [Google Developers: Lazy loading images and video](https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video)\n- [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)\n"
  },
  {
    "path": "questions/explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"performance\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Performance Optimization\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-lazy-loading-and-how-it-can-improve-performance/zh-CN.mdx",
    "content": "---\ntitle: 解释惰性加载的概念以及它如何提高性能\n---\n\n## TL;DR\n\n惰性加载是一种设计模式，它将资源的加载延迟到实际需要时。这可以通过减少初始加载时间和节省带宽来显着提高性能。例如，网页上的图像可以进行惰性加载，以便它们仅在进入视口时加载。这可以使用 HTML 中的 `loading=\"lazy\"` 属性或使用 JavaScript 库来实现。\n\n```html\n<img src=\"image.jpg\" loading=\"lazy\" alt=\"Lazy loaded image\" />\n```\n\n***\n\n## 惰性加载的概念以及它如何提高性能\n\n### 什么是惰性加载？\n\n惰性加载是一种设计模式，用于推迟对象的初始化，直到需要时才进行。这可以应用于各种类型的资源，例如图像、视频、脚本，甚至从 API 获取的数据。\n\n### 惰性加载如何工作？\n\n惰性加载通过延迟加载资源直到实际需要时才进行。例如，网页上的图像可以进行惰性加载，以便它们仅在进入视口时加载。这可以使用 HTML 中的 `loading=\"lazy\"` 属性或使用 JavaScript 库来实现。\n\n### 惰性加载的好处\n\n* **提高性能**：通过仅在初始加载时加载必要的资源，可以缩短页面加载时间，从而带来更快、响应更快的用户体验。\n* **减少带宽使用**：惰性加载有助于通过仅在需要时加载资源来节省带宽。\n* **更好的用户体验**：用户可以更快地开始与内容交互，因为初始加载时间缩短了。\n\n### 实现惰性加载\n\n#### 使用 HTML 中的 `loading` 属性\n\n实现图像惰性加载的最简单方法是使用 HTML 中的 `loading` 属性。\n\n```html\n<img src=\"image.jpg\" loading=\"lazy\" alt=\"Lazy loaded image\" />\n```\n\n#### 使用 JavaScript\n\n对于更复杂的场景，您可以使用 JavaScript 来实现惰性加载。这是一个使用 Intersection Observer API 的示例：\n\n```js\ndocument.addEventListener('DOMContentLoaded', function () {\n  const lazyImages = document.querySelectorAll('img.lazy');\n\n  const imageObserver = new IntersectionObserver((entries, observer) => {\n    entries.forEach((entry) => {\n      if (entry.isIntersecting) {\n        const img = entry.target;\n        img.src = img.dataset.src;\n        img.classList.remove('lazy');\n        observer.unobserve(img);\n      }\n    });\n  });\n\n  lazyImages.forEach((image) => {\n    imageObserver.observe(image);\n  });\n});\n```\n\n在此示例中，带有 `lazy` 类的图像仅在进入视口时加载。\n\n## 延伸阅读\n\n* [MDN Web Docs: Lazy loading](https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading)\n* [Google Developers: Lazy loading images and video](https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video)\n* [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)\n"
  },
  {
    "path": "questions/explain-the-concept-of-lexical-scoping/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"af91d864\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"f8875ab\",\n        \"b7c9b503\",\n        \"cdc318c9\",\n        \"2a7816d0\",\n        \"5449adb\",\n        \"78887597\",\n        \"a3b79723\",\n        \"52f723b5\",\n        \"9b5019f0\",\n        \"6ef3431\",\n        \"b7c9b503\",\n        \"670df17e\",\n        \"84bfb0a\",\n        \"d83b5de4\",\n        \"e386cee7\",\n        \"d5bfe237\",\n        \"670df17e\",\n        \"411f6623\",\n        \"1f4770e5\",\n        \"2b05c7f\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"f8875ab\",\n        \"b7c9b503\",\n        \"cdc318c9\",\n        \"2a7816d0\",\n        \"5449adb\",\n        \"78887597\",\n        \"a3b79723\",\n        \"52f723b5\",\n        \"9b5019f0\",\n        \"6ef3431\",\n        \"b7c9b503\",\n        \"670df17e\",\n        \"84bfb0a\",\n        \"d83b5de4\",\n        \"e386cee7\",\n        \"d5bfe237\",\n        \"670df17e\",\n        \"411f6623\",\n        \"1f4770e5\",\n        \"2b05c7f\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-lexical-scoping/en-US.mdx",
    "content": "---\ntitle: Explain the concept of lexical scoping\n---\n\n## TL;DR\n\nLexical scoping means that the scope of a variable is determined by its location within the source code, and nested functions have access to variables declared in their outer scope. For example:\n\n```js live\nfunction outerFunction() {\n  let outerVariable = 'I am outside!';\n\n  function innerFunction() {\n    console.log(outerVariable); // 'I am outside!'\n  }\n\n  innerFunction();\n}\n\nouterFunction();\n```\n\nIn this example, `innerFunction` can access `outerVariable` because of lexical scoping.\n\n---\n\n## Lexical scoping\n\nLexical scoping is a fundamental concept in JavaScript and many other programming languages. It determines how variable names are resolved in nested functions. The scope of a variable is defined by its position in the source code, and nested functions have access to variables declared in their outer scope.\n\n### How lexical scoping works\n\nWhen a function is defined, it captures the scope in which it was created. This means that the function has access to variables in its own scope as well as variables in any containing (outer) scopes.\n\n### Example\n\nConsider the following example:\n\n```js live\nfunction outerFunction() {\n  let outerVariable = 'I am outside!';\n\n  function innerFunction() {\n    console.log(outerVariable); // 'I am outside!'\n  }\n\n  innerFunction();\n}\n\nouterFunction();\n```\n\nIn this example:\n\n- `outerFunction` declares a variable `outerVariable`.\n- `innerFunction` is nested inside `outerFunction` and logs `outerVariable` to the console.\n- When `innerFunction` is called, it has access to `outerVariable` because of lexical scoping.\n\n### Nested functions and closures\n\nLexical scoping is closely related to closures. A closure is created when a function retains access to its lexical scope, even when the function is executed outside that scope.\n\n```js live\nfunction outerFunction() {\n  let outerVariable = 'I am outside!';\n\n  function innerFunction() {\n    console.log(outerVariable);\n  }\n\n  return innerFunction;\n}\n\nconst myInnerFunction = outerFunction();\nmyInnerFunction(); // 'I am outside!'\n```\n\nIn this example:\n\n- `outerFunction` returns `innerFunction`.\n- `myInnerFunction` is assigned the returned `innerFunction`.\n- When `myInnerFunction` is called, it still has access to `outerVariable` because of the closure created by lexical scoping.\n\n## Further reading\n\n- [MDN Web Docs: Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n- [JavaScript.info: Lexical environment](https://javascript.info/closure#lexical-environment)\n- [Eloquent JavaScript: Functions and closures](https://eloquentjavascript.net/03_functions.html#h_jxlm8r9e2g)\n"
  },
  {
    "path": "questions/explain-the-concept-of-lexical-scoping/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-lexical-scoping\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Closures & Scope\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-lexical-scoping/zh-CN.mdx",
    "content": "---\ntitle: 解释词法作用域的概念\n---\n\n## TL;DR\n\n词法作用域意味着变量的作用域由其在源代码中的位置决定，嵌套函数可以访问在其外部作用域中声明的变量。例如：\n\n```js live\nfunction outerFunction() {\n  let outerVariable = 'I am outside!';\n\n  function innerFunction() {\n    console.log(outerVariable); // 'I am outside!'\n  }\n\n  innerFunction();\n}\n\nouterFunction();\n```\n\n在这个例子中，`innerFunction` 可以访问 `outerVariable`，因为词法作用域。\n\n***\n\n## 词法作用域\n\n词法作用域是 JavaScript 和许多其他编程语言中的一个基本概念。它决定了在嵌套函数中如何解析变量名。变量的作用域由其在源代码中的位置定义，嵌套函数可以访问在其外部作用域中声明的变量。\n\n### 词法作用域的工作原理\n\n当一个函数被定义时，它会捕获创建它的作用域。这意味着该函数可以访问其自身作用域中的变量以及任何包含（外部）作用域中的变量。\n\n### 例子\n\n考虑以下示例：\n\n```js live\nfunction outerFunction() {\n  let outerVariable = 'I am outside!';\n\n  function innerFunction() {\n    console.log(outerVariable); // 'I am outside!'\n  }\n\n  innerFunction();\n}\n\nouterFunction();\n```\n\n在这个例子中：\n\n* `outerFunction` 声明一个变量 `outerVariable`。\n* `innerFunction` 嵌套在 `outerFunction` 内部，并将 `outerVariable` 记录到控制台。\n* 当调用 `innerFunction` 时，由于词法作用域，它可以访问 `outerVariable`。\n\n### 嵌套函数和闭包\n\n词法作用域与闭包密切相关。当一个函数保留对其词法作用域的访问权限时，即使该函数在作用域之外执行，也会创建一个闭包。\n\n```js live\nfunction outerFunction() {\n  let outerVariable = 'I am outside!';\n\n  function innerFunction() {\n    console.log(outerVariable);\n  }\n\n  return innerFunction;\n}\n\nconst myInnerFunction = outerFunction();\nmyInnerFunction(); // 'I am outside!'\n```\n\n在这个例子中：\n\n* `outerFunction` 返回 `innerFunction`。\n* `myInnerFunction` 被赋值为返回的 `innerFunction`。\n* 当调用 `myInnerFunction` 时，它仍然可以访问 `outerVariable`，因为词法作用域创建了闭包。\n\n## 延伸阅读\n\n* [MDN Web Docs: Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n* [JavaScript.info: Lexical environment](https://javascript.info/closure#lexical-environment)\n* [Eloquent JavaScript: Functions and closures](https://eloquentjavascript.net/03_functions.html#h_jxlm8r9e2g)\n"
  },
  {
    "path": "questions/explain-the-concept-of-partial-application/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"bdd76e95\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"7a176a9c\",\n        \"ccb4ad60\",\n        \"2a7816d0\",\n        \"1993a874\",\n        \"663a1ffc\",\n        \"9b5019f0\",\n        \"30ade118\",\n        \"2b49d068\",\n        \"827b6403\",\n        \"6894639b\",\n        \"4e8ede6c\",\n        \"2fc5f052\",\n        \"2819c383\",\n        \"252dcac\",\n        \"65d97317\",\n        \"68e56b3b\",\n        \"7641f0f3\",\n        \"1f4770e5\",\n        \"e9d26722\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"7a176a9c\",\n        \"ccb4ad60\",\n        \"2a7816d0\",\n        \"1993a874\",\n        \"663a1ffc\",\n        \"9b5019f0\",\n        \"30ade118\",\n        \"2b49d068\",\n        \"827b6403\",\n        \"6894639b\",\n        \"4e8ede6c\",\n        \"2fc5f052\",\n        \"2819c383\",\n        \"252dcac\",\n        \"65d97317\",\n        \"68e56b3b\",\n        \"7641f0f3\",\n        \"1f4770e5\",\n        \"e9d26722\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-partial-application/en-US.mdx",
    "content": "---\ntitle: Explain the concept of partial application\n---\n\n## TL;DR\n\nPartial application is a technique in functional programming where a function is applied to some of its arguments, producing a new function that takes the remaining arguments. This allows you to create more specific functions from general ones. For example, if you have a function `add(a, b)`, you can partially apply it to create a new function `add5` that always adds 5 to its argument.\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconst add5 = add.bind(null, 5);\nconsole.log(add5(10)); // Outputs 15\n```\n\n---\n\n## Partial application\n\nPartial application is a functional programming technique where a function is applied to some of its arguments, producing a new function that takes the remaining arguments. This can be useful for creating more specific functions from general ones, improving code reusability and readability.\n\n### Example\n\nConsider a simple `add` function that takes two arguments:\n\n```js\nfunction add(a, b) {\n  return a + b;\n}\n```\n\nUsing partial application, you can create a new function `add5` that always adds 5 to its argument:\n\n```js\nconst add5 = add.bind(null, 5);\nconsole.log(add5(10)); // Outputs 15\n```\n\n### How it works\n\nIn the example above, `add.bind(null, 5)` creates a new function where the first argument (`a`) is fixed to 5. The `null` value is used as the `this` context, which is not relevant in this case.\n\n### Benefits\n\n- **Code reusability**: You can create more specific functions from general ones, making your code more modular and reusable.\n- **Readability**: Partially applied functions can make your code easier to read and understand by reducing the number of arguments you need to pass around.\n\n### Real-world example\n\nPartial application is often used in libraries like Lodash. For example, Lodash's `_.partial` function allows you to create partially applied functions easily:\n\n```js\nconst _ = require('lodash');\n\nfunction greet(greeting, name) {\n  return `${greeting}, ${name}!`;\n}\n\nconst sayHelloTo = _.partial(greet, 'Hello');\nconsole.log(sayHelloTo('John')); // Outputs \"Hello, John!\"\n```\n\n## Further reading\n\n- [MDN Web Docs: Function.prototype.bind()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)\n- [Lodash Documentation: \\_.partial](https://lodash.com/docs/4.17.15#partial)\n- [Wikipedia: Partial application](https://en.wikipedia.org/wiki/Partial_application)\n"
  },
  {
    "path": "questions/explain-the-concept-of-partial-application/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-partial-application\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"closure\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Currying & Partial Application\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-partial-application/zh-CN.mdx",
    "content": "---\ntitle: 解释部分应用的理念\n---\n\n## 总结\n\n部分应用是函数式编程中的一种技术，它将一个函数应用于其部分参数，从而产生一个接受剩余参数的新函数。这允许你从通用函数中创建更具体的函数。例如，如果你有一个函数 `add(a, b)`，你可以部分应用它来创建一个新的函数 `add5`，它总是将其参数加上 5。\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconst add5 = add.bind(null, 5);\nconsole.log(add5(10)); // Outputs 15\n```\n\n***\n\n## 部分应用\n\n部分应用是一种函数式编程技术，它将一个函数应用于其部分参数，从而产生一个接受剩余参数的新函数。这对于从通用函数创建更具体的函数、提高代码可重用性和可读性很有用。\n\n### 示例\n\n考虑一个接受两个参数的简单 `add` 函数：\n\n```js\nfunction add(a, b) {\n  return a + b;\n}\n```\n\n使用部分应用，你可以创建一个新的函数 `add5`，它总是将其参数加上 5：\n\n```js\nconst add5 = add.bind(null, 5);\nconsole.log(add5(10)); // Outputs 15\n```\n\n### 工作原理\n\n在上面的例子中，`add.bind(null, 5)` 创建了一个新函数，其中第一个参数 (`a`) 被固定为 5。`null` 值用作 `this` 上下文，在这种情况下与此无关。\n\n### 优点\n\n* **代码可重用性**：你可以从通用函数中创建更具体的函数，使你的代码更模块化和可重用。\n* **可读性**：部分应用的函数可以通过减少你需要传递的参数数量来使你的代码更容易阅读和理解。\n\n### 真实世界的例子\n\n部分应用经常用于 Lodash 等库中。例如，Lodash 的 `_.partial` 函数允许你轻松创建部分应用的函数：\n\n```js\nconst _ = require('lodash');\n\nfunction greet(greeting, name) {\n  return `${greeting}, ${name}!`;\n}\n\nconst sayHelloTo = _.partial(greet, 'Hello');\nconsole.log(sayHelloTo('John')); // Outputs \"Hello, John!\"\n```\n\n## 延伸阅读\n\n* [MDN Web 文档：Function.prototype.bind()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)\n* [Lodash 文档：\\_.partial](https://lodash.com/docs/4.17.15#partial)\n* [维基百科：部分应用](https://zh.wikipedia.org/wiki/%E9%83%A8%E5%88%86%E5%BA%94%E7%94%A8)\n"
  },
  {
    "path": "questions/explain-the-concept-of-scope-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"f1d5c987\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"220bbf28\",\n        \"70e2c5f1\",\n        \"2a7816d0\",\n        \"454d89af\",\n        \"19fcdd6e\",\n        \"1d6f19ac\",\n        \"affa6549\",\n        \"9f817d95\",\n        \"39375d9f\",\n        \"3baf4fdd\",\n        \"35bb03fb\",\n        \"a8ba62be\",\n        \"9422beaa\",\n        \"a9a43f04\",\n        \"24883344\",\n        \"67ddff4a\",\n        \"1f4770e5\",\n        \"556d3732\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"220bbf28\",\n        \"70e2c5f1\",\n        \"2a7816d0\",\n        \"454d89af\",\n        \"19fcdd6e\",\n        \"1d6f19ac\",\n        \"affa6549\",\n        \"9f817d95\",\n        \"39375d9f\",\n        \"3baf4fdd\",\n        \"35bb03fb\",\n        \"a8ba62be\",\n        \"9422beaa\",\n        \"a9a43f04\",\n        \"24883344\",\n        \"67ddff4a\",\n        \"1f4770e5\",\n        \"556d3732\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-scope-in-javascript/en-US.mdx",
    "content": "---\ntitle: Explain the concept of scope in JavaScript\n---\n\n## TL;DR\n\nIn JavaScript, scope determines the accessibility of variables and functions at different parts of the code. There are three main types of scope: global scope, function scope, and block scope. Global scope means the variable is accessible everywhere in the code. Function scope means the variable is accessible only within the function it is declared. Block scope, introduced with ES6, means the variable is accessible only within the block (e.g., within curly braces `{}`) it is declared.\n\n```js live\nvar globalVar = 'I am a global var';\n\nfunction myFunction() {\n  var functionVar = 'I am a function-scoped var';\n\n  if (true) {\n    let blockVar = 'I am a block-scoped var';\n\n    console.log('Inside block:');\n    console.log(globalVar); // Accessible\n    console.log(functionVar); // Accessible\n    console.log(blockVar); // Accessible\n  }\n\n  console.log('Inside function:');\n  console.log(globalVar); // Accessible\n  console.log(functionVar); // Accessible\n  // console.log(blockVar); // Uncaught ReferenceError\n}\n\nmyFunction();\n\nconsole.log('In global scope:');\nconsole.log(globalVar); // Accessible\n// console.log(functionVar); // Uncaught ReferenceError\n// console.log(blockVar); // Uncaught ReferenceError\n```\n\n---\n\n## Scope in JavaScript\n\n### Global scope\n\nVariables declared outside any function or block have global scope. They are accessible from anywhere in the code.\n\n```js live\nvar globalVar = 'I am global';\n\nfunction myFunction() {\n  console.log(globalVar); // Accessible here\n}\n\nmyFunction();\nconsole.log(globalVar); // Accessible here\n```\n\n### Function scope\n\nVariables declared within a function are in function scope. They are accessible only within that function.\n\n```js live\nfunction myFunction() {\n  var functionVar = 'I am in a function';\n  console.log(functionVar); // Accessible here\n}\n\nmyFunction();\nconsole.log(functionVar); // Uncaught ReferenceError: functionVar is not defined\n```\n\n### Block scope\n\nVariables declared with `let` or `const` within a block (e.g., within curly braces `{}`) have block scope. They are accessible only within that block.\n\n```js live\nif (true) {\n  let blockVar = 'I am in a block';\n  console.log(blockVar); // Accessible here\n}\n\nconsole.log(blockVar); // Uncaught ReferenceError: blockVar is not defined\n```\n\n### Lexical scope\n\nJavaScript uses lexical scoping, meaning that the scope of a variable is determined by its location within the source code. Nested functions have access to variables declared in their outer scope.\n\n```js live\nfunction outerFunction() {\n  var outerVar = 'I am outside';\n\n  function innerFunction() {\n    console.log(outerVar); // Accessible here\n  }\n\n  innerFunction();\n}\n\nouterFunction();\n```\n\n## Further reading\n\n- [MDN Web Docs: Scope](https://developer.mozilla.org/en-US/docs/Glossary/Scope)\n- [JavaScript.info: Variable scope](https://javascript.info/var)\n- [Eloquent JavaScript: Functions and Scope](https://eloquentjavascript.net/03_functions.html#h_scope)\n"
  },
  {
    "path": "questions/explain-the-concept-of-scope-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-scope-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Functions\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-scope-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 中的作用域概念\n---\n\n## TL;DR\n\n在 JavaScript 中，作用域决定了变量和函数在代码不同部分的可访问性。主要有三种作用域：全局作用域、函数作用域和块级作用域。全局作用域意味着变量可以在代码中的任何地方访问。函数作用域意味着变量只能在其声明的函数内部访问。块级作用域是在 ES6 中引入的，意味着变量只能在其声明的块（例如，在大括号 `{}` 内）中访问。\n\n```js live\nvar globalVar = 'I am a global var';\n\nfunction myFunction() {\n  var functionVar = 'I am a function-scoped var';\n\n  if (true) {\n    let blockVar = 'I am a block-scoped var';\n\n    console.log('Inside block:');\n    console.log(globalVar); // Accessible\n    console.log(functionVar); // Accessible\n    console.log(blockVar); // Accessible\n  }\n\n  console.log('Inside function:');\n  console.log(globalVar); // Accessible\n  console.log(functionVar); // Accessible\n  // console.log(blockVar); // Uncaught ReferenceError\n}\n\nmyFunction();\n\nconsole.log('In global scope:');\nconsole.log(globalVar); // Accessible\n// console.log(functionVar); // Uncaught ReferenceError\n// console.log(blockVar); // Uncaught ReferenceError\n```\n\n***\n\n## JavaScript 中的作用域\n\n### 全局作用域\n\n在任何函数或块外部声明的变量具有全局作用域。它们可以在代码中的任何地方访问。\n\n```js live\nvar globalVar = 'I am global';\n\nfunction myFunction() {\n  console.log(globalVar); // Accessible here\n}\n\nmyFunction();\nconsole.log(globalVar); // Accessible here\n```\n\n### 函数作用域\n\n在函数内声明的变量属于函数作用域。它们只能在该函数内部访问。\n\n```js live\nfunction myFunction() {\n  var functionVar = 'I am in a function';\n  console.log(functionVar); // Accessible here\n}\n\nmyFunction();\nconsole.log(functionVar); // Uncaught ReferenceError: functionVar is not defined\n```\n\n### 块级作用域\n\n在块（例如，在大括号 `{}` 内）中使用 `let` 或 `const` 声明的变量具有块级作用域。它们只能在该块内访问。\n\n```js live\nif (true) {\n  let blockVar = 'I am in a block';\n  console.log(blockVar); // Accessible here\n}\n\nconsole.log(blockVar); // Uncaught ReferenceError: blockVar is not defined\n```\n\n### 词法作用域\n\nJavaScript 使用词法作用域，这意味着变量的作用域由其在源代码中的位置决定。嵌套函数可以访问在其外部作用域中声明的变量。\n\n```js live\nfunction outerFunction() {\n  var outerVar = 'I am outside';\n\n  function innerFunction() {\n    console.log(outerVar); // Accessible here\n  }\n\n  innerFunction();\n}\n\nouterFunction();\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Scope](https://developer.mozilla.org/en-US/docs/Glossary/Scope)\n* [JavaScript.info: Variable scope](https://javascript.info/var)\n* [Eloquent JavaScript: Functions and Scope](https://eloquentjavascript.net/03_functions.html#h_scope)\n"
  },
  {
    "path": "questions/explain-the-concept-of-tagged-templates/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"d92293fb\",\n        \"cd3a5faf\",\n        \"2a7816d0\",\n        \"7dc7f9d\",\n        \"286c0237\",\n        \"ab9d62c3\",\n        \"eea083fa\",\n        \"8747d9ff\",\n        \"c523088d\",\n        \"4e8ede6c\",\n        \"40da1341\",\n        \"aab2ce46\",\n        \"a2cf7bc1\",\n        \"e275671d\",\n        \"6dd3b324\",\n        \"f8288cb8\",\n        \"f127d093\",\n        \"9b5019f0\",\n        \"a70e6617\",\n        \"e350925c\",\n        \"1f4770e5\",\n        \"5a4eca21\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d92293fb\",\n        \"cd3a5faf\",\n        \"2a7816d0\",\n        \"7dc7f9d\",\n        \"286c0237\",\n        \"ab9d62c3\",\n        \"eea083fa\",\n        \"8747d9ff\",\n        \"c523088d\",\n        \"4e8ede6c\",\n        \"40da1341\",\n        \"aab2ce46\",\n        \"a2cf7bc1\",\n        \"e275671d\",\n        \"6dd3b324\",\n        \"f8288cb8\",\n        \"f127d093\",\n        \"9b5019f0\",\n        \"a70e6617\",\n        \"e350925c\",\n        \"1f4770e5\",\n        \"5a4eca21\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"644bf6e\"\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-tagged-templates/en-US.mdx",
    "content": "---\ntitle: Explain the concept of tagged templates\n---\n\n## TL;DR\n\nTagged templates in JavaScript allow you to parse template literals with a function. The function receives the literal strings and the values as arguments, enabling custom processing of the template. For example:\n\n```js live\nfunction tag(strings, ...values) {\n  return strings[0] + values[0] + strings[1] + values[1] + strings[2];\n}\n\nconst result = tag`Hello ${'world'}! How are ${'you'}?`;\nconsole.log(result); // \"Hello world! How are you?\"\n```\n\n---\n\n## Tagged templates\n\n### What are tagged templates?\n\nTagged templates are a feature in JavaScript that allows you to call a function (the \"tag\") with a template literal. The tag function can then process the template literal's parts (both the literal strings and the interpolated values) in a custom way.\n\n### Syntax\n\nThe syntax for tagged templates involves placing a function name before a template literal:\n\n```js\nfunction tag(strings, ...values) {\n  // Custom processing\n}\n\ntag`template literal with ${values}`;\n```\n\n### How it works\n\nWhen a tagged template is invoked, the tag function receives:\n\n1. An array of literal strings (the parts of the template that are not interpolated)\n2. The interpolated values as additional arguments\n\nFor example:\n\n```js live\nfunction tag(strings, ...values) {\n  console.log(strings); // [\"Hello \", \"! How are \", \"?\"]\n  console.log(values); // [\"world\", \"you\"]\n}\n\ntag`Hello ${'world'}! How are ${'you'}?`;\n```\n\n### Use cases\n\nTagged templates can be used for various purposes, such as:\n\n- **String escaping**: Preventing XSS attacks by escaping user input\n- **Localization**: Translating template literals into different languages\n- **Custom formatting**: Applying custom formatting to the interpolated values\n\n### Example\n\nHere is a simple example of a tagged template that escapes HTML:\n\n```js live\nfunction escapeHTML(strings, ...values) {\n  return strings.reduce((result, string, i) => {\n    const value = values[i - 1];\n    return (\n      result +\n      (value\n        ? String(value)\n            .replace(/&/g, '&amp;')\n            .replace(/</g, '&lt;')\n            .replace(/>/g, '&gt;')\n        : '') +\n      string\n    );\n  });\n}\n\nconst userInput = '<script>alert(\"XSS\")</script>';\nconst result = escapeHTML`User input: ${userInput}`;\nconsole.log(result); // \"User input: &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;\"\n```\n\n## Further reading\n\n- [MDN Web Docs: Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)\n- [Exploring JS: Template literals](http://exploringjs.com/es6/ch_template-literals.html#tagged-templates)\n"
  },
  {
    "path": "questions/explain-the-concept-of-tagged-templates/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-tagged-templates\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Data Types & Variables\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-tagged-templates/zh-CN.mdx",
    "content": "---\ntitle: 解释带标签的模板的概念\n---\n\n## TL;DR\n\nJavaScript 中的带标签的模板允许您使用函数解析模板字面量。该函数将字面量字符串和值作为参数接收，从而可以自定义处理模板。例如：\n\n```js live\nfunction tag(strings, ...values) {\n  return strings[0] + values[0] + strings[1] + values[1] + strings[2];\n}\n\nconst result = tag`Hello ${'world'}! How are ${'you'}?`;\nconsole.log(result); // \"Hello world! How are you?\"\n```\n\n***\n\n## 带标签的模板\n\n### 什么是带标签的模板？\n\n带标签的模板是 JavaScript 中的一个特性，它允许您使用模板字面量调用一个函数（“标签”）。然后，标签函数可以以自定义方式处理模板字面量的各个部分（字面量字符串和插值）。\n\n### 语法\n\n带标签的模板的语法涉及在模板字面量之前放置一个函数名称：\n\n```js\nfunction tag(strings, ...values) {\n  // Custom processing\n}\n\ntag`template literal with ${values}`;\n```\n\n### 工作原理\n\n当调用带标签的模板时，标签函数会收到：\n\n1. 字面量字符串的数组（模板中未插值的各个部分）\n2. 作为附加参数的插值\n\n例如：\n\n```js live\nfunction tag(strings, ...values) {\n  console.log(strings); // [\"Hello \", \"! How are \", \"?\"]\n  console.log(values); // [\"world\", \"you\"]\n}\n\ntag`Hello ${'world'}! How are ${'you'}?`;\n```\n\n### 用例\n\n带标签的模板可用于各种目的，例如：\n\n* **字符串转义**：通过转义用户输入来防止 XSS 攻击\n* **本地化**：将模板字面量翻译成不同的语言\n* **自定义格式**：将自定义格式应用于插值\n\n### 示例\n\n这是一个转义 HTML 的带标签模板的简单示例：\n\n```js live\nfunction escapeHTML(strings, ...values) {\n  return strings.reduce((result, string, i) => {\n    const value = values[i - 1];\n    return (\n      result +\n      (value\n        ? String(value)\n            .replace(/&/g, '&amp;')\n            .replace(/</g, '&lt;')\n            .replace(/>/g, '&gt;')\n        : '') +\n      string\n    );\n  });\n}\n\nconst userInput = '<script>alert(\"XSS\")</script>';\nconst result = escapeHTML`User input: ${userInput}`;\nconsole.log(result); // \"User input: &lt;script&gt;alert(&quot;XSS&quot;)&lt;/script&gt;\"\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates)\n* [Exploring JS: Template literals](http://exploringjs.com/es6/ch_template-literals.html#tagged-templates)\n"
  },
  {
    "path": "questions/explain-the-concept-of-test-driven-development-tdd/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"98f2e179\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3ed088f8\",\n        \"2a7816d0\",\n        \"d5dd7a38\",\n        \"ed01c895\",\n        \"95e2f781\",\n        \"acde2c9c\",\n        \"4743c356\",\n        \"76a6b3db\",\n        \"7e8c69c7\",\n        \"2b49d068\",\n        \"f67e5291\",\n        \"4e4108c1\",\n        \"404afa0d\",\n        \"b3b131ee\",\n        \"9d80de6f\",\n        \"6b224a22\",\n        \"ea32196c\",\n        \"74b3912a\",\n        \"69d899e1\",\n        \"18483de4\",\n        \"76c60b9c\",\n        \"c35f3a7a\",\n        \"3654a55e\",\n        \"86676132\",\n        \"fbf54f94\",\n        \"d0575c14\",\n        \"6be8e1e4\",\n        \"f20174db\",\n        \"1a6bf10b\",\n        \"1f4770e5\",\n        \"ee140c7f\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3ed088f8\",\n        \"2a7816d0\",\n        \"d5dd7a38\",\n        \"ed01c895\",\n        \"95e2f781\",\n        \"acde2c9c\",\n        \"4743c356\",\n        \"76a6b3db\",\n        \"7e8c69c7\",\n        \"2b49d068\",\n        \"f67e5291\",\n        \"4e4108c1\",\n        \"404afa0d\",\n        \"b3b131ee\",\n        \"9d80de6f\",\n        \"6b224a22\",\n        \"ea32196c\",\n        \"74b3912a\",\n        \"69d899e1\",\n        \"18483de4\",\n        \"76c60b9c\",\n        \"c35f3a7a\",\n        \"3654a55e\",\n        \"86676132\",\n        \"fbf54f94\",\n        \"d0575c14\",\n        \"6be8e1e4\",\n        \"f20174db\",\n        \"1a6bf10b\",\n        \"1f4770e5\",\n        \"ee140c7f\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-test-driven-development-tdd/en-US.mdx",
    "content": "---\ntitle: Explain the concept of test-driven development (TDD)\n---\n\n## TL;DR\n\nTest-driven development (TDD) is a software development approach where you write tests before writing the actual code. The process involves writing a failing test, writing the minimum code to pass the test, and then refactoring the code while keeping the tests passing. This ensures that the code is always tested and helps in maintaining high code quality.\n\n---\n\n## What is test-driven development (TDD)?\n\nTest-driven development (TDD) is a software development methodology that emphasizes writing tests before writing the actual code. The primary goal of TDD is to ensure that the code is thoroughly tested and meets the specified requirements. The TDD process can be broken down into three main steps: Red, Green, and Refactor.\n\n### Red: Write a failing test\n\n1. Write a test for a new feature or functionality.\n2. Run the test to ensure it fails, confirming that the feature is not yet implemented.\n\n```js\n// Example using Jest\ntest('adds 1 + 2 to equal 3', () => {\n  expect(add(1, 2)).toBe(3);\n});\n```\n\n### Green: Write the minimum code to pass the test\n\n1. Write the simplest code possible to make the test pass.\n2. Run the test to ensure it passes.\n\n```js\nfunction add(a, b) {\n  return a + b;\n}\n```\n\n### Refactor: Improve the code\n\n1. Refactor the code to improve its structure and readability without changing its behavior.\n2. Ensure that all tests still pass after refactoring.\n\n```js\n// Refactored code (if needed)\nfunction add(a, b) {\n  return a + b; // In this simple example, no refactoring is needed\n}\n```\n\n## Benefits of TDD\n\n### Improved code quality\n\nTDD ensures that the code is thoroughly tested, which helps in identifying and fixing bugs early in the development process.\n\n### Better design\n\nWriting tests first forces developers to think about the design and requirements of the code, leading to better-structured and more maintainable code.\n\n### Faster debugging\n\nSince tests are written for each piece of functionality, it becomes easier to identify the source of a bug when a test fails.\n\n### Documentation\n\nTests serve as documentation for the code, making it easier for other developers to understand the functionality and purpose of the code.\n\n## Challenges of TDD\n\n### Initial learning curve\n\nDevelopers new to TDD may find it challenging to adopt this methodology initially.\n\n### Time-consuming\n\nWriting tests before writing the actual code can be time-consuming, especially for complex features.\n\n### Overhead\n\nMaintaining a large number of tests can become an overhead, especially when the codebase changes frequently.\n\n## Further reading\n\n- [Test-Driven Development by Example by Kent Beck](https://www.amazon.com/Test-Driven-Development-Kent-Beck/dp/0321146530)\n- [TDD on Martin Fowler's website](https://martinfowler.com/bliki/TestDrivenDevelopment.html)\n- [Jest documentation](https://jestjs.io/docs/getting-started)\n"
  },
  {
    "path": "questions/explain-the-concept-of-test-driven-development-tdd/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-test-driven-development-tdd\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"testing\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Testing\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-test-driven-development-tdd/zh-CN.mdx",
    "content": "---\ntitle: 解释测试驱动开发 (TDD) 的概念\n---\n\n## TL;DR\n\n测试驱动开发 (TDD) 是一种软件开发方法，您在编写实际代码之前编写测试。该过程包括编写一个失败的测试，编写通过测试所需的最小代码，然后在保持测试通过的同时重构代码。这确保了代码始终经过测试，并有助于保持高代码质量。\n\n***\n\n## 什么是测试驱动开发 (TDD)？\n\n测试驱动开发 (TDD) 是一种软件开发方法，它强调在编写实际代码之前编写测试。 TDD 的主要目标是确保代码经过全面测试并满足指定的要求。 TDD 过程可以分为三个主要步骤：红色、绿色和重构。\n\n### 红色：编写一个失败的测试\n\n1. 为新功能或功能编写测试。\n2. 运行测试以确保它失败，确认该功能尚未实现。\n\n```js\n// Example using Jest\ntest('adds 1 + 2 to equal 3', () => {\n  expect(add(1, 2)).toBe(3);\n});\n```\n\n### 绿色：编写通过测试所需的最小代码\n\n1. 编写最简单的代码以使测试通过。\n2. 运行测试以确保它通过。\n\n```js\nfunction add(a, b) {\n  return a + b;\n}\n```\n\n### 重构：改进代码\n\n1. 重构代码以改进其结构和可读性，而无需更改其行为。\n2. 确保所有测试在重构后仍然通过。\n\n```js\n// Refactored code (if needed)\nfunction add(a, b) {\n  return a + b; // In this simple example, no refactoring is needed\n}\n```\n\n## TDD 的好处\n\n### 改进的代码质量\n\nTDD 确保代码经过全面测试，这有助于在开发过程的早期识别和修复错误。\n\n### 更好的设计\n\n首先编写测试迫使开发人员思考代码的设计和需求，从而产生结构更好、更易于维护的代码。\n\n### 更快的调试\n\n由于为每个功能都编写了测试，因此当测试失败时，更容易确定错误的来源。\n\n### 文档\n\n测试充当代码的文档，使其他开发人员更容易理解代码的功能和目的。\n\n## TDD 的挑战\n\n### 初始学习曲线\n\n刚接触 TDD 的开发人员可能会发现最初采用这种方法具有挑战性。\n\n### 耗时\n\n在编写实际代码之前编写测试可能很耗时，尤其对于复杂的功能而言。\n\n### 开销\n\n维护大量测试可能会成为一种开销，尤其是在代码库经常更改时。\n\n## 延伸阅读\n\n* [Kent Beck 著的《测试驱动开发实例》](https://www.amazon.com/Test-Driven-Development-Kent-Beck/dp/0321146530)\n* [Martin Fowler 网站上的 TDD](https://martinfowler.com/bliki/TestDrivenDevelopment.html)\n* [Jest 文档](https://jestjs.io/docs/getting-started)\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-prototype-pattern/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"9eec2bcf\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"281bbcfa\",\n        \"cd6287b4\",\n        \"2a7816d0\",\n        \"ef514c68\",\n        \"dcd0dd8d\",\n        \"4e8ede6c\",\n        \"39554ae1\",\n        \"30fcf78\",\n        \"dcf962a3\",\n        \"4fd352b6\",\n        \"9a3a183b\",\n        \"cd6287b4\",\n        \"6b852229\",\n        \"97e7414d\",\n        \"277ca897\",\n        \"e95f7e1c\",\n        \"e3185288\",\n        \"852195c\",\n        \"4f390bfa\",\n        \"82c3077\",\n        \"893e18a0\",\n        \"1f4770e5\",\n        \"37ba55e8\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"281bbcfa\",\n        \"cd6287b4\",\n        \"2a7816d0\",\n        \"ef514c68\",\n        \"dcd0dd8d\",\n        \"4e8ede6c\",\n        \"39554ae1\",\n        \"30fcf78\",\n        \"dcf962a3\",\n        \"4fd352b6\",\n        \"9a3a183b\",\n        \"cd6287b4\",\n        \"6b852229\",\n        \"97e7414d\",\n        \"277ca897\",\n        \"e95f7e1c\",\n        \"e3185288\",\n        \"852195c\",\n        \"4f390bfa\",\n        \"82c3077\",\n        \"893e18a0\",\n        \"1f4770e5\",\n        \"37ba55e8\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-prototype-pattern/en-US.mdx",
    "content": "---\ntitle: Explain the concept of the Prototype pattern\n---\n\n## TL;DR\n\nThe Prototype pattern is a creational design pattern used to create new objects by copying an existing object, known as the prototype. This pattern is useful when the cost of creating a new object is more expensive than cloning an existing one. In JavaScript, this can be achieved using the `Object.create` method or by using the `prototype` property of a constructor function.\n\n```js live\nconst prototypeObject = {\n  greet() {\n    console.log('Hello, world!');\n  },\n};\n\nconst newObject = Object.create(prototypeObject);\nnewObject.greet(); // Outputs: Hello, world!\n```\n\n---\n\n## The Prototype pattern\n\nThe Prototype pattern is a creational design pattern that allows you to create new objects by copying an existing object, known as the prototype. This pattern is particularly useful when the cost of creating a new object is more expensive than cloning an existing one.\n\n### How it works\n\nIn the Prototype pattern, an object is used as a blueprint for creating new objects. This blueprint object is called the prototype. New objects are created by copying the prototype, which can be done in various ways depending on the programming language.\n\n### Implementation in JavaScript\n\nIn JavaScript, the Prototype pattern can be implemented using the `Object.create` method or by using the `prototype` property of a constructor function.\n\n#### Using `Object.create`\n\nThe `Object.create` method creates a new object with the specified prototype object and properties.\n\n```js live\nconst prototypeObject = {\n  greet() {\n    console.log('Hello, world!');\n  },\n};\n\nconst newObject = Object.create(prototypeObject);\nnewObject.greet(); // Outputs: Hello, world!\n```\n\nIn this example, `newObject` is created with `prototypeObject` as its prototype. This means that `newObject` inherits the `greet` method from `prototypeObject`.\n\n#### Using constructor functions and the `prototype` property\n\nAnother way to implement the Prototype pattern in JavaScript is by using constructor functions and the `prototype` property.\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nPerson.prototype.greet = function () {\n  console.log(`Hello, my name is ${this.name}`);\n};\n\nconst person1 = new Person('Alice');\nconst person2 = new Person('Bob');\n\nperson1.greet(); // Outputs: Hello, my name is Alice\nperson2.greet(); // Outputs: Hello, my name is Bob\n```\n\nIn this example, the `Person` constructor function is used to create new `Person` objects. The `greet` method is added to the `Person.prototype`, so all instances of `Person` inherit this method.\n\n### Advantages\n\n- Reduces the cost of creating new objects by cloning existing ones\n- Simplifies the creation of complex objects\n- Promotes code reuse and reduces redundancy\n\n### Disadvantages\n\n- Cloning objects can be less efficient than creating new ones in some cases\n- Can lead to issues with deep cloning if the prototype object contains nested objects\n\n## Further reading\n\n- [MDN Web Docs: Object.create](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create)\n- [MDN Web Docs: Prototypes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes)\n- [Refactoring Guru: Prototype pattern](https://refactoring.guru/design-patterns/prototype)\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-prototype-pattern/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-the-prototype-pattern\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Design Patterns\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-prototype-pattern/zh-CN.mdx",
    "content": "---\ntitle: 解释原型模式的概念\n---\n\n## TL;DR\n\n原型模式是一种创建型设计模式，用于通过复制现有对象（称为原型）来创建新对象。当创建新对象的成本高于克隆现有对象时，此模式非常有用。在 JavaScript 中，这可以使用 `Object.create` 方法或使用构造函数函数的 `prototype` 属性来实现。\n\n```js live\nconst prototypeObject = {\n  greet() {\n    console.log('Hello, world!');\n  },\n};\n\nconst newObject = Object.create(prototypeObject);\nnewObject.greet(); // Outputs: Hello, world!\n```\n\n***\n\n## 原型模式\n\n原型模式是一种创建型设计模式，它允许您通过复制现有对象（称为原型）来创建新对象。当创建新对象的成本高于克隆现有对象时，此模式特别有用。\n\n### 工作原理\n\n在原型模式中，一个对象被用作创建新对象的蓝图。这个蓝图对象被称为原型。通过复制原型来创建新对象，这可以通过多种方式完成，具体取决于编程语言。\n\n### 在 JavaScript 中的实现\n\n在 JavaScript 中，原型模式可以使用 `Object.create` 方法或使用构造函数函数的 `prototype` 属性来实现。\n\n#### 使用 `Object.create`\n\n`Object.create` 方法使用指定原型对象和属性创建一个新对象。\n\n```js live\nconst prototypeObject = {\n  greet() {\n    console.log('Hello, world!');\n  },\n};\n\nconst newObject = Object.create(prototypeObject);\nnewObject.greet(); // Outputs: Hello, world!\n```\n\n在此示例中，`newObject` 以 `prototypeObject` 作为其原型创建。这意味着 `newObject` 从 `prototypeObject` 继承了 `greet` 方法。\n\n#### 使用构造函数和 `prototype` 属性\n\n在 JavaScript 中实现原型模式的另一种方法是使用构造函数和 `prototype` 属性。\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nPerson.prototype.greet = function () {\n  console.log(`Hello, my name is ${this.name}`);\n};\n\nconst person1 = new Person('Alice');\nconst person2 = new Person('Bob');\n\nperson1.greet(); // Outputs: Hello, my name is Alice\nperson2.greet(); // Outputs: Hello, my name is Bob\n```\n\n在此示例中，`Person` 构造函数用于创建新的 `Person` 对象。`greet` 方法被添加到 `Person.prototype`，因此 `Person` 的所有实例都继承此方法。\n\n### 优点\n\n* 通过克隆现有对象来降低创建新对象的成本\n* 简化复杂对象的创建\n* 促进代码重用并减少冗余\n\n### 缺点\n\n* 在某些情况下，克隆对象可能不如创建新对象有效\n* 如果原型对象包含嵌套对象，则可能导致深度克隆出现问题\n\n## 延伸阅读\n\n* [MDN Web Docs: Object.create](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create)\n* [MDN Web Docs: Prototypes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes)\n* [Refactoring Guru: Prototype pattern](https://refactoring.guru/design-patterns/prototype)\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-singleton-pattern/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"8d049ff2\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"c0e2e88a\",\n        \"a463f5e0\",\n        \"2a7816d0\",\n        \"c2cf3e5c\",\n        \"f8de5ab\",\n        \"b6df0131\",\n        \"a86655a8\",\n        \"30fcf78\",\n        \"fb8c9add\",\n        \"51751f90\",\n        \"361a279\",\n        \"5e04a9ba\",\n        \"a463f5e0\",\n        \"6dd3b324\",\n        \"1e0d2b6e\",\n        \"1f4770e5\",\n        \"5b7bc2dc\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"c0e2e88a\",\n        \"a463f5e0\",\n        \"2a7816d0\",\n        \"c2cf3e5c\",\n        \"f8de5ab\",\n        \"b6df0131\",\n        \"a86655a8\",\n        \"30fcf78\",\n        \"fb8c9add\",\n        \"51751f90\",\n        \"361a279\",\n        \"5e04a9ba\",\n        \"a463f5e0\",\n        \"6dd3b324\",\n        \"1e0d2b6e\",\n        \"1f4770e5\",\n        \"5b7bc2dc\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-singleton-pattern/en-US.mdx",
    "content": "---\ntitle: Explain the concept of the Singleton pattern\n---\n\n## TL;DR\n\nThe Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. This is useful when exactly one object is needed to coordinate actions across the system. In JavaScript, this can be implemented using closures or ES6 classes.\n\n```js live\nclass Singleton {\n  constructor() {\n    if (!Singleton.instance) {\n      Singleton.instance = this;\n    }\n    return Singleton.instance;\n  }\n}\n\nconst instance1 = new Singleton();\nconst instance2 = new Singleton();\n\nconsole.log(instance1 === instance2); // true\n```\n\n---\n\n## Singleton pattern\n\nThe Singleton pattern is a design pattern that restricts the instantiation of a class to one single instance. This is particularly useful when exactly one object is needed to coordinate actions across the system.\n\n### Key characteristics\n\n- **Single instance**: Ensures that a class has only one instance.\n- **Global access**: Provides a global point of access to the instance.\n- **Lazy initialization**: The instance is created only when it is needed.\n\n### Implementation in JavaScript\n\nThere are several ways to implement the Singleton pattern in JavaScript. Here are two common methods:\n\n#### Using closures\n\n```js live\nconst Singleton = (function () {\n  let instance;\n\n  function createInstance() {\n    const object = new Object('I am the instance');\n    return object;\n  }\n\n  return {\n    getInstance: function () {\n      if (!instance) {\n        instance = createInstance();\n      }\n      return instance;\n    },\n  };\n})();\n\nconst instance1 = Singleton.getInstance();\nconst instance2 = Singleton.getInstance();\n\nconsole.log(instance1 === instance2); // true\n```\n\n#### Using ES6 classes\n\n```js live\nclass Singleton {\n  constructor() {\n    if (!Singleton.instance) {\n      Singleton.instance = this;\n    }\n    return Singleton.instance;\n  }\n}\n\nconst instance1 = new Singleton();\nconst instance2 = new Singleton();\n\nconsole.log(instance1 === instance2); // true\n```\n\n### Use cases\n\n- **Configuration objects**: When you need a single configuration object shared across the application.\n- **Logging**: A single logging instance to manage log entries.\n- **Database connections**: Ensuring only one connection is made to the database.\n\n## Further reading\n\n- [Singleton pattern on Wikipedia](https://en.wikipedia.org/wiki/Singleton_pattern)\n- [JavaScript Design Patterns: Singleton](https://www.dofactory.com/javascript/design-patterns/singleton)\n- [MDN Web Docs: Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-singleton-pattern/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-the-singleton-pattern\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Design Patterns\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-singleton-pattern/zh-CN.mdx",
    "content": "---\ntitle: 解释单例模式的概念\n---\n\n## TL;DR\n\n单例模式确保一个类只有一个实例，并提供对该实例的全局访问点。当只需要一个对象来协调整个系统中的操作时，这非常有用。在 JavaScript 中，这可以使用闭包或 ES6 类来实现。\n\n```js live\nclass Singleton {\n  constructor() {\n    if (!Singleton.instance) {\n      Singleton.instance = this;\n    }\n    return Singleton.instance;\n  }\n}\n\nconst instance1 = new Singleton();\nconst instance2 = new Singleton();\n\nconsole.log(instance1 === instance2); // true\n```\n\n***\n\n## 单例模式\n\n单例模式是一种设计模式，它将一个类的实例化限制为单个实例。当只需要一个对象来协调整个系统中的操作时，这特别有用。\n\n### 关键特征\n\n* **单个实例**：确保一个类只有一个实例。\n* **全局访问**：提供对该实例的全局访问点。\n* **延迟初始化**：仅在需要时才创建实例。\n\n### 在 JavaScript 中的实现\n\n有几种方法可以在 JavaScript 中实现单例模式。以下是两种常见的方法：\n\n#### 使用闭包\n\n```js live\nconst Singleton = (function () {\n  let instance;\n\n  function createInstance() {\n    const object = new Object('I am the instance');\n    return object;\n  }\n\n  return {\n    getInstance: function () {\n      if (!instance) {\n        instance = createInstance();\n      }\n      return instance;\n    },\n  };\n})();\n\nconst instance1 = Singleton.getInstance();\nconst instance2 = Singleton.getInstance();\n\nconsole.log(instance1 === instance2); // true\n```\n\n#### 使用 ES6 类\n\n```js live\nclass Singleton {\n  constructor() {\n    if (!Singleton.instance) {\n      Singleton.instance = this;\n    }\n    return Singleton.instance;\n  }\n}\n\nconst instance1 = new Singleton();\nconst instance2 = new Singleton();\n\nconsole.log(instance1 === instance2); // true\n```\n\n### 用例\n\n* **配置对象**：当您需要一个在整个应用程序中共享的配置对象时。\n* **日志记录**：用于管理日志条目的单个日志记录实例。\n* **数据库连接**：确保只建立一个到数据库的连接。\n\n## 延伸阅读\n\n* [维基百科上的单例模式](https://en.wikipedia.org/wiki/Singleton_pattern)\n* [JavaScript 设计模式：单例](https://www.dofactory.com/javascript/design-patterns/singleton)\n* [MDN Web 文档：类](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-spread-operator-and-its-uses/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"4cddec00\",\n        \"18e2baf1\",\n        \"2a7816d0\",\n        \"466484ca\",\n        \"ee6c7c6d\",\n        \"e1ffa3a\",\n        \"f909b6e2\",\n        \"ca298e03\",\n        \"32a546a9\",\n        \"d2446c9d\",\n        \"c0fb02fb\",\n        \"b00d0348\",\n        \"40c21174\",\n        \"318becfc\",\n        \"c8de8ea9\",\n        \"81cf4eef\",\n        \"4dded10a\",\n        \"450199cb\",\n        \"1858d47f\",\n        \"1f4770e5\",\n        \"af185466\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4cddec00\",\n        \"18e2baf1\",\n        \"2a7816d0\",\n        \"466484ca\",\n        \"ee6c7c6d\",\n        \"e1ffa3a\",\n        \"f909b6e2\",\n        \"ca298e03\",\n        \"32a546a9\",\n        \"d2446c9d\",\n        \"c0fb02fb\",\n        \"b00d0348\",\n        \"40c21174\",\n        \"318becfc\",\n        \"c8de8ea9\",\n        \"81cf4eef\",\n        \"4dded10a\",\n        \"450199cb\",\n        \"1858d47f\",\n        \"1f4770e5\",\n        \"af185466\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"d5d88f1e\"\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-spread-operator-and-its-uses/en-US.mdx",
    "content": "---\ntitle: Explain the concept of the spread operator and its uses\n---\n\n## TL;DR\n\nThe spread operator (`...`) in JavaScript allows you to expand elements of an iterable (like an array or object) into individual elements. It is commonly used for copying arrays or objects, merging arrays or objects, and passing elements of an array as arguments to a function.\n\n```js live\n// Copying an array\nconst arr1 = [1, 2, 3];\nconst arr2 = [...arr1];\nconsole.log(arr2); // Output: [1, 2, 3]\n\n// Merging arrays\nconst arr3 = [4, 5, 6];\nconst mergedArray = [...arr1, ...arr3];\nconsole.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]\n\n// Copying an object\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { ...obj1 };\nconsole.log(obj2); // Output: { a: 1, b: 2 }\n\n// Merging objects\nconst obj3 = { c: 3, d: 4 };\nconst mergedObject = { ...obj1, ...obj3 };\nconsole.log(mergedObject); // Output: { a: 1, b: 2, c: 3, d: 4 }\n\n// Passing array elements as function arguments\nconst sum = (x, y, z) => x + y + z;\nconst numbers = [1, 2, 3];\nconsole.log(sum(...numbers)); // Output: 6\n```\n\n---\n\n## The spread operator and its uses\n\n### Copying arrays\n\nThe spread operator can be used to create a shallow copy of an array. This is useful when you want to duplicate an array without affecting the original array.\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr2 = [...arr1];\nconsole.log(arr2); // Output: [1, 2, 3]\n```\n\n### Merging arrays\n\nYou can use the spread operator to merge multiple arrays into one. This is a concise and readable way to combine arrays.\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr3 = [4, 5, 6];\nconst mergedArray = [...arr1, ...arr3];\nconsole.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]\n```\n\n### Copying objects\n\nSimilar to arrays, the spread operator can be used to create a shallow copy of an object. This is useful for duplicating objects without affecting the original object.\n\n```js live\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { ...obj1 };\nconsole.log(obj2); // Output: { a: 1, b: 2 }\n```\n\n### Merging objects\n\nThe spread operator can also be used to merge multiple objects into one. This is particularly useful for combining properties from different objects.\n\n```js live\nconst obj1 = { a: 1, b: 2 };\nconst obj3 = { c: 3, d: 4 };\nconst mergedObject = { ...obj1, ...obj3 };\nconsole.log(mergedObject); // Output: { a: 1, b: 2, c: 3, d: 4 }\n```\n\n### Passing array elements as function arguments\n\nThe spread operator allows you to pass elements of an array as individual arguments to a function. This is useful for functions that accept multiple arguments.\n\n```js live\nconst sum = (x, y, z) => x + y + z;\nconst numbers = [1, 2, 3];\nconsole.log(sum(...numbers)); // Output: 6\n```\n\n## Further reading\n\n- [MDN Web Docs: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n- [JavaScript.info: Spread operator](https://javascript.info/rest-parameters-spread-operator#spread-operator)\n- [FreeCodeCamp: JavaScript Spread and Rest Operators](https://www.freecodecamp.org/news/javascript-spread-and-rest-operators/)\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-spread-operator-and-its-uses/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-the-spread-operator-and-its-uses\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Operators & Control Flow\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-spread-operator-and-its-uses/zh-CN.mdx",
    "content": "---\ntitle: 解释展开运算符的概念及其用途\n---\n\n## TL;DR\n\nJavaScript 中的展开运算符 (`...`) 允许你将可迭代对象（如数组或对象）的元素展开为单个元素。它通常用于复制数组或对象、合并数组或对象，以及将数组的元素作为参数传递给函数。\n\n```js live\n// Copying an array\nconst arr1 = [1, 2, 3];\nconst arr2 = [...arr1];\nconsole.log(arr2); // Output: [1, 2, 3]\n\n// Merging arrays\nconst arr3 = [4, 5, 6];\nconst mergedArray = [...arr1, ...arr3];\nconsole.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]\n\n// Copying an object\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { ...obj1 };\nconsole.log(obj2); // Output: { a: 1, b: 2 }\n\n// Merging objects\nconst obj3 = { c: 3, d: 4 };\nconst mergedObject = { ...obj1, ...obj3 };\nconsole.log(mergedObject); // Output: { a: 1, b: 2, c: 3, d: 4 }\n\n// Passing array elements as function arguments\nconst sum = (x, y, z) => x + y + z;\nconst numbers = [1, 2, 3];\nconsole.log(sum(...numbers)); // Output: 6\n```\n\n***\n\n## 展开运算符及其用途\n\n### 复制数组\n\n展开运算符可用于创建数组的浅拷贝。当你想要复制一个数组而不影响原始数组时，这很有用。\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr2 = [...arr1];\nconsole.log(arr2); // Output: [1, 2, 3]\n```\n\n### 合并数组\n\n你可以使用展开运算符将多个数组合并成一个。这是一种简洁易读的组合数组的方式。\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr3 = [4, 5, 6];\nconst mergedArray = [...arr1, ...arr3];\nconsole.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]\n```\n\n### 复制对象\n\n与数组类似，展开运算符可用于创建对象的浅拷贝。这对于复制对象而不影响原始对象很有用。\n\n```js live\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { ...obj1 };\nconsole.log(obj2); // Output: { a: 1, b: 2 }\n```\n\n### 合并对象\n\n展开运算符也可用于将多个对象合并成一个。这对于组合来自不同对象的属性特别有用。\n\n```js live\nconst obj1 = { a: 1, b: 2 };\nconst obj3 = { c: 3, d: 4 };\nconst mergedObject = { ...obj1, ...obj3 };\nconsole.log(mergedObject); // Output: { a: 1, b: 2, c: 3, d: 4 }\n```\n\n### 将数组元素作为函数参数传递\n\n展开运算符允许你将数组的元素作为单个参数传递给函数。这对于接受多个参数的函数很有用。\n\n```js live\nconst sum = (x, y, z) => x + y + z;\nconst numbers = [1, 2, 3];\nconsole.log(sum(...numbers)); // Output: 6\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n* [JavaScript.info: Spread operator](https://javascript.info/rest-parameters-spread-operator#spread-operator)\n* [FreeCodeCamp: JavaScript Spread and Rest Operators](https://www.freecodecamp.org/news/javascript-spread-and-rest-operators/)\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-strategy-pattern/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"792ce120\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"1fff678c\",\n        \"5f29c9ba\",\n        \"2a7816d0\",\n        \"5e3a8d3a\",\n        \"25841bc3\",\n        \"4eb9debe\",\n        \"eb32a928\",\n        \"22000045\",\n        \"9b5019f0\",\n        \"7632dff0\",\n        \"858a84f1\",\n        \"2819c383\",\n        \"79dea2d5\",\n        \"c4e00cf2\",\n        \"4eab9522\",\n        \"1f4770e5\",\n        \"e4e7fbdd\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"1fff678c\",\n        \"5f29c9ba\",\n        \"2a7816d0\",\n        \"5e3a8d3a\",\n        \"25841bc3\",\n        \"4eb9debe\",\n        \"eb32a928\",\n        \"22000045\",\n        \"9b5019f0\",\n        \"7632dff0\",\n        \"858a84f1\",\n        \"2819c383\",\n        \"79dea2d5\",\n        \"c4e00cf2\",\n        \"4eab9522\",\n        \"1f4770e5\",\n        \"e4e7fbdd\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-strategy-pattern/en-US.mdx",
    "content": "---\ntitle: Explain the concept of the Strategy pattern\n---\n\n## TL;DR\n\nThe Strategy pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one as a separate class, and make them interchangeable. This pattern lets the algorithm vary independently from the clients that use it. For example, if you have different sorting algorithms, you can define each one as a strategy and switch between them without changing the client code.\n\n```js live\nclass Context {\n  constructor(strategy) {\n    this.strategy = strategy;\n  }\n\n  executeStrategy(data) {\n    return this.strategy.doAlgorithm(data);\n  }\n}\n\nclass ConcreteStrategyA {\n  doAlgorithm(data) {\n    // Implementation of algorithm A\n    return 'Algorithm A was run on ' + data;\n  }\n}\n\nclass ConcreteStrategyB {\n  doAlgorithm(data) {\n    // Implementation of algorithm B\n    return 'Algorithm B was run on ' + data;\n  }\n}\n\n// Usage\nconst context = new Context(new ConcreteStrategyA());\ncontext.executeStrategy('someData'); // Output: Algorithm A was run on someData\n```\n\n---\n\n## The Strategy pattern\n\n### Definition\n\nThe Strategy pattern is a behavioral design pattern that enables selecting an algorithm's behavior at runtime. It defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern allows the algorithm to vary independently from the clients that use it.\n\n### Components\n\n1. **Context**: Maintains a reference to a `Strategy` object and is configured with a `ConcreteStrategy` object.\n2. **Strategy**: An interface common to all supported algorithms. The `Context` uses this interface to call the algorithm defined by a `ConcreteStrategy`.\n3. **ConcreteStrategy**: Implements the `Strategy` interface to provide a specific algorithm.\n\n### Example\n\nConsider a scenario where you have different sorting algorithms and you want to switch between them without changing the client code.\n\n```js live\n// Strategy interface\nclass Strategy {\n  doAlgorithm(data) {\n    throw new Error('This method should be overridden!');\n  }\n}\n\n// ConcreteStrategyA\nclass ConcreteStrategyA extends Strategy {\n  doAlgorithm(data) {\n    return data.sort((a, b) => a - b); // Example: ascending sort\n  }\n}\n\n// ConcreteStrategyB\nclass ConcreteStrategyB extends Strategy {\n  doAlgorithm(data) {\n    return data.sort((a, b) => b - a); // Example: descending sort\n  }\n}\n\n// Context\nclass Context {\n  constructor(strategy) {\n    this.strategy = strategy;\n  }\n\n  setStrategy(strategy) {\n    this.strategy = strategy;\n  }\n\n  executeStrategy(data) {\n    return this.strategy.doAlgorithm(data);\n  }\n}\n\n// Usage\nconst data = [3, 1, 4, 1, 5, 9];\nconst context = new Context(new ConcreteStrategyA());\nconsole.log(context.executeStrategy([...data])); // Output: [1, 1, 3, 4, 5, 9]\n\ncontext.setStrategy(new ConcreteStrategyB());\nconsole.log(context.executeStrategy([...data])); // Output: [9, 5, 4, 3, 1, 1]\n```\n\n### Benefits\n\n- **Flexibility**: You can change the algorithm at runtime.\n- **Maintainability**: Adding new strategies does not affect existing code.\n- **Encapsulation**: Each algorithm is encapsulated in its own class.\n\n### Drawbacks\n\n- **Overhead**: Increased number of classes and objects.\n- **Complexity**: Can make the system more complex if not used judiciously.\n\n## Further reading\n\n- [Strategy pattern on Wikipedia](https://en.wikipedia.org/wiki/Strategy_pattern)\n- [Refactoring Guru: Strategy pattern](https://refactoring.guru/design-patterns/strategy)\n- [MDN Web Docs: JavaScript classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-strategy-pattern/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-the-strategy-pattern\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Design Patterns\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-strategy-pattern/zh-CN.mdx",
    "content": "---\ntitle: 解释策略模式的概念\n---\n\n## TL;DR\n\n策略模式是一种行为型设计模式，它允许您定义一系列算法，将每个算法封装成一个单独的类，并使它们可以互换。这种模式使算法可以独立于使用它的客户端而变化。例如，如果您有不同的排序算法，您可以将每个算法定义为一个策略，并在它们之间切换，而无需更改客户端代码。\n\n```js live\nclass Context {\n  constructor(strategy) {\n    this.strategy = strategy;\n  }\n\n  executeStrategy(data) {\n    return this.strategy.doAlgorithm(data);\n  }\n}\n\nclass ConcreteStrategyA {\n  doAlgorithm(data) {\n    // Implementation of algorithm A\n    return 'Algorithm A was run on ' + data;\n  }\n}\n\nclass ConcreteStrategyB {\n  doAlgorithm(data) {\n    // Implementation of algorithm B\n    return 'Algorithm B was run on ' + data;\n  }\n}\n\n// Usage\nconst context = new Context(new ConcreteStrategyA());\ncontext.executeStrategy('someData'); // Output: Algorithm A was run on someData\n```\n\n***\n\n## 策略模式\n\n### 定义\n\n策略模式是一种行为型设计模式，它允许在运行时选择算法的行为。它定义了一系列算法，封装了每一个算法，并使它们可以互换。这种模式允许算法独立于使用它的客户端而变化。\n\n### 组件\n\n1. **Context**: 维护对 `Strategy` 对象的引用，并使用 `ConcreteStrategy` 对象进行配置。\n2. **Strategy**: 所有支持的算法通用的接口。`Context` 使用此接口来调用由 `ConcreteStrategy` 定义的算法。\n3. **ConcreteStrategy**: 实现 `Strategy` 接口以提供特定的算法。\n\n### 示例\n\n考虑一个场景，您有不同的排序算法，并且您希望在它们之间切换，而无需更改客户端代码。\n\n```js live\n// Strategy interface\nclass Strategy {\n  doAlgorithm(data) {\n    throw new Error('This method should be overridden!');\n  }\n}\n\n// ConcreteStrategyA\nclass ConcreteStrategyA extends Strategy {\n  doAlgorithm(data) {\n    return data.sort((a, b) => a - b); // Example: ascending sort\n  }\n}\n\n// ConcreteStrategyB\nclass ConcreteStrategyB extends Strategy {\n  doAlgorithm(data) {\n    return data.sort((a, b) => b - a); // Example: descending sort\n  }\n}\n\n// Context\nclass Context {\n  constructor(strategy) {\n    this.strategy = strategy;\n  }\n\n  setStrategy(strategy) {\n    this.strategy = strategy;\n  }\n\n  executeStrategy(data) {\n    return this.strategy.doAlgorithm(data);\n  }\n}\n\n// Usage\nconst data = [3, 1, 4, 1, 5, 9];\nconst context = new Context(new ConcreteStrategyA());\nconsole.log(context.executeStrategy([...data])); // Output: [1, 1, 3, 4, 5, 9]\n\ncontext.setStrategy(new ConcreteStrategyB());\nconsole.log(context.executeStrategy([...data])); // Output: [9, 5, 4, 3, 1, 1]\n```\n\n### 优点\n\n* **灵活性**：您可以在运行时更改算法。\n* **可维护性**：添加新的策略不会影响现有代码。\n* **封装**：每个算法都封装在自己的类中。\n\n### 缺点\n\n* **开销**：增加了类和对象的数量。\n* **复杂性**：如果使用不当，会使系统更加复杂。\n\n## 延伸阅读\n\n* [维基百科上的策略模式](https://en.wikipedia.org/wiki/Strategy_pattern)\n* [Refactoring Guru: 策略模式](https://refactoring.guru/design-patterns/strategy)\n* [MDN Web Docs: JavaScript 类](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-web-socket-api/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"cc037bfb\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"1927e37a\",\n        \"d9d44665\",\n        \"e8f40c5d\",\n        \"2a7816d0\",\n        \"c92c0dcf\",\n        \"7dedde60\",\n        \"65abfcef\",\n        \"dec9bcb3\",\n        \"4e8ede6c\",\n        \"2366468e\",\n        \"19c254ba\",\n        \"19d8c504\",\n        \"7989cb83\",\n        \"6dd3b324\",\n        \"70cc2c28\",\n        \"1f4770e5\",\n        \"abc6b4bc\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"1927e37a\",\n        \"d9d44665\",\n        \"e8f40c5d\",\n        \"2a7816d0\",\n        \"c92c0dcf\",\n        \"7dedde60\",\n        \"65abfcef\",\n        \"dec9bcb3\",\n        \"4e8ede6c\",\n        \"2366468e\",\n        \"19c254ba\",\n        \"19d8c504\",\n        \"7989cb83\",\n        \"6dd3b324\",\n        \"70cc2c28\",\n        \"1f4770e5\",\n        \"abc6b4bc\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-web-socket-api/en-US.mdx",
    "content": "---\ntitle: Explain the concept of the Web Socket API\n---\n\n## TL;DR\n\nThe WebSocket API provides a way to open a persistent connection between a client and a server, allowing for real-time, two-way communication. Unlike HTTP, which is request-response based, WebSocket enables full-duplex communication, meaning both the client and server can send and receive messages independently. This is particularly useful for applications like chat apps, live updates, and online gaming.\n\nThe following example uses Postman's WebSocket echo service to demonstrate how web sockets work.\n\n```js live\n// Postman's echo server that will echo back messages you send\nconst socket = new WebSocket('wss://ws.postman-echo.com/raw');\n\n// Event listener for when the connection is open\nsocket.addEventListener('open', function (event) {\n  socket.send('Hello Server!'); // Sends the message to the Postman WebSocket server\n});\n\n// Event listener for when a message is received from the server\nsocket.addEventListener('message', function (event) {\n  console.log('Message from server ', event.data);\n});\n```\n\n---\n\n## What is the WebSocket API?\n\nThe WebSocket API is a technology that provides a way to establish a persistent, low-latency, full-duplex communication channel between a client (usually a web browser) and a server. This is different from the traditional HTTP request-response model, which is stateless and requires a new connection for each request.\n\n### Key features\n\n- **Full-duplex communication**: Both the client and server can send and receive messages independently.\n- **Low latency**: The persistent connection reduces the overhead of establishing a new connection for each message.\n- **Real-time updates**: Ideal for applications that require real-time data, such as chat applications, live sports updates, and online gaming.\n\n### How it works\n\n1. **Connection establishment**: The client initiates a WebSocket connection by sending a handshake request to the server.\n2. **Handshake response**: The server responds with a handshake response, and if successful, the connection is established.\n3. **Data exchange**: Both the client and server can now send and receive messages independently over the established connection.\n4. **Connection closure**: Either the client or server can close the connection when it is no longer needed.\n\n### Example usage\n\nHere is a basic example of how to use the WebSocket API in JavaScript, using Postman's WebSocket Echo Service.\n\n```js live\n// Postman's echo server that will echo back messages you send\nconst socket = new WebSocket('wss://ws.postman-echo.com/raw');\n\n// Event listener for when the connection is open\nsocket.addEventListener('open', function (event) {\n  console.log('Connection opened');\n  socket.send('Hello Server!'); // Sends the message to the Postman WebSocket server\n});\n\n// Event listener for when a message is received from the server\nsocket.addEventListener('message', function (event) {\n  console.log('Message from server ', event.data);\n});\n\n// Event listener for when the connection is closed\nsocket.addEventListener('close', function (event) {\n  console.log('Connection closed');\n});\n\n// Event listener for when an error occurs\nsocket.addEventListener('error', function (event) {\n  console.error('WebSocket error: ', event);\n});\n```\n\n### Use cases\n\n- **Chat applications**: Real-time messaging between users.\n- **Live updates**: Stock prices, sports scores, or news updates.\n- **Online gaming**: Real-time interaction between players.\n- **Collaborative tools**: Real-time document editing or whiteboarding.\n\n## Further reading\n\n- [MDN WebSocket API documentation](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)\n- [WebSocket.org](https://www.websocket.org/)\n- [Introduction to WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications)\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-web-socket-api/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-the-web-socket-api\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"networking\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-the-web-socket-api/zh-CN.mdx",
    "content": "---\ntitle: 解释 Web Socket API 的概念\n---\n\n## TL;DR\n\nWebSocket API 提供了一种在客户端和服务器之间打开持久连接的方式，允许进行实时的双向通信。与基于请求-响应的 HTTP 不同，WebSocket 实现了全双工通信，这意味着客户端和服务器都可以独立地发送和接收消息。这对于聊天应用程序、实时更新和在线游戏等应用程序特别有用。\n\n以下示例使用 Postman 的 WebSocket 回显服务来演示 WebSockets 的工作原理。\n\n```js live\n// Postman's echo server that will echo back messages you send\nconst socket = new WebSocket('wss://ws.postman-echo.com/raw');\n\n// Event listener for when the connection is open\nsocket.addEventListener('open', function (event) {\n  socket.send('Hello Server!'); // Sends the message to the Postman WebSocket server\n});\n\n// Event listener for when a message is received from the server\nsocket.addEventListener('message', function (event) {\n  console.log('Message from server ', event.data);\n});\n```\n\n***\n\n## 什么是 WebSocket API？\n\nWebSocket API 是一种技术，它提供了一种在客户端（通常是 Web 浏览器）和服务器之间建立持久的、低延迟的、全双工通信通道的方式。这与传统的 HTTP 请求-响应模型不同，后者是无状态的，并且需要为每个请求建立新的连接。\n\n### 关键特性\n\n*   **全双工通信**：客户端和服务器都可以独立地发送和接收消息。\n*   **低延迟**：持久连接减少了为每条消息建立新连接的开销。\n*   **实时更新**：非常适合需要实时数据的应用程序，例如聊天应用程序、实时体育更新和在线游戏。\n\n### 它是如何工作的\n\n1.  **连接建立**：客户端通过向服务器发送握手请求来启动 WebSocket 连接。\n2.  **握手响应**：服务器使用握手响应进行响应，如果成功，则建立连接。\n3.  **数据交换**：客户端和服务器现在可以通过已建立的连接独立地发送和接收消息。\n4.  **连接关闭**：当不再需要连接时，客户端或服务器都可以关闭连接。\n\n### 使用示例\n\n这是一个关于如何在 JavaScript 中使用 WebSocket API 的基本示例，使用 Postman 的 WebSocket Echo Service。\n\n```js live\n// Postman's echo server that will echo back messages you send\nconst socket = new WebSocket('wss://ws.postman-echo.com/raw');\n\n// Event listener for when the connection is open\nsocket.addEventListener('open', function (event) {\n  console.log('Connection opened');\n  socket.send('Hello Server!'); // Sends the message to the Postman WebSocket server\n});\n\n// Event listener for when a message is received from the server\nsocket.addEventListener('message', function (event) {\n  console.log('Message from server ', event.data);\n});\n\n// Event listener for when the connection is closed\nsocket.addEventListener('close', function (event) {\n  console.log('Connection closed');\n});\n\n// Event listener for when an error occurs\nsocket.addEventListener('error', function (event) {\n  console.error('WebSocket error: ', event);\n});\n```\n\n### 用例\n\n*   **聊天应用程序**：用户之间的实时消息传递。\n*   **实时更新**：股票价格、体育比分或新闻更新。\n*   **在线游戏**：玩家之间的实时互动。\n*   **协作工具**：实时文档编辑或白板。\n\n## 延伸阅读\n\n*   [MDN WebSocket API 文档](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)\n*   [WebSocket.org](https://www.websocket.org/)\n*   [WebSockets 简介](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications)\n"
  },
  {
    "path": "questions/explain-the-concept-of-this-binding-in-event-handlers/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"9d9ca7d4\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"b02cafdb\",\n        \"2a7816d0\",\n        \"92a95930\",\n        \"5689734b\",\n        \"51779df7\",\n        \"f1bbbe40\",\n        \"caca90b3\",\n        \"94f1f97f\",\n        \"c037271b\",\n        \"4853f86b\",\n        \"bbd231b\",\n        \"d88ee417\",\n        \"165bc57c\",\n        \"3356f7d\",\n        \"e339215b\",\n        \"e9e72c17\",\n        \"c7cd52c3\",\n        \"d76487f9\",\n        \"32d421c9\",\n        \"836c5237\",\n        \"104f8ce5\",\n        \"e33be333\",\n        \"8e37d275\",\n        \"1f4770e5\",\n        \"af15df23\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"b02cafdb\",\n        \"2a7816d0\",\n        \"92a95930\",\n        \"5689734b\",\n        \"51779df7\",\n        \"f1bbbe40\",\n        \"caca90b3\",\n        \"94f1f97f\",\n        \"c037271b\",\n        \"4853f86b\",\n        \"bbd231b\",\n        \"d88ee417\",\n        \"165bc57c\",\n        \"3356f7d\",\n        \"e339215b\",\n        \"e9e72c17\",\n        \"c7cd52c3\",\n        \"d76487f9\",\n        \"32d421c9\",\n        \"836c5237\",\n        \"104f8ce5\",\n        \"e33be333\",\n        \"8e37d275\",\n        \"1f4770e5\",\n        \"af15df23\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-this-binding-in-event-handlers/en-US.mdx",
    "content": "---\ntitle: Explain the concept of `this` binding in event handlers\n---\n\n## TL;DR\n\nIn JavaScript, the `this` keyword refers to the object that is currently executing the code. In event handlers, `this` typically refers to the element that triggered the event. However, the value of `this` can change depending on how the event handler is defined and called. To ensure `this` refers to the desired object, you can use methods like `bind()`, arrow functions, or assign the context explicitly.\n\n---\n\n## The concept of `this` binding in event handlers\n\n### Understanding `this` in JavaScript\n\nIn JavaScript, the `this` keyword is a reference to the object that is currently executing the code. The value of `this` is determined by how a function is called, not where it is defined. This can lead to different values of `this` in different contexts.\n\n### `this` in event handlers\n\nIn the context of event handlers, `this` usually refers to the DOM element that triggered the event. For example:\n\n```js live\n// Create a button element and append it to the DOM\nconst button = document.createElement('button');\nbutton.id = 'myButton';\ndocument.body.appendChild(button);\n\ndocument.getElementById('myButton').addEventListener('click', function () {\n  console.log(this); // `this` refers to the 'myButton' element\n});\n\nbutton.click(); // Logs the button element\n```\n\nIn this example, `this` inside the event handler refers to the button element that was clicked.\n\n### Changing the value of `this`\n\nThere are several ways to change the value of `this` in event handlers:\n\n#### Using `bind()`\n\nThe `bind()` method creates a new function that, when called, has its `this` keyword set to the provided value:\n\n```js live\n// Create a button element and append it to the DOM\nconst button = document.createElement('button');\nbutton.id = 'myButton';\ndocument.body.appendChild(button);\n\nfunction handleClick() {\n  console.log(this); // Logs the object passed to bind()\n}\n\nconst obj = { name: 'MyObject' };\ndocument\n  .getElementById('myButton')\n  .addEventListener('click', handleClick.bind(obj));\n\nbutton.click(); // Logs obj because handleClick was bound to obj using bind()\n```\n\nIn this example, `this` inside `handleClick` refers to `obj`.\n\n#### Using arrow functions\n\nArrow functions do not have their own `this` context; they inherit `this` from the surrounding lexical context:\n\n```js live\n// Create a button element and append it to the DOM\nconst button = document.createElement('button');\nbutton.id = 'myButton';\ndocument.body.appendChild(button);\n\nconst obj = {\n  name: 'MyObject',\n  handleClick: function () {\n    document.getElementById('myButton').addEventListener('click', () => {\n      console.log(this); // Logs obj\n    });\n  },\n};\n\nobj.handleClick();\nbutton.click(); // This will log obj\n```\n\nIn this example, `this` inside the arrow function refers to `obj`.\n\n#### Assigning the context explicitly\n\nYou can also assign the context explicitly by using a variable:\n\n```js live\n// Create a button element and append it to the DOM\nconst button = document.createElement('button');\nbutton.id = 'myButton';\ndocument.body.appendChild(button);\n\nconst obj = {\n  name: 'MyObject',\n  handleClick: function () {\n    const self = this;\n    document.getElementById('myButton').addEventListener('click', function () {\n      console.log(self); // Logs obj\n    });\n  },\n};\n\nobj.handleClick();\nbutton.click(); // This will log obj\n```\n\nIn this example, `self` is used to capture the value of `this` from the outer function.\n\n## Further reading\n\n- [MDN Web Docs: `this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\n- [MDN Web Docs: `bind()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind)\n- [MDN Web Docs: Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\n"
  },
  {
    "path": "questions/explain-the-concept-of-this-binding-in-event-handlers/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-this-binding-in-event-handlers\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"closure\", \"web-api\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"This Keyword\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-this-binding-in-event-handlers/zh-CN.mdx",
    "content": "---\ntitle: 解释事件处理程序中 `this` 绑定的概念\n---\n\n## TL;DR\n\n在 JavaScript 中，`this` 关键字指的是当前正在执行代码的对象。在事件处理程序中，`this` 通常指的是触发事件的元素。但是，`this` 的值可能会根据事件处理程序的定义和调用方式而改变。为了确保 `this` 指的是期望的对象，你可以使用 `bind()` 方法、箭头函数或显式地分配上下文。\n\n***\n\n## 事件处理程序中 `this` 绑定的概念\n\n### 理解 JavaScript 中的 `this`\n\n在 JavaScript 中，`this` 关键字是对当前正在执行代码的对象的引用。`this` 的值由函数的调用方式决定，而不是定义的位置。这可能导致 `this` 在不同的上下文中具有不同的值。\n\n### 事件处理程序中的 `this`\n\n在事件处理程序的上下文中，`this` 通常指的是触发事件的 DOM 元素。例如：\n\n```js live\n// 创建一个 button 元素并将其附加到 DOM\nconst button = document.createElement('button');\nbutton.id = 'myButton';\ndocument.body.appendChild(button);\n\ndocument.getElementById('myButton').addEventListener('click', function () {\n  console.log(this); // `this` 指的是 'myButton' 元素\n});\n\nbutton.click(); // 记录 button 元素\n```\n\n在这个例子中，事件处理程序中的 `this` 指的是被点击的 button 元素。\n\n### 改变 `this` 的值\n\n有几种方法可以改变事件处理程序中 `this` 的值：\n\n#### 使用 `bind()`\n\n`bind()` 方法创建一个新函数，当调用该函数时，其 `this` 关键字设置为提供的值：\n\n```js live\n// 创建一个 button 元素并将其附加到 DOM\nconst button = document.createElement('button');\nbutton.id = 'myButton';\ndocument.body.appendChild(button);\n\nfunction handleClick() {\n  console.log(this); // 记录传递给 bind() 的对象\n}\n\nconst obj = { name: 'MyObject' };\ndocument\n  .getElementById('myButton')\n  .addEventListener('click', handleClick.bind(obj));\n\nbutton.click(); // 记录 obj，因为 handleClick 使用 bind() 绑定到 obj\n```\n\n在这个例子中，`handleClick` 中的 `this` 指的是 `obj`。\n\n#### 使用箭头函数\n\n箭头函数没有自己的 `this` 上下文；它们从周围的词法上下文中继承 `this`：\n\n```js live\n// 创建一个 button 元素并将其附加到 DOM\nconst button = document.createElement('button');\nbutton.id = 'myButton';\ndocument.body.appendChild(button);\n\nconst obj = {\n  name: 'MyObject',\n  handleClick: function () {\n    document.getElementById('myButton').addEventListener('click', () => {\n      console.log(this); // 记录 obj\n    });\n  },\n};\n\nobj.handleClick();\nbutton.click(); // 这将记录 obj\n```\n\n在这个例子中，箭头函数中的 `this` 指的是 `obj`。\n\n#### 显式地分配上下文\n\n您还可以使用变量显式地分配上下文：\n\n```js live\n// Create a button element and append it to the DOM\nconst button = document.createElement('button');\nbutton.id = 'myButton';\ndocument.body.appendChild(button);\n\nconst obj = {\n  name: 'MyObject',\n  handleClick: function () {\n    const self = this;\n    document.getElementById('myButton').addEventListener('click', function () {\n      console.log(self); // Logs obj\n    });\n  },\n};\n\nobj.handleClick();\nbutton.click(); // This will log obj\n```\n\n在这个例子中，`self` 用于捕获外部函数中 `this` 的值。\n\n## 延伸阅读\n\n* [MDN Web Docs: `this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\n* [MDN Web Docs: `bind()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind)\n* [MDN Web Docs: Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\n"
  },
  {
    "path": "questions/explain-the-concept-of-tree-shaking-in-module-bundling/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"817d7afc\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"38d45c46\",\n        \"2a7816d0\",\n        \"9103bc5\",\n        \"9035d25c\",\n        \"32ea89f8\",\n        \"d2418fbc\",\n        \"9b5019f0\",\n        \"6ef3431\",\n        \"6c633e70\",\n        \"9756851\",\n        \"4acfe5db\",\n        \"dd6813be\",\n        \"f7b6a0a0\",\n        \"90704233\",\n        \"83342f81\",\n        \"8bb2867d\",\n        \"1f4770e5\",\n        \"433806f0\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"38d45c46\",\n        \"2a7816d0\",\n        \"9103bc5\",\n        \"9035d25c\",\n        \"32ea89f8\",\n        \"d2418fbc\",\n        \"9b5019f0\",\n        \"6ef3431\",\n        \"6c633e70\",\n        \"9756851\",\n        \"4acfe5db\",\n        \"dd6813be\",\n        \"f7b6a0a0\",\n        \"90704233\",\n        \"83342f81\",\n        \"8bb2867d\",\n        \"1f4770e5\",\n        \"433806f0\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-tree-shaking-in-module-bundling/en-US.mdx",
    "content": "---\ntitle: Explain the concept of tree shaking in module bundling\n---\n\n## TL;DR\n\nTree shaking is a technique used in module bundling to eliminate dead code, which is code that is never used or executed. This helps to reduce the final bundle size and improve application performance. It works by analyzing the dependency graph of the code and removing any unused exports. Tools like Webpack and Rollup support tree shaking when using ES6 module syntax (`import` and `export`).\n\n---\n\n## The concept of tree shaking in module bundling\n\nTree shaking is a term commonly used in the context of JavaScript module bundlers like Webpack and Rollup. It refers to the process of eliminating dead code from the final bundle, which helps in reducing the bundle size and improving the performance of the application.\n\n### How tree shaking works\n\nTree shaking works by analyzing the dependency graph of the code. It looks at the `import` and `export` statements to determine which parts of the code are actually used and which are not. The unused code, also known as dead code, is then removed from the final bundle.\n\n### Example\n\nConsider the following example:\n\n```js\n// utils.js\nexport function add(a, b) {\n  return a + b;\n}\n\nexport function subtract(a, b) {\n  return a - b;\n}\n\n// main.js\nimport { add } from './utils';\n\nconsole.log(add(2, 3));\n```\n\nIn this example, the `subtract` function is never used in `main.js`. A tree-shaking-enabled bundler will recognize this and exclude the `subtract` function from the final bundle.\n\n### Requirements for tree shaking\n\n1. **ES6 module syntax**: Tree shaking relies on the static structure of ES6 module syntax (`import` and `export`). CommonJS modules (`require` and `module.exports`) are not statically analyzable and thus not suitable for tree shaking.\n2. **Bundler support**: The bundler you are using must support tree shaking. Both Webpack and Rollup have built-in support for tree shaking.\n\n### Tools that support tree shaking\n\n- **Webpack**: Webpack supports tree shaking out of the box when using ES6 modules. You can enable it by setting the `mode` to `production` in your Webpack configuration.\n- **Rollup**: Rollup is designed with tree shaking in mind and provides excellent support for it.\n\n### Benefits of tree shaking\n\n- **Reduced bundle size**: By removing unused code, the final bundle size is reduced, leading to faster load times.\n- **Improved performance**: Smaller bundles mean less code to parse and execute, which can improve the performance of your application.\n\n## Further reading\n\n- [Webpack Tree Shaking](https://webpack.js.org/guides/tree-shaking/)\n- [Rollup Tree Shaking](https://rollupjs.org/guide/en/#tree-shaking)\n- [MDN Web Docs: Import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\n- [MDN Web Docs: Export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\n"
  },
  {
    "path": "questions/explain-the-concept-of-tree-shaking-in-module-bundling/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-concept-of-tree-shaking-in-module-bundling\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Modules\"\n}\n"
  },
  {
    "path": "questions/explain-the-concept-of-tree-shaking-in-module-bundling/zh-CN.mdx",
    "content": "---\ntitle: 解释模块打包中的 Tree Shaking 概念\n---\n\n## TL;DR\n\nTree shaking 是一种用于模块打包的技术，用于消除死代码，即从未被使用或执行的代码。这有助于减小最终的 bundle 大小并提高应用程序的性能。它通过分析代码的依赖关系图并删除任何未使用的导出来实现。Webpack 和 Rollup 等工具在使用 ES6 模块语法（`import` 和 `export`）时支持 Tree shaking。\n\n***\n\n## 模块打包中的 Tree Shaking 概念\n\nTree shaking 是一个常用术语，通常用于 JavaScript 模块打包器，如 Webpack 和 Rollup。它指的是从最终的 bundle 中消除死代码的过程，这有助于减小 bundle 大小并提高应用程序的性能。\n\n### Tree shaking 的工作原理\n\nTree shaking 通过分析代码的依赖关系图来工作。它查看 `import` 和 `export` 语句，以确定代码的哪些部分实际被使用，哪些没有被使用。然后，将未使用的代码（也称为死代码）从最终的 bundle 中删除。\n\n### 示例\n\n考虑以下示例：\n\n```js\n// utils.js\nexport function add(a, b) {\n  return a + b;\n}\n\nexport function subtract(a, b) {\n  return a - b;\n}\n\n// main.js\nimport { add } from './utils';\n\nconsole.log(add(2, 3));\n```\n\n在这个例子中，`subtract` 函数在 `main.js` 中从未使用。支持 Tree Shaking 的打包器会识别这一点，并将 `subtract` 函数从最终的 bundle 中排除。\n\n### Tree shaking 的要求\n\n1. **ES6 模块语法**：Tree shaking 依赖于 ES6 模块语法（`import` 和 `export`）的静态结构。CommonJS 模块（`require` 和 `module.exports`）无法进行静态分析，因此不适合进行 Tree shaking。\n2. **Bundler 支持**：您使用的打包器必须支持 Tree shaking。Webpack 和 Rollup 都内置了对 Tree shaking 的支持。\n\n### 支持 Tree shaking 的工具\n\n* **Webpack**: 使用 ES6 模块时，Webpack 开箱即支持 Tree Shaking。您可以通过在 Webpack 配置中将 `mode` 设置为 `production` 来启用它。\n* **Rollup**: Rollup 在设计时就考虑了 Tree Shaking，并为此提供了出色的支持。\n\n### Tree shaking 的好处\n\n* **减小 bundle 大小**：通过删除未使用的代码，最终的 bundle 大小减小，从而加快加载时间。\n* **提高性能**：更小的 bundle 意味着更少的代码需要解析和执行，这可以提高应用程序的性能。\n\n## 延伸阅读\n\n* [Webpack Tree Shaking](https://webpack.js.org/guides/tree-shaking/)\n* [Rollup Tree Shaking](https://rollupjs.org/guide/en/#tree-shaking)\n* [MDN Web Docs: Import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\n* [MDN Web Docs: Export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\n"
  },
  {
    "path": "questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"7b24d351\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"e2ba4dd1\",\n        \"2a7816d0\",\n        \"de238ccd\",\n        \"28780379\",\n        \"eab2410d\",\n        \"75e7f824\",\n        \"57545be2\",\n        \"530d06c9\",\n        \"a3268b75\",\n        \"27f014d3\",\n        \"8460b666\",\n        \"8d9f8e10\",\n        \"521a97ea\",\n        \"67423e0a\",\n        \"489abc18\",\n        \"1f4770e5\",\n        \"dc2690c5\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"e2ba4dd1\",\n        \"2a7816d0\",\n        \"de238ccd\",\n        \"28780379\",\n        \"eab2410d\",\n        \"75e7f824\",\n        \"57545be2\",\n        \"530d06c9\",\n        \"a3268b75\",\n        \"27f014d3\",\n        \"8460b666\",\n        \"8d9f8e10\",\n        \"521a97ea\",\n        \"67423e0a\",\n        \"489abc18\",\n        \"1f4770e5\",\n        \"dc2690c5\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/en-US.mdx",
    "content": "---\ntitle: Explain the difference between classical inheritance and prototypal inheritance\n---\n\n## TL;DR\n\nClassical inheritance is a model where classes inherit from other classes, typically seen in languages like Java and C++. Prototypal inheritance, used in JavaScript, involves objects inheriting directly from other objects. In classical inheritance, you define a class and create instances from it. In prototypal inheritance, you create an object and use it as a prototype for other objects.\n\n---\n\n## Difference between classical inheritance and prototypal inheritance\n\n### Classical inheritance\n\nClassical inheritance is a pattern used in many object-oriented programming languages like Java, C++, and Python. It involves creating a class hierarchy where classes inherit properties and methods from other classes.\n\n- **Class definition**: You define a class with properties and methods.\n- **Instantiation**: You create instances (objects) of the class.\n- **Inheritance**: A class can inherit from another class, forming a parent-child relationship.\n\nExample in Java:\n\n```java\nclass Animal {\n    void eat() {\n        System.out.println(\"This animal eats food.\");\n    }\n}\n\nclass Dog extends Animal {\n    void bark() {\n        System.out.println(\"The dog barks.\");\n    }\n}\n\npublic class Main {\n    public static void main(String[] args) {\n        Dog dog = new Dog();\n        dog.eat(); // Inherited method\n        dog.bark(); // Own method\n    }\n}\n```\n\n### Prototypal inheritance\n\nPrototypal inheritance is a feature of JavaScript where objects inherit directly from other objects. There are no classes; instead, objects serve as prototypes for other objects.\n\n- **Object creation**: You create an object directly.\n- **Prototype chain**: Objects can inherit properties and methods from other objects through the prototype chain.\n- **Flexibility**: You can dynamically add or modify properties and methods.\n\nExample in JavaScript:\n\n```js live\nconst animal = {\n  eat() {\n    console.log('This animal eats food.');\n  },\n};\n\nconst dog = Object.create(animal);\ndog.bark = function () {\n  console.log('The dog barks.');\n};\n\ndog.eat(); // Inherited method (Output: The animal eats food.)\ndog.bark(); // Own method (Output: The dog barks.)\n```\n\n### Key differences\n\n- **Class-based vs. prototype-based**: Classical inheritance uses classes, while prototypal inheritance uses objects.\n- **Inheritance model**: Classical inheritance forms a class hierarchy, whereas prototypal inheritance forms a prototype chain.\n- **Flexibility**: Prototypal inheritance is more flexible and dynamic, allowing for changes at runtime.\n\n## Further reading\n\n- [MDN Web Docs: Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\n- [JavaScript.info: Prototypal inheritance](https://javascript.info/prototype-inheritance)\n- [MDN Web Docs: Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n"
  },
  {
    "path": "questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-difference-between-classical-inheritance-and-prototypal-inheritance\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Prototypes & Inheritance\"\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-classical-inheritance-and-prototypal-inheritance/zh-CN.mdx",
    "content": "---\ntitle: 解释经典继承和原型继承的区别\n---\n\n## TL;DR\n\n经典继承是一种模型，其中类从其他类继承，通常在 Java 和 C++ 等语言中可见。原型继承（在 JavaScript 中使用）涉及对象直接从其他对象继承。在经典继承中，您定义一个类并从中创建实例。在原型继承中，您创建一个对象并将其用作其他对象的原型。\n\n***\n\n## 经典继承和原型继承的区别\n\n### 经典继承\n\n经典继承是许多面向对象编程语言（如 Java、C++ 和 Python）中使用的一种模式。它涉及创建一个类层次结构，其中类从其他类继承属性和方法。\n\n* **类定义**：您定义一个具有属性和方法的类。\n* **实例化**：您创建类的实例（对象）。\n* **继承**：一个类可以从另一个类继承，形成父子关系。\n\nJava 中的示例：\n\n```java\nclass Animal {\n    void eat() {\n        System.out.println(\"This animal eats food.\");\n    }\n}\n\nclass Dog extends Animal {\n    void bark() {\n        System.out.println(\"The dog barks.\");\n    }\n}\n\npublic class Main {\n    public static void main(String[] args) {\n        Dog dog = new Dog();\n        dog.eat(); // Inherited method\n        dog.bark(); // Own method\n    }\n}\n```\n\n### 原型继承\n\n原型继承是 JavaScript 的一个特性，其中对象直接从其他对象继承。没有类；相反，对象充当其他对象的原型。\n\n* **对象创建**：您直接创建一个对象。\n* **原型链**：对象可以通过原型链从其他对象继承属性和方法。\n* **灵活性**：您可以动态地添加或修改属性和方法。\n\nJavaScript 中的示例：\n\n```js live\nconst animal = {\n  eat() {\n    console.log('This animal eats food.');\n  },\n};\n\nconst dog = Object.create(animal);\ndog.bark = function () {\n  console.log('The dog barks.');\n};\n\ndog.eat(); // Inherited method (Output: The animal eats food.)\ndog.bark(); // Own method (Output: The dog barks.)\n```\n\n### 主要区别\n\n* **基于类的与基于原型的**：经典继承使用类，而原型继承使用对象。\n* **继承模型**：经典继承形成一个类层次结构，而原型继承形成一个原型链。\n* **灵活性**：原型继承更灵活和动态，允许在运行时进行更改。\n\n## 延伸阅读\n\n* [MDN Web Docs: Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\n* [JavaScript.info: Prototypal inheritance](https://javascript.info/prototype-inheritance)\n* [MDN Web Docs: Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n"
  },
  {
    "path": "questions/explain-the-difference-between-documentqueryselector-and-documentgetelementbyid/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"6e8251fa\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"f27a47d\",\n        \"c5f559c\",\n        \"2a7816d0\",\n        \"ccb9f1d1\",\n        \"929b1575\",\n        \"a9c23976\",\n        \"52f691e1\",\n        \"e3d26385\",\n        \"665bc7e6\",\n        \"4b9361ec\",\n        \"67423e0a\",\n        \"7bd8b7fe\",\n        \"1f4770e5\",\n        \"2901f003\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"f27a47d\",\n        \"c5f559c\",\n        \"2a7816d0\",\n        \"ccb9f1d1\",\n        \"929b1575\",\n        \"a9c23976\",\n        \"52f691e1\",\n        \"e3d26385\",\n        \"665bc7e6\",\n        \"4b9361ec\",\n        \"67423e0a\",\n        \"7bd8b7fe\",\n        \"1f4770e5\",\n        \"2901f003\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-documentqueryselector-and-documentgetelementbyid/en-US.mdx",
    "content": "---\ntitle: Explain the difference between `document.querySelector()` and `document.getElementById()`\n---\n\n## TL;DR\n\n`document.querySelector()` and `document.getElementById()` are both methods used to select elements from the DOM, but they have key differences. `document.querySelector()` can select any element using a CSS selector and returns the first match, while `document.getElementById()` selects an element by its ID and returns the element with that specific ID.\n\n```js\n// Using document.querySelector()\nconst element = document.querySelector('.my-class');\n\n// Using document.getElementById()\nconst elementById = document.getElementById('my-id');\n```\n\n---\n\n## Difference between `document.querySelector()` and `document.getElementById()`\n\n### `document.querySelector()`\n\n- Can select elements using any valid CSS selector, including class, ID, tag, attribute, and pseudo-classes\n- Returns the first element that matches the specified selector\n- More versatile but slightly slower due to the flexibility of CSS selectors\n\n```js\n// Select the first element with the class 'my-class'\nconst element = document.querySelector('.my-class');\n\n// Select the first <div> element\nconst divElement = document.querySelector('div');\n\n// Select the first element with the attribute data-role='button'\nconst buttonElement = document.querySelector('[data-role=\"button\"]');\n```\n\n### `document.getElementById()`\n\n- Selects an element by its ID attribute\n- Returns the element with the specified ID\n- Faster and more efficient for selecting elements by ID, but less versatile\n\n```js\n// Select the element with the ID 'my-id'\nconst elementById = document.getElementById('my-id');\n```\n\n### Key differences\n\n- **Selector type**: `document.querySelector()` uses CSS selectors, while `document.getElementById()` uses only the ID attribute.\n- **Return value**: `document.querySelector()` returns the first matching element, whereas `document.getElementById()` returns the element with the specified ID.\n- **Performance**: `document.getElementById()` is generally faster because it directly accesses the element by ID, while `document.querySelector()` has to parse the CSS selector.\n\n## Further reading\n\n- [MDN Web Docs: document.querySelector()](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector)\n- [MDN Web Docs: document.getElementById()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)\n"
  },
  {
    "path": "questions/explain-the-difference-between-documentqueryselector-and-documentgetelementbyid/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-difference-between-documentqueryselector-and-documentgetelementbyid\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"web-api\", \"javascript\", \"html\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"DOM Manipulation & Events\"\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-documentqueryselector-and-documentgetelementbyid/zh-CN.mdx",
    "content": "---\ntitle: 解释 `document.querySelector()` 和 `document.getElementById()` 之间的区别\n---\n\n## TL;DR\n\n`document.querySelector()` 和 `document.getElementById()` 都是用于从 DOM 中选择元素的方法，但它们有关键的区别。`document.querySelector()` 可以使用 CSS 选择器选择任何元素并返回第一个匹配项，而 `document.getElementById()` 通过其 ID 选择一个元素并返回具有该特定 ID 的元素。\n\n```js\n// 使用 document.querySelector()\nconst element = document.querySelector('.my-class');\n\n// 使用 document.getElementById()\nconst elementById = document.getElementById('my-id');\n```\n\n***\n\n## `document.querySelector()` 和 `document.getElementById()` 之间的区别\n\n### `document.querySelector()`\n\n* 可以使用任何有效的 CSS 选择器选择元素，包括类、ID、标签、属性和伪类\n* 返回与指定选择器匹配的第一个元素\n* 更通用，但由于 CSS 选择器的灵活性，速度稍慢\n\n```js\n// 选择具有类 'my-class' 的第一个元素\nconst element = document.querySelector('.my-class');\n\n// 选择第一个 <div> 元素\nconst divElement = document.querySelector('div');\n\n// 选择具有属性 data-role='button' 的第一个元素\nconst buttonElement = document.querySelector('[data-role=\"button\"]');\n```\n\n### `document.getElementById()`\n\n* 通过其 ID 属性选择一个元素\n* 返回具有指定 ID 的元素\n* 通过 ID 选择元素更快更有效，但通用性较差\n\n```js\n// 选择具有 ID 'my-id' 的元素\nconst elementById = document.getElementById('my-id');\n```\n\n### 关键区别\n\n* **选择器类型**：`document.querySelector()` 使用 CSS 选择器，而 `document.getElementById()` 仅使用 ID 属性。\n* **返回值**：`document.querySelector()` 返回第一个匹配的元素，而 `document.getElementById()` 返回具有指定 ID 的元素。\n* **性能**：`document.getElementById()` 通常更快，因为它直接通过 ID 访问元素，而 `document.querySelector()` 必须解析 CSS 选择器。\n\n## 延伸阅读\n\n* [MDN Web Docs: document.querySelector()](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector)\n* [MDN Web Docs: document.getElementById()](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)\n"
  },
  {
    "path": "questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"2ca0663e\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"bb599b30\",\n        \"329a47d5\",\n        \"2a7816d0\",\n        \"45340a21\",\n        \"51e6884c\",\n        \"5eb38f46\",\n        \"f4801713\",\n        \"4a88b64c\",\n        \"748ffe75\",\n        \"df60dafd\",\n        \"6fcc2862\",\n        \"c29a9d39\",\n        \"28216df6\",\n        \"e52f01fd\",\n        \"f4801713\",\n        \"28c7e2f3\",\n        \"748ffe75\",\n        \"c1be8a68\",\n        \"e21a058e\",\n        \"2ac07382\",\n        \"44210bbc\",\n        \"bdd529f9\",\n        \"1f4770e5\",\n        \"edfd734e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"bb599b30\",\n        \"329a47d5\",\n        \"2a7816d0\",\n        \"45340a21\",\n        \"51e6884c\",\n        \"5eb38f46\",\n        \"f4801713\",\n        \"4a88b64c\",\n        \"748ffe75\",\n        \"df60dafd\",\n        \"6fcc2862\",\n        \"c29a9d39\",\n        \"28216df6\",\n        \"e52f01fd\",\n        \"f4801713\",\n        \"28c7e2f3\",\n        \"748ffe75\",\n        \"c1be8a68\",\n        \"e21a058e\",\n        \"2ac07382\",\n        \"44210bbc\",\n        \"bdd529f9\",\n        \"1f4770e5\",\n        \"edfd734e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/en-US.mdx",
    "content": "---\ntitle: Explain the difference between dot notation and bracket notation for accessing object properties\n---\n\n## TL;DR\n\nDot notation and bracket notation are two ways to access properties of an object in JavaScript. Dot notation is more concise and readable but can only be used with valid JavaScript identifiers. Bracket notation is more flexible and can be used with property names that are not valid identifiers, such as those containing spaces or special characters.\n\n```js live\nconst obj = { name: 'Alice', 'favorite color': 'blue' };\n\n// Dot notation\nconsole.log(obj.name); // Alice\n\n// Bracket notation\nconsole.log(obj['favorite color']); // blue\n```\n\n---\n\n## Dot notation vs. bracket notation\n\n### Dot notation\n\nDot notation is the most common and straightforward way to access object properties. It is concise and easy to read but has some limitations.\n\n#### Syntax\n\n```js\nobject.property;\n```\n\n#### Example\n\n```js live\nconst person = {\n  name: 'Alice',\n  age: 30,\n};\n\nconsole.log(person.name); // Alice\nconsole.log(person.age); // 30\n```\n\n#### Limitations\n\n- Property names must be valid JavaScript identifiers (e.g., no spaces, special characters, or starting with a number)\n- Property names cannot be dynamic (i.e., they must be hardcoded)\n\n### Bracket notation\n\nBracket notation is more flexible and can be used in situations where dot notation cannot.\n\n#### Syntax\n\n```js\nobject['property'];\n```\n\n#### Example\n\n```js live\nconst person = {\n  name: 'Alice',\n  'favorite color': 'blue',\n  1: 'one',\n};\n\nconsole.log(person['name']); // Alice\nconsole.log(person['favorite color']); // blue\nconsole.log(person[1]); // one\n```\n\n#### Advantages\n\n- Can access properties with names that are not valid JavaScript identifiers\n- Can use variables or expressions to dynamically determine the property name\n\n#### Example with dynamic property names\n\n```js live\nconst person = {\n  name: 'Alice',\n  age: 30,\n};\n\nconst property = 'name';\nconsole.log(person[property]); // Alice\n```\n\n## Further reading\n\n- [MDN Web Docs: Working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects)\n- [JavaScript.info: Objects](https://javascript.info/object)\n"
  },
  {
    "path": "questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-dot-notation-and-bracket-notation-for-accessing-object-properties/zh-CN.mdx",
    "content": "---\ntitle: 解释使用点符号和方括号符号访问对象属性的区别\n---\n\n## TL;DR\n\n点符号和方括号符号是 JavaScript 中访问对象属性的两种方式。点符号更简洁易读，但只能用于有效的 JavaScript 标识符。方括号符号更灵活，可以用于不是有效标识符的属性名称，例如包含空格或特殊字符的属性名称。\n\n```js live\nconst obj = { name: 'Alice', 'favorite color': 'blue' };\n\n// Dot notation\nconsole.log(obj.name); // Alice\n\n// Bracket notation\nconsole.log(obj['favorite color']); // blue\n```\n\n***\n\n## 点符号 vs. 方括号符号\n\n### 点符号\n\n点符号是访问对象属性最常见和最直接的方式。它简洁易读，但也有一些限制。\n\n#### 语法\n\n```js\nobject.property;\n```\n\n#### 示例\n\n```js live\nconst person = {\n  name: 'Alice',\n  age: 30,\n};\n\nconsole.log(person.name); // Alice\nconsole.log(person.age); // 30\n```\n\n#### 限制\n\n* 属性名称必须是有效的 JavaScript 标识符（例如，没有空格、特殊字符，或不以数字开头）\n* 属性名称不能是动态的（即，它们必须是硬编码的）\n\n### 方括号符号\n\n方括号符号更灵活，可以在点符号无法使用的情况下使用。\n\n#### 语法\n\n```js\nobject['property'];\n```\n\n#### 示例\n\n```js live\nconst person = {\n  name: 'Alice',\n  'favorite color': 'blue',\n  1: 'one',\n};\n\nconsole.log(person['name']); // Alice\nconsole.log(person['favorite color']); // blue\nconsole.log(person[1]); // one\n```\n\n#### 优点\n\n* 可以访问名称不是有效 JavaScript 标识符的属性\n* 可以使用变量或表达式来动态确定属性名称\n\n#### 动态属性名示例\n\n```js live\nconst person = {\n  name: 'Alice',\n  age: 30,\n};\n\nconst property = 'name';\nconsole.log(person[property]); // Alice\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects)\n* [JavaScript.info: Objects](https://javascript.info/object)\n"
  },
  {
    "path": "questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"33b69221\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"889b5b6d\",\n        \"84025ce3\",\n        \"2a7816d0\",\n        \"4e03a4d4\",\n        \"19fcdd6e\",\n        \"fab8870f\",\n        \"3416169\",\n        \"9f817d95\",\n        \"42cf5b55\",\n        \"55b4452d\",\n        \"35bb03fb\",\n        \"e8d9b1b2\",\n        \"5e606b26\",\n        \"1f4770e5\",\n        \"cf31109e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"889b5b6d\",\n        \"84025ce3\",\n        \"2a7816d0\",\n        \"4e03a4d4\",\n        \"19fcdd6e\",\n        \"fab8870f\",\n        \"3416169\",\n        \"9f817d95\",\n        \"42cf5b55\",\n        \"55b4452d\",\n        \"35bb03fb\",\n        \"e8d9b1b2\",\n        \"5e606b26\",\n        \"1f4770e5\",\n        \"cf31109e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/en-US.mdx",
    "content": "---\ntitle: Explain the difference between global scope, function scope, and block scope\n---\n\n## TL;DR\n\nGlobal scope means variables are accessible from anywhere in the code. Function scope means variables are accessible only within the function they are declared in. Block scope means variables are accessible only within the block (e.g., within `{}`) they are declared in.\n\n```js live\nvar globalVar = \"I'm global\"; // Global scope\n\nfunction myFunction() {\n  var functionVar = \"I'm in a function\"; // Function scope\n  if (true) {\n    let blockVar = \"I'm in a block\"; // Block scope\n    console.log(blockVar); // Accessible here\n  }\n  // console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined\n}\n// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined\nmyFunction();\n```\n\n---\n\n## Global scope, function scope, and block scope\n\n### Global scope\n\nVariables declared in the global scope are accessible from anywhere in the code. In a browser environment, these variables become properties of the `window` object.\n\n```js live\nvar globalVar = \"I'm global\";\n\nfunction checkGlobal() {\n  console.log(globalVar); // Accessible here\n}\n\ncheckGlobal(); // Output: \"I'm global\"\nconsole.log(globalVar); // Output: \"I'm global\"\n```\n\n### Function scope\n\nVariables declared within a function are only accessible within that function. This is true for variables declared using `var`, `let`, or `const`.\n\n```js live\nfunction myFunction() {\n  var functionVar = \"I'm in a function\";\n  console.log(functionVar); // Accessible here\n}\n\nmyFunction(); // Output: \"I'm in a function\"\nconsole.log(functionVar); // Uncaught ReferenceError: functionVar is not defined\n```\n\n### Block scope\n\nVariables declared with `let` or `const` within a block (e.g., within `{}`) are only accessible within that block. This is not true for `var`, which is function-scoped.\n\n```js live\nif (true) {\n  let blockVar = \"I'm in a block\";\n  console.log(blockVar); // Accessible here\n}\n// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined\n\nif (true) {\n  var blockVarVar = \"I'm in a block but declared with var\";\n  console.log(blockVarVar); // Accessible here\n}\nconsole.log(blockVarVar); // Output: \"I'm in a block but declared with var\"\n```\n\n## Further reading\n\n- [MDN Web Docs: JavaScript scoping](https://developer.mozilla.org/en-US/docs/Glossary/Scope)\n- [MDN Web Docs: var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)\n- [MDN Web Docs: let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)\n- [MDN Web Docs: const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)\n"
  },
  {
    "path": "questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-difference-between-global-scope-function-scope-and-block-scope\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Closures & Scope\"\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-global-scope-function-scope-and-block-scope/zh-CN.mdx",
    "content": "---\ntitle: 解释全局作用域、函数作用域和块级作用域的区别\n---\n\n## TL;DR\n\n全局作用域意味着变量可以在代码中的任何地方访问。函数作用域意味着变量只能在其声明的函数内部访问。块级作用域意味着变量只能在其声明的块（例如，在 `{}` 内）中访问。\n\n```js live\nvar globalVar = \"I'm global\"; // 全局作用域\n\nfunction myFunction() {\n  var functionVar = \"I'm in a function\"; // 函数作用域\n  if (true) {\n    let blockVar = \"I'm in a block\"; // 块级作用域\n    console.log(blockVar); // 可以在这里访问\n  }\n  // console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined\n}\n// console.log(functionVar); // Uncaught ReferenceError: functionVar is not defined\nmyFunction();\n```\n\n***\n\n## 全局作用域、函数作用域和块级作用域\n\n### 全局作用域\n\n在全局作用域中声明的变量可以在代码中的任何地方访问。在浏览器环境中，这些变量会成为 `window` 对象的属性。\n\n```js live\nvar globalVar = \"I'm global\";\n\nfunction checkGlobal() {\n  console.log(globalVar); // Accessible here\n}\n\ncheckGlobal(); // Output: \"I'm global\"\nconsole.log(globalVar); // Output: \"I'm global\"\n```\n\n### 函数作用域\n\n在函数内声明的变量只能在该函数内部访问。这对于使用 `var`、`let` 或 `const` 声明的变量都是正确的。\n\n```js live\nfunction myFunction() {\n  var functionVar = \"I'm in a function\";\n  console.log(functionVar); // 可以在这里访问\n}\n\nmyFunction(); // Output: \"I'm in a function\"\nconsole.log(functionVar); // Uncaught ReferenceError: functionVar is not defined\n```\n\n### 块级作用域\n\n使用 `let` 或 `const` 在块（例如，在 `{}` 内）中声明的变量只能在该块内访问。这对于 `var` 来说是不成立的，`var` 是函数作用域的。\n\n```js live\nif (true) {\n  let blockVar = \"I'm in a block\";\n  console.log(blockVar); // 可以在这里访问\n}\n// console.log(blockVar); // Uncaught ReferenceError: blockVar is not defined\n\nif (true) {\n  var blockVarVar = \"I'm in a block but declared with var\";\n  console.log(blockVarVar); // 可以在这里访问\n}\nconsole.log(blockVarVar); // Output: \"I'm in a block but declared with var\"\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: JavaScript scoping](https://developer.mozilla.org/en-US/docs/Glossary/Scope)\n* [MDN Web Docs: var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)\n* [MDN Web Docs: let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)\n* [MDN Web Docs: const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)\n"
  },
  {
    "path": "questions/explain-the-difference-between-mutable-and-immutable-objects/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"9ee6afcc\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3ad141aa\",\n        \"3e4d7711\",\n        \"4adbc31c\",\n        \"50c9ec0c\",\n        \"e436fe1a\",\n        \"2a7816d0\",\n        \"1336182d\",\n        \"54735fd5\",\n        \"a106d00e\",\n        \"adc6f0d1\",\n        \"3e4d7711\",\n        \"543475e9\",\n        \"5c0c905a\",\n        \"50c9ec0c\",\n        \"a44e3981\",\n        \"b700e127\",\n        \"a1b7324e\",\n        \"77ee9c94\",\n        \"7d7101d5\",\n        \"757f8077\",\n        \"bf00b02b\",\n        \"d5d39cf6\",\n        \"55ee6e0b\",\n        \"508c5191\",\n        \"920ceebd\",\n        \"fbc0c27e\",\n        \"875f02d0\",\n        \"a7b4e6a2\",\n        \"64e53dbb\",\n        \"dabdde0f\",\n        \"f92176b0\",\n        \"901470d1\",\n        \"39f2d91c\",\n        \"b6caadd5\",\n        \"4d769f00\",\n        \"ebdc442b\",\n        \"9f355b2c\",\n        \"fd79cc03\",\n        \"6a66a886\",\n        \"b4b2d394\",\n        \"cc5e0144\",\n        \"27d4d017\",\n        \"a26bc9f8\",\n        \"ddd815e1\",\n        \"52c17055\",\n        \"3a0811b1\",\n        \"1f4d10ba\",\n        \"1e6219b5\",\n        \"3a5de94a\",\n        \"6ee43b19\",\n        \"1f4770e5\",\n        \"168bd85a\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3ad141aa\",\n        \"3e4d7711\",\n        \"4adbc31c\",\n        \"50c9ec0c\",\n        \"e436fe1a\",\n        \"2a7816d0\",\n        \"1336182d\",\n        \"54735fd5\",\n        \"a106d00e\",\n        \"adc6f0d1\",\n        \"3e4d7711\",\n        \"543475e9\",\n        \"5c0c905a\",\n        \"50c9ec0c\",\n        \"a44e3981\",\n        \"b700e127\",\n        \"a1b7324e\",\n        \"77ee9c94\",\n        \"7d7101d5\",\n        \"757f8077\",\n        \"bf00b02b\",\n        \"d5d39cf6\",\n        \"55ee6e0b\",\n        \"508c5191\",\n        \"920ceebd\",\n        \"fbc0c27e\",\n        \"875f02d0\",\n        \"a7b4e6a2\",\n        \"64e53dbb\",\n        \"dabdde0f\",\n        \"f92176b0\",\n        \"901470d1\",\n        \"39f2d91c\",\n        \"b6caadd5\",\n        \"4d769f00\",\n        \"ebdc442b\",\n        \"9f355b2c\",\n        \"fd79cc03\",\n        \"6a66a886\",\n        \"b4b2d394\",\n        \"cc5e0144\",\n        \"27d4d017\",\n        \"a26bc9f8\",\n        \"ddd815e1\",\n        \"52c17055\",\n        \"3a0811b1\",\n        \"1f4d10ba\",\n        \"1e6219b5\",\n        \"3a5de94a\",\n        \"6ee43b19\",\n        \"1f4770e5\",\n        \"168bd85a\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-mutable-and-immutable-objects/en-US.mdx",
    "content": "---\ntitle: Explain the difference between mutable and immutable objects in JavaScript\n---\n\n## TL;DR\n\n**Mutable objects** allow for modification of properties and values after creation, which is the default behavior for most objects.\n\n```js live\nconst mutableObject = {\n  name: 'John',\n  age: 30,\n};\n\n// Modify the object\nmutableObject.name = 'Jane';\n\n// The object has been modified\nconsole.log(mutableObject); // Output: { name: 'Jane', age: 30 }\n```\n\n**Immutable objects** cannot be directly modified after creation. Its content cannot be changed without creating an entirely new value.\n\n```js live\nconst immutableObject = Object.freeze({\n  name: 'John',\n  age: 30,\n});\n\n// Attempt to modify the object\nimmutableObject.name = 'Jane';\n\n// The object remains unchanged\nconsole.log(immutableObject); // Output: { name: 'John', age: 30 }\n```\n\nThe key difference between mutable and immutable objects is modifiability. Immutable objects cannot be modified after they are created, while mutable objects can be.\n\n---\n\n## Immutability\n\nImmutability is a core principle in functional programming but it has lots to offer to object-oriented programs as well.\n\n### Mutable objects\n\nMutability refers to the ability of an object to have its properties or elements changed after it's created. A mutable object is an object whose state can be modified after it is created. In JavaScript, objects and arrays are mutable by default. They store references to their data in memory. Changing a property or element modifies the original object. Here is an example of a mutable object:\n\n```js live\nconst mutableObject = {\n  name: 'John',\n  age: 30,\n};\n\n// Modify the object\nmutableObject.name = 'Jane';\n\n// The object has been modified\nconsole.log(mutableObject); // Output: { name: 'Jane', age: 30 }\n```\n\n### Immutable objects\n\nAn immutable object is an object whose state cannot be modified after it is created. Here is an example of an immutable object:\n\n```js live\nconst immutableObject = Object.freeze({\n  name: 'John',\n  age: 30,\n});\n\n// Attempt to modify the object\nimmutableObject.name = 'Jane';\n\n// The object remains unchanged\nconsole.log(immutableObject); // Output: { name: 'John', age: 30 }\n```\n\nPrimitive data types like numbers, strings, booleans, `null`, and `undefined` are inherently immutable. Once assigned a value, you cannot directly modify them.\n\n```js live\nlet name = 'Alice';\nname.toUpperCase(); // This won't modify the original name variable\nconsole.log(name); // Still prints \"Alice\"\n\n// To change the value, you need to reassign a new string\nname = name.toUpperCase();\nconsole.log(name); // Now prints \"ALICE\"\n```\n\nSome built-in immutable JavaScript objects are `Math`, `Date` but custom objects are generally mutable.\n\n### `const` vs immutable objects\n\nA common confusion / misunderstanding is that declaring a variable using `const` makes the value immutable, which is not true at all.\n\n`const` prevents reassignment of the variable itself, but does not make the value it holds immutable. This means:\n\n- For primitive values (numbers, strings, booleans), `const` makes the value immutable since primitives are immutable by nature.\n- For non-primitive values like objects and arrays, `const` only prevents reassigning a new object/array to the variable, but the properties/elements of the existing object/array can still be modified.\n\nOn the other hand, an immutable object is an object whose state (properties and values) cannot be modified after it is created. This is achieved by using methods like `Object.freeze()` which makes the object immutable by preventing any changes to its properties.\n\n```js live\n// Using const\nconst person = { name: 'John' };\nperson = { name: 'Jane' }; // Error: Assignment to constant variable\nperson.name = 'Jane'; // Allowed, person.name is now 'Jane'\n\n// Using Object.freeze() to create an immutable object\nconst frozenPerson = Object.freeze({ name: 'John' });\nfrozenPerson.name = 'Jane'; // Fails silently (no error, but no change)\nfrozenPerson = { name: 'Jane' }; // Error: Assignment to constant variable\n```\n\nIn the first example with `const`, reassigning a new object to `person` is not allowed, but modifying the `name` property is permitted. In the second example, `Object.freeze()` makes the `frozenPerson` object immutable, preventing any changes to its properties.\n\nIt's important to note that `Object.freeze()` creates a shallow immutable object. If the object contains nested objects or arrays, those nested data structures are still mutable unless frozen separately.\n\nTherefore, while `const` provides immutability for primitive values, creating truly immutable objects requires using `Object.freeze()` or other immutability techniques like deep freezing or using immutable data structures from libraries like [Immer](https://immerjs.github.io/immer/) or [Immutable.js](https://immutable-js.com/).\n\n## Various ways to implement immutability in plain JavaScript objects\n\nHere are a few ways to add/simulate different forms of immutability in plain JavaScript objects.\n\n### Immutable object properties\n\nBy combining `writable: false` and `configurable: false`, you can essentially create a constant (cannot be changed, redefined or deleted) as an object property, like:\n\n```js live\nconst myObject = {};\nObject.defineProperty(myObject, 'number', {\n  value: 42,\n  writable: false,\n  configurable: false,\n});\nconsole.log(myObject.number); // 42\nmyObject.number = 43;\nconsole.log(myObject.number); // 42\n```\n\n### Preventing extensions on objects\n\nIf you want to prevent an object from having new properties added to it, but otherwise leave the rest of the object's properties alone, call `Object.preventExtensions(...)`:\n\n```js live\nlet myObject = {\n  a: 2,\n};\n\nObject.preventExtensions(myObject);\n\nmyObject.b = 3;\nconsole.log(myObject.b); // undefined\n```\n\nIn non-strict mode, the creation of `b` fails silently. In strict mode, it throws a `TypeError`.\n\n### Sealing an object\n\n`Object.seal()` creates a \"sealed\" object, which means it takes an existing object and essentially calls `Object.preventExtensions()` on it, but also marks all its existing properties as `configurable: false`. Therefore, not only can you not add any more properties, but you also cannot reconfigure or delete any existing properties, though you can still modify their values.\n\n```js live\n// Create an object\nconst person = {\n  name: 'John Doe',\n  age: 30,\n};\n\n// Seal the object\nObject.seal(person);\n\n// Try to add a new property (this will fail silently)\nperson.city = 'New York'; // This has no effect\n\n// Try to delete an existing property (this will fail silently)\ndelete person.age; // This has no effect\n\n// Modify an existing property (this will work)\nperson.age = 35;\n\nconsole.log(person); // Output: { name: 'John Doe', age: 35 }\n\n// Try to re-configure an existing property descriptor (this will fail silently)\nObject.defineProperty(person, 'name', { writable: false }); // Fails silently in non strict mode\n\n// Check if the object is sealed\nconsole.log(Object.isSealed(person)); // Output: true\n```\n\n### Freezing an object\n\n`Object.freeze()` creates a frozen object, which means it takes an existing object and essentially calls `Object.seal()` on it, but it also marks all \"data accessor\" properties as writable:false, so that their values cannot be changed.\n\nThis approach is the highest level of immutability that you can attain for an object itself, as it prevents any changes to the object or to any of its direct properties (though, as mentioned above, the contents of any referenced other objects are unaffected).\n\n```js\nlet immutableObject = Object.freeze({});\n```\n\nFreezing an object does not allow new properties to be added to an object and prevents users from removing or altering the existing properties. `Object.freeze()` preserves the enumerability, configurability, writability and the `prototype` of the object. It returns the passed object and does not create a frozen copy.\n\n`Object.freeze()` makes the object immutable. However, it is not necessarily constant. `Object.freeze` prevents modifications to the object itself and its direct properties, nested objects within the frozen object can still be modified.\n\n```js live\nlet obj = {\n  user: {},\n};\n\nObject.freeze(obj);\nobj.user.name = 'John';\n\nconsole.log(obj.user.name); //Output: 'John'\n```\n\n## What are the pros and cons of immutability?\n\n### Pros\n\n- **Easier change detection**: Object equality can be determined in a performant and easy manner through referential equality. This is useful for comparing object differences in React and Redux.\n- **Less complicated**: Programs with immutable objects are less complicated to think about, since you don't need to worry about how an object may evolve over time.\n- Easy sharing via references: One copy of an object is just as good as another, so you can cache objects or reuse the same object multiple times.\n- **Thread-safe**: Immutable objects can be safely used between threads in a multi-threaded environment since there is no risk of them being modified in other concurrently running threads. In the most cases, JavaScript runs in a single-threaded environment\n- **Less memory needed**: Using libraries like [Immer](https://immerjs.github.io/immer/) and [Immutable.js](https://immutable-js.com/), objects are modified using structural sharing and less memory is needed for having multiple objects with similar structures.\n- **No need for defensive copying**: Defensive copies are no longer necessary when immutable objects are returning from or passed to functions, since there is no possibility an immutable object will be modified by it.\n\n### Cons\n\n- **Complex to create yourself**: Naive implementations of immutable data structures and its operations can result in extremely poor performance because new objects are created each time. It is recommended to use libraries for efficient immutable data structures and operations that leverage on structural sharing.\n- **Potential negative performance**: Allocation (and deallocation) of many small objects rather than modifying existing ones can cause a performance impact. The complexity of either the allocator or the garbage collector usually depends on the number of objects on the heap.\n- **Complexity for cyclic data structures**: Cyclic data structures such as graphs are difficult to implement.\n\n## Further reading\n\n- [Object.defineProperty() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)\n- [Object.freeze() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)\n- [Object.seal() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)\n- [Object.preventExtensions() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions)\n"
  },
  {
    "path": "questions/explain-the-difference-between-mutable-and-immutable-objects/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-difference-between-mutable-and-immutable-objects\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 390,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-mutable-and-immutable-objects/pt-BR.mdx",
    "content": "---\ntitle: Explique a diferença entre objetos mutáveis e imutáveis\n---\n\nA imutabilidade é um princípio central na programação funcional e também tem muito a oferecer para programas orientados para objetos. Um objeto mutável é um objeto cujo estado pode ser modificado depois de criado. Um objeto mutável é um objeto cujo estado pode ser modificado depois de criado.\n\n## O que é um exemplo de um objeto imutável em JavaScript?\n\nEm JavaScript, alguns tipos internos (números, strings) são imutáveis, mas objetos personalizados geralmente são mutáveis.\n\nAlguns objetos JavaScript imutáveis integrados são `Math`, `Date`.\n\nAqui estão algumas maneiras de adicionar/simular imutabilidade em objetos JavaScript simples.\n\n### Propriedades Constante de Objeto\n\nAo combinar `gravável: falso` e `configurável: falso`, você pode criar uma constante (não pode ser alterada, redefinida ou apagada) como uma propriedade do objeto, como:\n\n```js\nlet myObject = {};\nObject.defineProperty(myObject, 'number', {\n  value: 42,\n  writable: false,\n  configurable: false,\n});\nconsole.log(myObject.number); // 42\nmyObject.number = 43;\nconsole.log(myObject.number); // 42\n```\n\n### Evitar Extensões\n\nSe você quiser evitar que um objeto tenha novas propriedades adicionadas, mas deixando o resto das propriedades do objeto sozinhas, chame `Object.preventExtensions(...)`:\n\n```js\nlet myObject = {\n  a: 2,\n};\n\nObject.preventExtensions(myObject);\n\nmyObject.b = 3;\nmyObject.b; // undefined\n```\n\nNo modo não restrito, a criação de `b` falha silenciosamente. No modo estrito, ele lança um `TypeError`.\n\n### Proteção\n\n`Object.seal()` cria um objeto \"selado\", o que significa que recebe um objeto existente e basicamente chama `Object.preventExtensions()` nele, mas também marca todas as suas propriedades existentes como `configurable: false`.\n\nEntão, não só você não pode adicionar mais propriedades, mas você também não pode reconfigurar ou apagar quaisquer propriedades existentes (embora você ainda possa modificar seus valores).\n\n### Travamento\n\n`Object.freeze()` cria um objeto congelado, o que significa que é preciso um objeto existente e basicamente chama `objeto.seal()` nele, mas também marca todas as propriedades do tipo \"acesso a dados\" como writable:false, para que seus valores não possam ser alterados.\n\nEssa abordagem é o maior nível de imutabilidade que você pode alcançar para um objeto em si, pois impede quaisquer mudanças no objeto ou em qualquer uma de suas propriedades diretas (embora, como mencionado acima, o conteúdo de quaisquer outros objetos referenciados não seja afetado).\n\n```js\nlet immutableObject = Object.freeze({});\n```\n\nCongelar um objeto não permite que novas propriedades sejam adicionadas a um objeto e impede que os usuários removam ou modifiquem as propriedades existentes. `Object.freeze()` preserva a enumerabilidade, configurabilidade, gravabilidade e protótipo do objeto. Ele retorna o objeto passado e não cria uma cópia congelada.\n\n## Quais são os prós e os contras da imutabilidade?\n\n### Prós\n\n- Detecção de mudanças mais fácil: A igualdade de objetos pode ser determinada de maneira eficiente e fácil por meio da igualdade referencial. Isso é útil para comparar diferenças de objetos no React e Redux.\n- Menos complicado: Programas com objetos imutáveis são menos complicados de se pensar, já que você não precisa se preocupar sobre como um objeto pode evoluir ao longo do tempo.\n- Compartilhamento fácil por referências: Uma cópia de um objeto é tão boa quanto outra, então você pode armazenar objetos em cache ou reutilizar o mesmo objeto várias vezes.\n- Seguro para threads: Objetos imutáveis podem ser usados com segurança entre threads em um ambiente multi-threaded, já que não há risco de serem modificados em outras threads que estão sendo executadas simultaneamente.\n- Menos necessidade de memória: Usando bibliotecas como [Immer](https://immerjs.github.io/immer/) e [Immutable.js](https://immutable-js.com/), objetos são modificados usando compartilhamento estrutural e menos memória é necessária para ter vários objetos com estruturas semelhantes.\n- Não há necessidade de cópias defensivas: cópias defensivas não são mais necessárias quando objetos imutáveis são retornados ou passados para funções, uma vez que não há possibilidade de um objeto imutável ser modificado por ela.\n\n### Contras\n\n- Complexo para criar por si mesmo: Implementações ingênuas de estruturas de dados imutáveis e suas operações podem resultar em desempenho extremamente pobre porque novos objetos são criados cada vez. É recomendado o uso de bibliotecas para estruturas de dados imutáveis e operações eficientes que utilizam compartilhamento estrutural.\n- Potencial impacto negativo na performance: Alocação (e desalocação) de muitos objetos pequenos ao invés de modificar objetos existentes pode causar um impacto na performance. A complexidade do alocador ou do coletor de lixo geralmente depende do número de objetos no heap.\n- Complexidade para estruturas de dados cíclicas: estruturas de dados cíclicas como grafos são difíceis de construir. Se você tiver dois objetos que não podem ser modificados após a inicialização, como você pode fazer com que eles apontem um para o outro?\n"
  },
  {
    "path": "questions/explain-the-difference-between-mutable-and-immutable-objects/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 中可变对象和不可变对象的区别\n---\n\n## TL;DR\n\n**可变对象** 允许在创建后修改属性和值，这是大多数对象的默认行为。\n\n```js live\nconst mutableObject = {\n  name: 'John',\n  age: 30,\n};\n\n// Modify the object\nmutableObject.name = 'Jane';\n\n// The object has been modified\nconsole.log(mutableObject); // Output: { name: 'Jane', age: 30 }\n```\n\n**不可变对象** 在创建后不能直接修改。在不创建全新值的情况下，其内容无法更改。\n\n```js live\nconst immutableObject = Object.freeze({\n  name: 'John',\n  age: 30,\n});\n\n// Attempt to modify the object\nimmutableObject.name = 'Jane';\n\n// The object remains unchanged\nconsole.log(immutableObject); // Output: { name: 'John', age: 30 }\n```\n\n可变对象和不可变对象之间的主要区别在于可修改性。不可变对象在创建后无法修改，而可变对象可以。\n\n***\n\n## 不可变性\n\n不可变性是函数式编程的核心原则，但它也为面向对象程序提供了很多东西。\n\n### 可变对象\n\n可变性是指对象在创建后可以更改其属性或元素的能力。可变对象是指其状态在创建后可以修改的对象。在 JavaScript 中，对象和数组默认是可变的。它们在内存中存储对其数据的引用。更改属性或元素会修改原始对象。这是一个可变对象的示例：\n\n```js live\nconst mutableObject = {\n  name: 'John',\n  age: 30,\n};\n\n// Modify the object\nmutableObject.name = 'Jane';\n\n// The object has been modified\nconsole.log(mutableObject); // Output: { name: 'Jane', age: 30 }\n```\n\n### 不可变对象\n\n不可变对象是指其状态在创建后无法修改的对象。这是一个不可变对象的示例：\n\n```js live\nconst immutableObject = Object.freeze({\n  name: 'John',\n  age: 30,\n});\n\n// Attempt to modify the object\nimmutableObject.name = 'Jane';\n\n// The object remains unchanged\nconsole.log(immutableObject); // Output: { name: 'John', age: 30 }\n```\n\n原始数据类型（如数字、字符串、布尔值、`null` 和 `undefined`）本质上是不可变的。一旦分配了值，就不能直接修改它们。\n\n```js live\nlet name = 'Alice';\nname.toUpperCase(); // This won't modify the original name variable\nconsole.log(name); // Still prints \"Alice\"\n\n// To change the value, you need to reassign a new string\nname = name.toUpperCase();\nconsole.log(name); // Now prints \"ALICE\"\n```\n\n一些内置的不可变 JavaScript 对象是 `Math`、`Date`，但自定义对象通常是可变的。\n\n### `const` vs 不可变对象\n\n一个常见的混淆/误解是使用 `const` 声明变量会使该值不可变，这根本不是真的。\n\n`const` 阻止重新分配变量本身，但不会使其持有的值不可变。这意味着：\n\n* 对于原始值（数字、字符串、布尔值），`const` 使值不可变，因为原始值本质上是不可变的。\n* 对于非原始值，如对象和数组，`const` 仅阻止将新的对象/数组重新分配给变量，但现有对象/数组的属性/元素仍然可以被修改。\n\n另一方面，不可变对象是指在创建后其状态（属性和值）无法修改的对象。这可以通过使用 `Object.freeze()` 等方法来实现，该方法通过阻止对其属性的任何更改来使对象不可变。\n\n```js live\n// 使用 const\nconst person = { name: 'John' };\nperson = { name: 'Jane' }; // 错误：赋值给常量变量\nperson.name = 'Jane'; // 允许，person.name 现在是 'Jane'\n\n// 使用 Object.freeze() 创建一个不可变对象\nconst frozenPerson = Object.freeze({ name: 'John' });\nfrozenPerson.name = 'Jane'; // 静默失败（没有错误，但没有变化）\nfrozenPerson = { name: 'Jane' }; // 错误：赋值给常量变量\n```\n\n在第一个使用 `const` 的例子中，不允许将新对象重新分配给 `person`，但允许修改 `name` 属性。在第二个例子中，`Object.freeze()` 使 `frozenPerson` 对象不可变，从而阻止对其属性的任何更改。\n\n需要注意的是，`Object.freeze()` 创建的是一个浅不可变对象。如果对象包含嵌套对象或数组，除非单独冻结，否则这些嵌套数据结构仍然是可变的。\n\n因此，虽然 `const` 为原始值提供了不可变性，但创建真正不可变的对象需要使用 `Object.freeze()` 或其他不可变性技术，如深度冻结或使用来自 [Immer](https://immerjs.github.io/immer/) 或 [Immutable.js](https://immutable-js.com/) 等库的不可变数据结构。\n\n## 在普通 JavaScript 对象中实现不可变的各种方法\n\n以下是在普通 JavaScript 对象中添加/模拟不同形式的不可变性的几种方法。\n\n### 不可变对象属性\n\n通过结合 `writable: false` 和 `configurable: false`，您本质上可以创建一个常量（不能更改、重新定义或删除）作为对象属性，例如：\n\n```js live\nconst myObject = {};\nObject.defineProperty(myObject, 'number', {\n  value: 42,\n  writable: false,\n  configurable: false,\n});\nconsole.log(myObject.number); // 42\nmyObject.number = 43;\nconsole.log(myObject.number); // 42\n```\n\n### 阻止对象扩展\n\n如果您想阻止向对象添加新属性，但保持对象的其余属性不变，请调用 `Object.preventExtensions(...)`：\n\n```js live\nlet myObject = {\n  a: 2,\n};\n\nObject.preventExtensions(myObject);\n\nmyObject.b = 3;\nconsole.log(myObject.b); // undefined\n```\n\n在非严格模式下，创建 `b` 会静默失败。在严格模式下，它会抛出 `TypeError`。\n\n### 密封一个对象\n\n`Object.seal()` 创建一个“密封”对象，这意味着它会获取一个现有对象，并基本上在其上调用 `Object.preventExtensions()`，但也会将所有现有属性标记为 `configurable: false`。因此，您不仅不能添加更多属性，而且也不能重新配置或删除任何现有属性，尽管您仍然可以修改它们的值。\n\n```js live\n// 创建一个对象\nconst person = {\n  name: 'John Doe',\n  age: 30,\n};\n\n// 密封对象\nObject.seal(person);\n\n// 尝试添加新属性（这将静默失败）\nperson.city = 'New York'; // 这没有效果\n\n// 尝试删除现有属性（这将静默失败）\ndelete person.age; // 这没有效果\n\n// 修改现有属性（这将起作用）\nperson.age = 35;\n\nconsole.log(person); // 输出：{ name: 'John Doe', age: 35 }\n\n// 尝试重新配置现有属性描述符（这将静默失败）\nObject.defineProperty(person, 'name', { writable: false }); // 在非严格模式下静默失败\n\n// 检查对象是否被密封\nconsole.log(Object.isSealed(person)); // 输出：true\n```\n\n### 冻结一个对象\n\n`Object.freeze()` 创建一个冻结对象，这意味着它会获取一个现有对象，并基本上在其上调用 `Object.seal()`，但它也会将所有“数据访问器”属性标记为 writable:false，以便它们的值不能被更改。\n\n这种方法是您可以为对象本身达到的最高级别的不可变性，因为它阻止了对对象或其任何直接属性的任何更改（尽管，如上所述，任何引用的其他对象的内容不受影响）。\n\n```js\nlet immutableObject = Object.freeze({});\n```\n\n冻结对象不允许向对象添加新属性，并阻止用户删除或更改现有属性。`Object.freeze()` 保留了对象的枚举性、可配置性、可写性和 `prototype`。它返回传递的对象，并且不会创建冻结副本。\n\n`Object.freeze()` 使对象不可变。但是，它不一定是常量。`Object.freeze` 阻止对对象本身及其直接属性的修改，冻结对象内的嵌套对象仍然可以被修改。\n\n```js live\nlet obj = {\n  user: {},\n};\n\nObject.freeze(obj);\nobj.user.name = 'John';\n\nconsole.log(obj.user.name); //Output: 'John'\n```\n\n## 不可变性的优缺点是什么？\n\n### 优点\n\n* **更容易进行更改检测**：可以通过引用相等性以高性能和简单的方式确定对象相等性。这对于比较 React 和 Redux 中的对象差异很有用。\n* **更简单**：使用不可变对象的程序更易于思考，因为您无需担心对象可能随时间演变的方式。\n* 通过引用轻松共享：一个对象的副本与另一个对象一样好，因此您可以缓存对象或多次重用同一对象。\n* **线程安全**：不可变对象可以在多线程环境中的线程之间安全使用，因为它们不会有在其他并发运行的线程中被修改的风险。在大多数情况下，JavaScript 在单线程环境中运行\n* **减少内存需求**：使用 [Immer](https://immerjs.github.io/immer/) 和 [Immutable.js](https://immutable-js.com/) 等库，使用结构共享修改对象，并且对于具有相似结构的多个对象，所需的内存更少。\n* **无需防御性复制**：当从不可变对象返回或传递给函数时，不再需要防御性副本，因为不可变对象不可能被它修改。\n\n### 缺点\n\n* **难以自行创建**：不可变数据结构及其操作的朴素实现可能会导致性能极差，因为每次都会创建新对象。建议使用库来实现高效的不可变数据结构和利用结构共享的操作。\n* **潜在的负面性能**：分配（和释放）许多小对象而不是修改现有对象可能会导致性能影响。分配器或垃圾收集器的复杂性通常取决于堆上的对象数量。\n* **循环数据结构的复杂性**：循环数据结构（如图形）难以实现。\n\n## 延伸阅读\n\n* [Object.defineProperty() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)\n* [Object.freeze() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)\n* [Object.seal() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)\n* [Object.preventExtensions() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions)\n"
  },
  {
    "path": "questions/explain-the-difference-between-shallow-copy-and-deep-copy/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"b464b6ed\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"2da4a603\",\n        \"2a097296\",\n        \"2a7816d0\",\n        \"81bf7792\",\n        \"7cbd2fa0\",\n        \"8a84aed0\",\n        \"748ffe75\",\n        \"2f269887\",\n        \"13d64888\",\n        \"4ee204dd\",\n        \"77f10b13\",\n        \"748ffe75\",\n        \"b3f5e718\",\n        \"90c7e71b\",\n        \"63480df5\",\n        \"ce2b509d\",\n        \"f3d7af6c\",\n        \"843ec0f0\",\n        \"b6be0b83\",\n        \"1f4770e5\",\n        \"9c662245\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"2da4a603\",\n        \"2a097296\",\n        \"2a7816d0\",\n        \"81bf7792\",\n        \"7cbd2fa0\",\n        \"8a84aed0\",\n        \"748ffe75\",\n        \"2f269887\",\n        \"13d64888\",\n        \"4ee204dd\",\n        \"77f10b13\",\n        \"748ffe75\",\n        \"b3f5e718\",\n        \"90c7e71b\",\n        \"63480df5\",\n        \"ce2b509d\",\n        \"f3d7af6c\",\n        \"843ec0f0\",\n        \"b6be0b83\",\n        \"1f4770e5\",\n        \"9c662245\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-shallow-copy-and-deep-copy/en-US.mdx",
    "content": "---\ntitle: Explain the difference between shallow copy and deep copy\n---\n\n## TL;DR\n\nA shallow copy duplicates the top-level properties of an object, but nested objects are still referenced. A deep copy duplicates all levels of an object, creating entirely new instances of nested objects. For example, using `Object.assign()` creates a shallow copy, while using libraries like `Lodash` or `structuredClone()` in modern JavaScript can create deep copies.\n\n```js live\n// Shallow copy example\nlet obj1 = { a: 1, b: { c: 2 } };\nlet shallowCopy = Object.assign({}, obj1);\nshallowCopy.b.c = 3;\nconsole.log(shallowCopy.b.c); // Output: 3\nconsole.log(obj1.b.c); // Output: 3 (original nested object changed too!)\n\n// Deep copy example\nlet obj2 = { a: 1, b: { c: 2 } };\nlet deepCopy = JSON.parse(JSON.stringify(obj2));\ndeepCopy.b.c = 4;\nconsole.log(deepCopy.b.c); // Output: 4\nconsole.log(obj2.b.c); // Output: 2 (original nested object remains unchanged)\n```\n\n---\n\n## Difference between shallow copy and deep copy\n\n### Shallow copy\n\nA shallow copy creates a new object and copies the values of the original object's top-level properties into the new object. However, if any of these properties are references to other objects, only the reference is copied, not the actual object. This means that changes to nested objects in the copied object will affect the original object.\n\n#### Example\n\n```js live\nlet obj1 = { a: 1, b: { c: 2 } };\nlet shallowCopy = Object.assign({}, obj1);\nshallowCopy.b.c = 3;\nconsole.log(shallowCopy.b.c); // Output: 3\nconsole.log(obj1.b.c); // Output: 3 (original nested object changed too!)\n```\n\nIn this example, `shallowCopy` is a shallow copy of `obj1`. Changing `shallowCopy.b.c` also changes `obj1.b.c` because `b` is a reference to the same object in both `obj1` and `shallowCopy`.\n\n### Deep copy\n\nA deep copy creates a new object and recursively copies all properties and nested objects from the original object. This means that the new object is completely independent of the original object, and changes to nested objects in the copied object do not affect the original object.\n\n#### Example\n\n```js live\nlet obj1 = { a: 1, b: { c: 2 } };\nlet deepCopy = JSON.parse(JSON.stringify(obj1));\ndeepCopy.b.c = 4;\nconsole.log(deepCopy.b.c); // Output: 4\nconsole.log(obj1.b.c); // Output: 2 (original nested object remains unchanged)\n```\n\nIn this example, `deepCopy` is a deep copy of `obj1`. Changing `deepCopy.b.c` does not affect `obj1.b.c` because `b` is a completely new object in `deepCopy`.\n\n### Methods to create shallow and deep copies\n\n#### Shallow copy methods\n\n- `Object.assign()`\n- Spread operator (`...`)\n\n#### Deep copy methods\n\n- `JSON.parse(JSON.stringify())`\n- `structuredClone()` (modern JavaScript)\n- Libraries like `Lodash` (`_.cloneDeep`)\n\n## Further reading\n\n- [MDN Web Docs: Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)\n- [MDN Web Docs: JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)\n- [MDN Web Docs: structuredClone()](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone)\n- [Lodash Documentation: \\_.cloneDeep](https://lodash.com/docs/4.17.15#cloneDeep)\n"
  },
  {
    "path": "questions/explain-the-difference-between-shallow-copy-and-deep-copy/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-difference-between-shallow-copy-and-deep-copy\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-shallow-copy-and-deep-copy/zh-CN.mdx",
    "content": "---\ntitle: 解释浅拷贝和深拷贝的区别\n---\n\n## TL;DR\n\n浅拷贝复制对象的顶层属性，但嵌套对象仍然被引用。深拷贝复制对象的所有层级，创建嵌套对象的全新实例。例如，使用 `Object.assign()` 创建浅拷贝，而使用像 `Lodash` 或现代 JavaScript 中的 `structuredClone()` 这样的库可以创建深拷贝。\n\n```js live\n// Shallow copy example\nlet obj1 = { a: 1, b: { c: 2 } };\nlet shallowCopy = Object.assign({}, obj1);\nshallowCopy.b.c = 3;\nconsole.log(shallowCopy.b.c); // Output: 3\nconsole.log(obj1.b.c); // Output: 3 (original nested object changed too!)\n\n// Deep copy example\nlet obj2 = { a: 1, b: { c: 2 } };\nlet deepCopy = JSON.parse(JSON.stringify(obj2));\ndeepCopy.b.c = 4;\nconsole.log(deepCopy.b.c); // Output: 4\nconsole.log(obj2.b.c); // Output: 2 (original nested object remains unchanged)\n```\n\n***\n\n## 浅拷贝和深拷贝的区别\n\n### 浅拷贝\n\n浅拷贝创建一个新对象，并将原始对象的顶层属性的值复制到新对象中。但是，如果这些属性中的任何一个是其他对象的引用，则仅复制引用，而不是实际对象。这意味着对复制对象中嵌套对象的更改将影响原始对象。\n\n#### 示例\n\n```js live\nlet obj1 = { a: 1, b: { c: 2 } };\nlet shallowCopy = Object.assign({}, obj1);\nshallowCopy.b.c = 3;\nconsole.log(shallowCopy.b.c); // Output: 3\nconsole.log(obj1.b.c); // Output: 3 (original nested object changed too!)\n```\n\n在此示例中，`shallowCopy` 是 `obj1` 的浅拷贝。更改 `shallowCopy.b.c` 也会更改 `obj1.b.c`，因为 `b` 是 `obj1` 和 `shallowCopy` 中对同一对象的引用。\n\n### 深拷贝\n\n深拷贝创建一个新对象，并递归地复制原始对象的所有属性和嵌套对象。这意味着新对象完全独立于原始对象，并且对复制对象中嵌套对象的更改不会影响原始对象。\n\n#### 示例\n\n```js live\nlet obj1 = { a: 1, b: { c: 2 } };\nlet deepCopy = JSON.parse(JSON.stringify(obj1));\ndeepCopy.b.c = 4;\nconsole.log(deepCopy.b.c); // Output: 4\nconsole.log(obj1.b.c); // Output: 2 (original nested object remains unchanged)\n```\n\n在此示例中，`deepCopy` 是 `obj1` 的深拷贝。更改 `deepCopy.b.c` 不会影响 `obj1.b.c`，因为 `b` 在 `deepCopy` 中是一个全新的对象。\n\n### 创建浅拷贝和深拷贝的方法\n\n#### 浅拷贝方法\n\n* `Object.assign()`\n* 展开运算符 (`...`)\n\n#### 深拷贝方法\n\n* `JSON.parse(JSON.stringify())`\n* `structuredClone()` (现代 JavaScript)\n* 像 `Lodash` 这样的库 (`_.cloneDeep`)\n\n## 延伸阅读\n\n* [MDN Web Docs: Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)\n* [MDN Web Docs: JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)\n* [MDN Web Docs: structuredClone()](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone)\n* [Lodash Documentation: \\_.cloneDeep](https://lodash.com/docs/4.17.15#cloneDeep)\n"
  },
  {
    "path": "questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"bda19b5e\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"b45397\",\n        \"b96222cb\",\n        \"ea9c8d09\",\n        \"d903fbfe\",\n        \"2a7816d0\",\n        \"88ad93b4\",\n        \"d31824f0\",\n        \"89091bf\",\n        \"83bc36aa\",\n        \"1cebd99d\",\n        \"c1b47d4b\",\n        \"4e3a3fa6\",\n        \"e742614c\",\n        \"10cfe95e\",\n        \"3fe22110\",\n        \"fc64aed8\",\n        \"22d459a1\",\n        \"6d790401\",\n        \"c8718ad4\",\n        \"96c3e970\",\n        \"5ba185f5\",\n        \"f4ae8c6b\",\n        \"f978b707\",\n        \"62fab12e\",\n        \"1975533b\",\n        \"db7ed482\",\n        \"1f4770e5\",\n        \"2f2273a2\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"b45397\",\n        \"b96222cb\",\n        \"ea9c8d09\",\n        \"d903fbfe\",\n        \"2a7816d0\",\n        \"88ad93b4\",\n        \"d31824f0\",\n        \"89091bf\",\n        \"83bc36aa\",\n        \"1cebd99d\",\n        \"c1b47d4b\",\n        \"4e3a3fa6\",\n        \"e742614c\",\n        \"10cfe95e\",\n        \"3fe22110\",\n        \"fc64aed8\",\n        \"22d459a1\",\n        \"6d790401\",\n        \"c8718ad4\",\n        \"96c3e970\",\n        \"5ba185f5\",\n        \"f4ae8c6b\",\n        \"f978b707\",\n        \"62fab12e\",\n        \"1975533b\",\n        \"db7ed482\",\n        \"1f4770e5\",\n        \"2f2273a2\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-synchronous-and-asynchronous-functions/en-US.mdx",
    "content": "---\ntitle: Explain the difference between synchronous and asynchronous functions in JavaScript\n---\n\n## TL;DR\n\nSynchronous functions are blocking while asynchronous functions are not. In synchronous functions, statements complete before the next statement is run. As a result, programs containing only synchronous code are evaluated exactly in order of the statements. The execution of the program is paused if one of the statements take a very long time.\n\n```js live\nfunction sum(a, b) {\n  console.log('Inside sum function');\n  return a + b;\n}\n\nconst result = sum(2, 3); // The program waits for sum() to complete before assigning the result\nconsole.log('Result: ', result); // Output: 5\n```\n\nAsynchronous functions usually accept a callback as a parameter and execution continue on to the next line immediately after the asynchronous function is invoked. The callback is only invoked when the asynchronous operation is complete and the call stack is empty. Heavy duty operations such as loading data from a web server or querying a database should be done asynchronously so that the main thread can continue executing other operations instead of blocking until that long operation to complete (in the case of browsers, the UI will freeze).\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John', age: 30 };\n    callback(data); // Calling the callback function with data\n  }, 2000); // Simulating a 2-second delay\n}\n\nconsole.log('Fetching data...');\n\nfetchData((data) => {\n  console.log(data); // Output: { name: 'John', age: 30 } (after 2 seconds)\n});\n\nconsole.log('Call made to fetch data'); // This will print before the data is fetched\n```\n\n---\n\n## Synchronous vs asynchronous functions\n\nIn JavaScript, the concepts of synchronous and asynchronous functions are fundamental to understanding how code execution is managed, particularly in the context of handling operations like I/O tasks, API calls, and other time-consuming processes.\n\n## Synchronous functions\n\nSynchronous functions execute in a sequential order, one after the other. Each operation must wait for the previous one to complete before moving on to the next.\n\n- Synchronous code is blocking, meaning the program execution halts until the current operation finishes.\n- It follows a strict sequence, executing instructions line by line.\n- Synchronous functions are easier to understand and debug since the flow is predictable.\n\n### Synchronous function examples\n\n1. **Reading files synchronously**: When reading a file from the file system using the synchronous readFileSync method from the fs module in Node.js, the program execution is blocked until the entire file is read. This can cause performance issues, especially for large files or when reading multiple files sequentially\n\n   ```js\n   const fs = require('fs');\n   const data = fs.readFileSync('large-file.txt', 'utf8');\n   console.log(data); // Execution is blocked until the file is read.\n   console.log('End of the program');\n   ```\n\n2. **Looping over large datasets**: Iterating over a large array or dataset synchronously can freeze the user interface or browser tab until the operation completes, leading to an unresponsive application.\n\n   ```js live\n   const largeArray = new Array(1_000_000).fill(0);\n   // Blocks the main thread until the million operations are completed.\n   const result = largeArray.map((num) => num * 2);\n   console.log(result);\n   ```\n\n## Asynchronous functions\n\nAsynchronous functions do not block the execution of the program. They allow other operations to continue while waiting for a response or completion of a time-consuming task.\n\n    - Asynchronous code is non-blocking, allowing the program to keep running without waiting for a specific operation to finish.\n    - It enables concurrent execution, improving performance and responsiveness.\n    - Asynchronous functions are commonly used for tasks like network requests, file I/O, and timers.\n\n### Asynchronous function examples\n\n1. **Network requests**: Making network requests, such as fetching data from an API or sending data to a server, is typically done asynchronously. This allows the application to remain responsive while waiting for the response, preventing the user interface from freezing\n\n   ```js live\n   console.log('Start of the program'); // This will be printed first as program starts here\n\n   fetch('https://jsonplaceholder.typicode.com/todos/1')\n     .then((response) => response.json())\n     .then((data) => {\n       console.log(data);\n       /** Process the data without blocking the main thread\n        *  and printed at the end if fetch call succeeds\n        */\n     })\n     .catch((error) => console.error(error));\n\n   console.log('End of program'); // This will be printed before the fetch callback\n   ```\n\n2. **User input and events**: Handling user input events, such as clicks, key presses, or mouse movements, is inherently asynchronous. The application needs to respond to these events without blocking the main thread, ensuring a smooth user experience.\n\n   ```js\n   const button = document.getElementById('myButton');\n   button.addEventListener('click', () => {\n     // Handle the click event asynchronously\n     console.log('Button clicked');\n   });\n   ```\n\n3. **Timers and Animations**: Timers (`setTimeout()`, `setInterval()`) and animations (e.g., `requestAnimationFrame()`) are asynchronous operations that allow the application to schedule tasks or update animations without blocking the main thread.\n\n   ```js live\n   setTimeout(() => {\n     console.log('This message is delayed by 2 seconds');\n   }, 2000);\n\n   setInterval(() => {\n     console.log('Current time:', new Date().toLocaleString());\n   }, 2000); // Interval runs every 2 seconds\n   ```\n\nBy using asynchronous functions and operations, JavaScript can handle time-consuming tasks without freezing the user interface or blocking the main thread.\n\nIt is important to note that **`async` functions do not run on a different thread**. They still run on the main thread. However, it is possible to achieve parallelism in JavaScript by using [Web workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)\n\n## Achieving parallelism in JavaScript via web workers\n\nWeb workers allow you to spawn separate background threads that can perform CPU-intensive tasks in parallel with the main thread. These worker threads can communicate with the main thread via message passing, but they do not have direct access to the DOM or other browser APIs.\n\n```js\n// main.js\nconst worker = new Worker('worker.js');\n\nworker.onmessage = function (event) {\n  console.log('Result from worker:', event.data);\n};\n\nworker.postMessage('Start computation');\n```\n\n```js\n// worker.js\nself.onmessage = function (event) {\n  const result = performHeavyComputation();\n  self.postMessage(result);\n};\n\nfunction performHeavyComputation() {\n  // CPU-intensive computation\n  return 'Computation result';\n}\n```\n\nIn this example, the main thread creates a new web worker and sends it a message to start a computation. The worker performs the heavy computation in parallel with the main thread and sends the result back via `postMessage()`.\n\n## Event loop\n\nThe async nature of JavaScript is powered by a JavaScript engine's [event loop](/questions/quiz/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue) allowing concurrent operations even though JavaScript is single-threaded. It's an important concept to understand so we highly recommend going through that topic as well.\n\n## Further reading\n\n- [Asynchronous JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous)\n- [The Basics: synchronous and asynchronous JavaScript](https://www.linkedin.com/pulse/basics-synchronous-asynchronous-javascript-abdulkabir-okeowo)\n- [Synchronous and asynchronous programming in JavaScript](https://code.pieces.app/blog/synchronous-and-asynchronous-programming-in-javascript)\n- [Web Workers API - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)\n- [An overview of web workers - Web.dev](https://web.dev/learn/performance/web-worker-overview)\n"
  },
  {
    "path": "questions/explain-the-difference-between-synchronous-and-asynchronous-functions/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-difference-between-synchronous-and-asynchronous-functions\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"async\", \"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 250,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-synchronous-and-asynchronous-functions/pt-BR.mdx",
    "content": "---\ntitle: Explique a diferença entre funções síncronas e assíncronas\n---\n\nFunções síncronas são bloqueadoras enquanto funções assíncronas não são. Em funções síncronas, as instruções são concluídas antes que a próxima instrução seja executada. Nesse caso, o programa é avaliado exatamente na ordem das instruções, e a execução do programa é pausada se uma das instruções demorar muito tempo.\n\nFunções assíncronas geralmente aceitam uma função de retorno de chamada como parâmetro e a execução continua na próxima linha imediatamente após a invocação da função assíncrona. A callback só é invocada quando a operação assíncrona é concluída e a pilha de chamadas está vazia. Operações pesadas, como carregar dados de um servidor web ou consultar um banco de dados, devem ser feitas de forma assíncrona para que a thread principal possa continuar executando outras operações em vez de bloquear até que aquela operação longa seja concluída (no caso dos navegadores, a interface do usuário ficará congelada).\n"
  },
  {
    "path": "questions/explain-the-difference-between-synchronous-and-asynchronous-functions/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 中同步和异步函数的区别\n---\n\n## 总结\n\n同步函数是阻塞的，而异步函数则不是。在同步函数中，语句在运行下一条语句之前完成。因此，仅包含同步代码的程序将完全按照语句的顺序进行评估。如果其中一条语句花费很长时间，程序的执行将暂停。\n\n```js live\nfunction sum(a, b) {\n  console.log('Inside sum function');\n  return a + b;\n}\n\nconst result = sum(2, 3); // The program waits for sum() to complete before assigning the result\nconsole.log('Result: ', result); // Output: 5\n```\n\n异步函数通常接受回调作为参数，并且在调用异步函数后立即继续执行到下一行。仅当异步操作完成且调用堆栈为空时，才会调用回调。诸如从 Web 服务器加载数据或查询数据库之类的繁重操作应异步完成，以便主线程可以继续执行其他操作，而不是阻塞直到该长时间操作完成（对于浏览器，UI 将冻结）。\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John', age: 30 };\n    callback(data); // Calling the callback function with data\n  }, 2000); // Simulating a 2-second delay\n}\n\nconsole.log('Fetching data...');\n\nfetchData((data) => {\n  console.log(data); // Output: { name: 'John', age: 30 } (after 2 seconds)\n});\n\nconsole.log('Call made to fetch data'); // This will print before the data is fetched\n```\n\n***\n\n## 同步函数与异步函数\n\n在 JavaScript 中，同步和异步函数的概念是理解代码执行方式的基础，尤其是在处理 I/O 任务、API 调用和其他耗时进程的上下文中。\n\n## 同步函数\n\n同步函数按顺序执行，一个接一个。每个操作都必须等待前一个操作完成才能继续进行。\n\n* 同步代码是阻塞的，这意味着程序执行会暂停，直到当前操作完成。\n* 它遵循严格的顺序，逐行执行指令。\n* 同步函数更容易理解和调试，因为流程是可预测的。\n\n### 同步函数示例\n\n1. **同步读取文件**：使用 Node.js 中 fs 模块的同步 readFileSync 方法从文件系统读取文件时，程序执行将被阻塞，直到整个文件被读取。这可能会导致性能问题，尤其是在处理大文件或顺序读取多个文件时\n\n   ```js\n   const fs = require('fs');\n   const data = fs.readFileSync('large-file.txt', 'utf8');\n   console.log(data); // Execution is blocked until the file is read.\n   console.log('End of the program');\n   ```\n\n2. **循环遍历大型数据集**：同步迭代大型数组或数据集可能会冻结用户界面或浏览器选项卡，直到操作完成，导致应用程序无响应。\n\n   ```js live\n   const largeArray = new Array(1_000_000).fill(0);\n   // Blocks the main thread until the million operations are completed.\n   const result = largeArray.map((num) => num * 2);\n   console.log(result);\n   ```\n\n## 异步函数\n\n异步函数不会阻塞程序的执行。它们允许其他操作继续进行，同时等待响应或完成耗时的任务。\n\n* 异步代码是非阻塞的，允许程序继续运行，而无需等待特定操作完成。\n* 它支持并发执行，从而提高性能和响应能力。\n* 异步函数通常用于网络请求、文件 I/O 和计时器等任务。\n\n### 异步函数示例\n\n1. **网络请求**：发出网络请求（例如从 API 获取数据或向服务器发送数据）通常是异步完成的。这使得应用程序在等待响应时保持响应，从而防止用户界面冻结\n\n   ```js live\n   console.log('Start of the program'); // This will be printed first as program starts here\n\n   fetch('https://jsonplaceholder.typicode.com/todos/1')\n     .then((response) => response.json())\n     .then((data) => {\n       console.log(data);\n       /** Process the data without blocking the main thread\n        *  and printed at the end if fetch call succeeds\n        */\n     })\n     .catch((error) => console.error(error));\n\n   console.log('End of program'); // This will be printed before the fetch callback\n   ```\n\n2. **用户输入和事件**：处理用户输入事件（例如单击、按键或鼠标移动）本质上是异步的。应用程序需要响应这些事件，而不会阻塞主线程，从而确保流畅的用户体验。\n\n   ```js\n   const button = document.getElementById('myButton');\n   button.addEventListener('click', () => {\n     // Handle the click event asynchronously\n     console.log('Button clicked');\n   });\n   ```\n\n3. **计时器和动画**：计时器（`setTimeout()`、`setInterval()`）和动画（例如，`requestAnimationFrame()`）是异步操作，允许应用程序调度任务或更新动画，而不会阻塞主线程。\n\n   ```js live\n   setTimeout(() => {\n     console.log('This message is delayed by 2 seconds');\n   }, 2000);\n\n   setInterval(() => {\n     console.log('Current time:', new Date().toLocaleString());\n   }, 2000); // Interval runs every 2 seconds\n   ```\n\n通过使用异步函数和操作，JavaScript 可以处理耗时的任务，而不会冻结用户界面或阻塞主线程。\n\n重要的是要注意，**`async` 函数不会在不同的线程上运行**。它们仍然在主线程上运行。但是，通过使用 [Web workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)，可以在 JavaScript 中实现并行性。\n\n## 通过 Web worker 在 JavaScript 中实现并行性\n\nWeb worker 允许您生成单独的后台线程，这些线程可以与主线程并行执行 CPU 密集型任务。这些工作线程可以通过消息传递与主线程通信，但它们无法直接访问 DOM 或其他浏览器 API。\n\n```js\n// main.js\nconst worker = new Worker('worker.js');\n\nworker.onmessage = function (event) {\n  console.log('Result from worker:', event.data);\n};\n\nworker.postMessage('Start computation');\n```\n\n```js\n// worker.js\nself.onmessage = function (event) {\n  const result = performHeavyComputation();\n  self.postMessage(result);\n};\n\nfunction performHeavyComputation() {\n  // CPU-intensive computation\n  return 'Computation result';\n}\n```\n\n在此示例中，主线程创建一个新的 web worker，并向其发送一条消息以启动计算。worker 与主线程并行执行繁重的计算，并通过 `postMessage()` 将结果发送回去。\n\n## 事件循环\n\nJavaScript 的异步特性由 JavaScript 引擎的 [事件循环](/questions/quiz/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue) 提供支持，即使 JavaScript 是单线程的，它也允许并发操作。 这是一个重要的概念，需要理解，因此我们强烈建议您也浏览该主题。\n\n## 延伸阅读\n\n* [Asynchronous JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous)\n* [The Basics: synchronous and asynchronous JavaScript](https://www.linkedin.com/pulse/basics-synchronous-asynchronous-javascript-abdulkabir-okeowo)\n* [Synchronous and asynchronous programming in JavaScript](https://code.pieces.app/blog/synchronous-and-asynchronous-programming-in-javascript)\n* [Web Workers API - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)\n* [An overview of web workers - Web.dev](https://web.dev/learn/performance/web-worker-overview)\n"
  },
  {
    "path": "questions/explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"4e6b68eb\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"42798ec9\",\n        \"2a7816d0\",\n        \"8ee3e685\",\n        \"7c737123\",\n        \"614cdd4e\",\n        \"400f2c90\",\n        \"1b7dfa50\",\n        \"ca7a8d03\",\n        \"353d24f5\",\n        \"5cf4274c\",\n        \"c4b56a3\",\n        \"3d29713c\",\n        \"ac5147e5\",\n        \"8c71025f\",\n        \"ed3052d4\",\n        \"1f4770e5\",\n        \"aca48b7\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"42798ec9\",\n        \"2a7816d0\",\n        \"8ee3e685\",\n        \"7c737123\",\n        \"614cdd4e\",\n        \"400f2c90\",\n        \"1b7dfa50\",\n        \"ca7a8d03\",\n        \"353d24f5\",\n        \"5cf4274c\",\n        \"c4b56a3\",\n        \"3d29713c\",\n        \"ac5147e5\",\n        \"8c71025f\",\n        \"ed3052d4\",\n        \"1f4770e5\",\n        \"aca48b7\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing/en-US.mdx",
    "content": "---\ntitle: Explain the difference between unit testing, integration testing, and end-to-end testing\n---\n\n## TL;DR\n\nUnit testing focuses on testing individual components or functions in isolation to ensure they work as expected. Integration testing checks how different modules or services work together. End-to-end testing simulates real user scenarios to verify the entire application flow from start to finish.\n\n---\n\n## Difference between unit testing, integration testing, and end-to-end testing\n\n### Unit testing\n\nUnit testing involves testing individual components or functions in isolation. The goal is to ensure that each part of the code works correctly on its own. These tests are usually written by developers and are the first line of defense against bugs.\n\n- **Scope**: Single function or component\n- **Tools**: Jest, Mocha, Jasmine\n- **Example**: Testing a function that adds two numbers\n\n```js\nfunction add(a, b) {\n  return a + b;\n}\n\ntest('adds 1 + 2 to equal 3', () => {\n  expect(add(1, 2)).toBe(3);\n});\n```\n\n### Integration testing\n\nIntegration testing focuses on verifying the interactions between different modules or services. The goal is to ensure that combined parts of the application work together as expected. These tests are usually more complex than unit tests and may involve multiple components.\n\n- **Scope**: Multiple components or services\n- **Tools**: Jest, Mocha, Jasmine, Postman (for API testing)\n- **Example**: Testing a function that fetches data from an API and processes it\n\n```js\nasync function fetchData(apiUrl) {\n  const response = await fetch(apiUrl);\n  const data = await response.json();\n  return processData(data);\n}\n\ntest('fetches and processes data correctly', async () => {\n  const apiUrl = 'https://api.example.com/data';\n  const data = await fetchData(apiUrl);\n  expect(data).toEqual(expectedProcessedData);\n});\n```\n\n### End-to-end testing\n\nEnd-to-end (E2E) testing simulates real user scenarios to verify the entire application flow from start to finish. The goal is to ensure that the application works as a whole, including the user interface, backend, and any external services.\n\n- **Scope**: Entire application\n- **Tools**: Cypress, Selenium, Puppeteer\n- **Example**: Testing a user login flow\n\n```js\ndescribe('User Login Flow', () => {\n  it('should allow a user to log in', () => {\n    cy.visit('https://example.com/login');\n    cy.get('input[name=\"username\"]').type('testuser');\n    cy.get('input[name=\"password\"]').type('password123');\n    cy.get('button[type=\"submit\"]').click();\n    cy.url().should('include', '/dashboard');\n  });\n});\n```\n\n## Further reading\n\n- [Unit testing on Wikipedia](https://en.wikipedia.org/wiki/Unit_testing)\n- [Integration testing on Wikipedia](https://en.wikipedia.org/wiki/Integration_testing)\n- [End-to-end testing on Wikipedia](https://en.wikipedia.org/wiki/End-to-end_testing)\n- [Jest documentation](https://jestjs.io/docs/getting-started)\n- [Cypress documentation](https://docs.cypress.io/guides/overview/why-cypress)\n"
  },
  {
    "path": "questions/explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"testing\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Testing\"\n}\n"
  },
  {
    "path": "questions/explain-the-difference-between-unit-testing-integration-testing-and-end-to-end-testing/zh-CN.mdx",
    "content": "---\ntitle: 解释单元测试、集成测试和端到端测试的区别\n---\n\n## TL;DR\n\n单元测试侧重于隔离测试单个组件或函数，以确保它们按预期工作。集成测试检查不同模块或服务如何协同工作。端到端测试模拟真实用户场景，以验证从开始到结束的整个应用程序流程。\n\n***\n\n## 单元测试、集成测试和端到端测试的区别\n\n### 单元测试\n\n单元测试涉及隔离测试单个组件或函数。目标是确保代码的每个部分都能正常工作。这些测试通常由开发人员编写，是防止错误的的第一道防线。\n\n* **范围**：单个函数或组件\n* **工具**：Jest、Mocha、Jasmine\n* **示例**：测试一个将两个数字相加的函数\n\n```js\nfunction add(a, b) {\n  return a + b;\n}\n\ntest('adds 1 + 2 to equal 3', () => {\n  expect(add(1, 2)).toBe(3);\n});\n```\n\n### 集成测试\n\n集成测试侧重于验证不同模块或服务之间的交互。目标是确保应用程序的组合部分按预期协同工作。这些测试通常比单元测试更复杂，可能涉及多个组件。\n\n* **范围**：多个组件或服务\n* **工具**：Jest、Mocha、Jasmine、Postman（用于 API 测试）\n* **示例**：测试一个从 API 获取数据并处理数据的函数\n\n```js\nasync function fetchData(apiUrl) {\n  const response = await fetch(apiUrl);\n  const data = await response.json();\n  return processData(data);\n}\n\ntest('fetches and processes data correctly', async () => {\n  const apiUrl = 'https://api.example.com/data';\n  const data = await fetchData(apiUrl);\n  expect(data).toEqual(expectedProcessedData);\n});\n```\n\n### 端到端测试\n\n端到端 (E2E) 测试模拟真实用户场景，以验证从开始到结束的整个应用程序流程。目标是确保应用程序作为一个整体工作，包括用户界面、后端和任何外部服务。\n\n* **范围**：整个应用程序\n* **工具**：Cypress、Selenium、Puppeteer\n* **示例**：测试用户登录流程\n\n```js\ndescribe('User Login Flow', () => {\n  it('should allow a user to log in', () => {\n    cy.visit('https://example.com/login');\n    cy.get('input[name=\"username\"]').type('testuser');\n    cy.get('input[name=\"password\"]').type('password123');\n    cy.get('button[type=\"submit\"]').click();\n    cy.url().should('include', '/dashboard');\n  });\n});\n```\n\n## 延伸阅读\n\n* [维基百科上的单元测试](https://en.wikipedia.org/wiki/Unit_testing)\n* [维基百科上的集成测试](https://en.wikipedia.org/wiki/Integration_testing)\n* [维基百科上的端到端测试](https://en.wikipedia.org/wiki/End-to-end_testing)\n* [Jest 文档](https://jestjs.io/docs/getting-started)\n* [Cypress 文档](https://docs.cypress.io/guides/overview/why-cypress)\n"
  },
  {
    "path": "questions/explain-the-difference-in-hoisting-between-var-let-and-const/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"ef61e101\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"6ca0ae49\",\n        \"2a7816d0\",\n        \"bf1362d8\",\n        \"cf21213f\",\n        \"8fe0f375\",\n        \"aa3aef43\",\n        \"2a8fefa2\",\n        \"48899074\",\n        \"11857e44\",\n        \"1623a878\",\n        \"1553a533\",\n        \"31d7ee9f\",\n        \"1f4770e5\",\n        \"a69fa1aa\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"6ca0ae49\",\n        \"2a7816d0\",\n        \"bf1362d8\",\n        \"cf21213f\",\n        \"8fe0f375\",\n        \"aa3aef43\",\n        \"2a8fefa2\",\n        \"48899074\",\n        \"11857e44\",\n        \"1623a878\",\n        \"1553a533\",\n        \"31d7ee9f\",\n        \"1f4770e5\",\n        \"a69fa1aa\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-difference-in-hoisting-between-var-let-and-const/en-US.mdx",
    "content": "---\ntitle: Explain the difference in hoisting between `var`, `let`, and `const`\n---\n\n## TL;DR\n\n`var` declarations are hoisted to the top of their scope and initialized with `undefined`, allowing them to be used before their declaration. `let` and `const` declarations are also hoisted but are not initialized, resulting in a `ReferenceError` if accessed before their declaration. `const` additionally requires an initial value at the time of declaration.\n\n---\n\n## Hoisting differences between `var`, `let`, and `const`\n\n### `var` hoisting\n\n`var` declarations are hoisted to the top of their containing function or global scope. This means the variable is available throughout the entire function or script, even before the line where it is declared. However, the variable is initialized with `undefined` until the actual declaration is encountered.\n\n```js live\nconsole.log(a); // Output: undefined\nvar a = 10;\nconsole.log(a); // Output: 10\n```\n\n### `let` hoisting\n\n`let` declarations are also hoisted to the top of their block scope, but they are not initialized. This creates a \"temporal dead zone\" (TDZ) from the start of the block until the declaration is encountered. Accessing the variable in the TDZ results in a `ReferenceError`.\n\n```js live\nconsole.log(b); // ReferenceError: Cannot access 'b' before initialization\nlet b = 20;\nconsole.log(b); // Output: 20\n```\n\n### `const` hoisting\n\n`const` declarations behave similarly to `let` in terms of hoisting. They are hoisted to the top of their block scope but are not initialized, resulting in a TDZ. Additionally, `const` requires an initial value at the time of declaration and cannot be reassigned.\n\n```js live\nconsole.log(c); // ReferenceError: Cannot access 'c' before initialization\nconst c = 30;\nconsole.log(c); // Output: 30\n```\n\n## Further reading\n\n- [MDN Web Docs: var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)\n- [MDN Web Docs: let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)\n- [MDN Web Docs: const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)\n- [JavaScript.info: Variable scope, closure](https://javascript.info/closure#var)\n"
  },
  {
    "path": "questions/explain-the-difference-in-hoisting-between-var-let-and-const/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-difference-in-hoisting-between-var-let-and-const\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Hoisting\"\n}\n"
  },
  {
    "path": "questions/explain-the-difference-in-hoisting-between-var-let-and-const/zh-CN.mdx",
    "content": "---\ntitle: 解释 `var`、`let` 和 `const` 之间的变量提升区别\n---\n\n## 总结\n\n`var` 声明会被提升到其作用域的顶部并使用 `undefined` 初始化，允许它们在其声明之前被使用。`let` 和 `const` 声明也会被提升，但不会被初始化，如果在声明之前访问它们，则会导致 `ReferenceError`。`const` 声明在声明时还需要一个初始值。\n\n***\n\n## `var`、`let` 和 `const` 之间的变量提升区别\n\n### `var` 的变量提升\n\n`var` 声明会被提升到其包含的函数或全局作用域的顶部。这意味着变量可以在整个函数或脚本中使用，即使在声明它的行之前也是如此。但是，在遇到实际声明之前，变量会被初始化为 `undefined`。\n\n```js live\nconsole.log(a); // Output: undefined\nvar a = 10;\nconsole.log(a); // Output: 10\n```\n\n### `let` 的变量提升\n\n`let` 声明也会被提升到其块级作用域的顶部，但它们不会被初始化。这会在块的开始到声明被遇到之间创建一个“暂时性死区”（TDZ）。在 TDZ 中访问变量会导致 `ReferenceError`。\n\n```js live\nconsole.log(b); // ReferenceError: Cannot access 'b' before initialization\nlet b = 20;\nconsole.log(b); // Output: 20\n```\n\n### `const` 的变量提升\n\n`const` 声明在变量提升方面与 `let` 类似。它们被提升到其块级作用域的顶部，但未被初始化，从而导致 TDZ。此外，`const` 在声明时需要一个初始值，并且不能被重新赋值。\n\n```js live\nconsole.log(c); // ReferenceError: Cannot access 'c' before initialization\nconst c = 30;\nconsole.log(c); // Output: 30\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)\n* [MDN Web Docs: let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)\n* [MDN Web Docs: const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)\n* [JavaScript.info: Variable scope, closure](https://javascript.info/closure#var)\n"
  },
  {
    "path": "questions/explain-the-differences-between-commonjs-modules-and-es-modules/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"5f802061\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"2765778b\",\n        \"f56cb764\",\n        \"597ab666\",\n        \"c7fc1f4a\",\n        \"3dc21eb\",\n        \"4aadbe48\",\n        \"ec242a06\",\n        \"2a7816d0\",\n        \"23440456\",\n        \"61ea4d33\",\n        \"96b698d\",\n        \"8ac7ebde\",\n        \"3cfea1c2\",\n        \"597ab666\",\n        \"241f077b\",\n        \"fe089a\",\n        \"2e26993b\",\n        \"3dc21eb\",\n        \"67a1d4f3\",\n        \"ae22a9f0\",\n        \"1f4770e5\",\n        \"2f1b469c\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"2765778b\",\n        \"f56cb764\",\n        \"597ab666\",\n        \"c7fc1f4a\",\n        \"3dc21eb\",\n        \"4aadbe48\",\n        \"ec242a06\",\n        \"2a7816d0\",\n        \"23440456\",\n        \"61ea4d33\",\n        \"96b698d\",\n        \"8ac7ebde\",\n        \"3cfea1c2\",\n        \"597ab666\",\n        \"241f077b\",\n        \"fe089a\",\n        \"2e26993b\",\n        \"3dc21eb\",\n        \"67a1d4f3\",\n        \"ae22a9f0\",\n        \"1f4770e5\",\n        \"2f1b469c\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-differences-between-commonjs-modules-and-es-modules/en-US.mdx",
    "content": "---\ntitle: Explain the differences between CommonJS modules and ES modules in JavaScript\n---\n\n## TL;DR\n\nIn JavaScript, modules are reusable pieces of code that encapsulate functionality, making it easier to manage, maintain, and structure your applications. Modules allow you to break down your code into smaller, manageable parts, each with its own scope.\n\n**CommonJS** is an older module system that was initially designed for server-side JavaScript development with Node.js. It uses the `require()` function to load modules and the `module.exports` or `exports` object to define the exports of a module.\n\n```js\n// my-module.js\nconst value = 42;\nmodule.exports = { value };\n\n// main.js\nconst myModule = require('./my-module.js');\nconsole.log(myModule.value); // 42\n```\n\n**ES Modules** (ECMAScript Modules) are the standardized module system introduced in ES6 (ECMAScript 2015). They use the `import` and `export` statements to handle module dependencies.\n\n```js\n// my-module.js\nexport const value = 42;\n\n// main.js\nimport { value } from './my-module.js';\nconsole.log(value); // 42\n```\n\n**CommonJS vs ES modules**\n\n| Feature | CommonJS | ES modules |\n| --- | --- | --- |\n| Module Syntax | `require()` for importing `module.exports` for exporting | `import` for importing `export` for exporting |\n| Environment | Primarily used in Node.js for server-side development | Designed for both browser and server-side JavaScript (Node.js) |\n| Loading | Synchronous loading of modules | Asynchronous loading of modules |\n| Structure | Dynamic imports, can be conditionally called | Static imports/exports at the top level |\n| File extensions | `.js` (default) | `.mjs` or `.js` (with `type: \"module\"` in `package.json`) |\n| Browser support | Not natively supported in browsers | Natively supported in modern browsers |\n| Optimization | Limited optimization due to dynamic nature | Allows for optimizations like tree-shaking due to static structure |\n| Compatibility | Widely used in existing Node.js codebases and libraries | Newer standard, but gaining adoption in modern projects |\n\n---\n\n## Modules in Javascript\n\nModules in JavaScript are a way to organize and encapsulate code into reusable and maintainable units. They allow developers to break down their codebase into smaller, self-contained pieces, promoting code reuse, separation of concerns, and better organization. There are two main module systems in JavaScript: CommonJS and ES modules.\n\n### CommonJS\n\nCommonJS is an older module system that was initially designed for server-side JavaScript development with Node.js. It uses the require function to load modules and the `module.exports` or `exports` object to define the exports of a module.\n\n- **Syntax**: Modules are included using `require()` and exported using `module.exports`.\n- **Environment**: Primarily used in `Node.js`.\n- **Execution**: Modules are loaded synchronously.\n- Modules are loaded dynamically at runtime.\n\n```js\n// my-module.js\nconst value = 42;\nmodule.exports = { value };\n\n// main.js\nconst myModule = require('./my-module.js');\nconsole.log(myModule.value); // 42\n```\n\n### ES Modules\n\nES Modules (ECMAScript Modules) are the standardized module system introduced in ES6 (ECMAScript 2015). They use the `import` and `export` statements to handle module dependencies.\n\n- **Syntax**: Modules are imported using `import` and exported using `export`.\n- **Environment**: Can be used in both browser environments and Node.js (with certain configurations).\n- **Execution**: Modules are loaded asynchronously.\n- **Support**: Introduced in ES2015, now widely supported in modern browsers and Node.js.\n- Modules are loaded statically at compile-time.\n- Enables better performance due to static analysis and tree-shaking.\n\n```js\n// my-module.js\nexport const value = 42;\n\n// main.js\nimport { value } from './my-module.js';\nconsole.log(value); // 42\n```\n\n## Summary\n\nWhile CommonJS was the default module system in Node.js initially, ES modules are now the recommended approach for new projects, as they provide better tooling, performance, and ecosystem compatibility. However, CommonJS modules are still widely used in existing code bases and libraries especially for legacy dependencies.\n\n## Further reading\n\n- [JavaScript modules - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n- [Modules, introduction - javascript.info](https://javascript.info/modules-intro)\n- [Modules - Eloquent Javascript](https://eloquentjavascript.net/10_modules.html)\n- [CommonJS vs. ES modules in Node.js](https://blog.logrocket.com/commonjs-vs-es-modules-node-js/)\n- [Understanding CommonJS vs. ES Modules in JavaScript](https://www.syncfusion.com/blogs/post/js-commonjs-vs-es-modules)\n"
  },
  {
    "path": "questions/explain-the-differences-between-commonjs-modules-and-es-modules/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-differences-between-commonjs-modules-and-es-modules\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 340,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/explain-the-differences-between-commonjs-modules-and-es-modules/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 中 CommonJS 模块和 ES 模块的区别\n---\n\n## 总结\n\n在 JavaScript 中，模块是可重用的代码片段，封装了功能，使其更易于管理、维护和构建应用程序。模块允许您将代码分解为更小、更易于管理的部分，每个部分都有自己的作用域。\n\n**CommonJS** 是一个较旧的模块系统，最初是为使用 Node.js 进行服务器端 JavaScript 开发而设计的。它使用 `require()` 函数来加载模块，并使用 `module.exports` 或 `exports` 对象来定义模块的导出。\n\n```js\n// my-module.js\nconst value = 42;\nmodule.exports = { value };\n\n// main.js\nconst myModule = require('./my-module.js');\nconsole.log(myModule.value); // 42\n```\n\n**ES 模块**（ECMAScript 模块）是 ES6（ECMAScript 2015）中引入的标准化模块系统。它们使用 `import` 和 `export` 语句来处理模块依赖关系。\n\n```js\n// my-module.js\nexport const value = 42;\n\n// main.js\nimport { value } from './my-module.js';\nconsole.log(value); // 42\n```\n\n**CommonJS vs ES 模块**\n\n| 特性 | CommonJS | ES 模块 |\n| --- | --- | --- |\n| 模块语法 | `require()` 用于导入 `module.exports` 用于导出 | `import` 用于导入 `export` 用于导出 |\n| 环境 | 主要用于 Node.js 进行服务器端开发 | 专为浏览器和服务器端 JavaScript (Node.js) 设计 |\n| 加载 | 模块的同步加载 | 模块的异步加载 |\n| 结构 | 动态导入，可以有条件地调用 | 顶层的静态导入/导出 |\n| 文件扩展名 | `.js` (默认) | `.mjs` 或 `.js` (在 `package.json` 中使用 `type: \"module\"`) |\n| 浏览器支持 | 浏览器中不原生支持 | 现代浏览器中原生支持 |\n| 优化 | 由于其动态特性，优化有限 | 允许进行树摇等优化，因为具有静态结构 |\n| 兼容性 | 广泛用于现有的 Node.js 代码库和库 | 较新的标准，但在现代项目中得到越来越多的采用 |\n\n***\n\n## Javascript 中的模块\n\nJavaScript 中的模块是一种将代码组织和封装成可重用和可维护单元的方式。它们允许开发人员将他们的代码库分解成更小、自包含的部分，从而促进代码重用、关注点分离和更好的组织。JavaScript 中有两个主要的模块系统：CommonJS 和 ES 模块。\n\n### CommonJS\n\nCommonJS 是一个较旧的模块系统，最初是为使用 Node.js 进行服务器端 JavaScript 开发而设计的。它使用 require 函数来加载模块，并使用 `module.exports` 或 `exports` 对象来定义模块的导出。\n\n* **语法**：使用 `require()` 包含模块，使用 `module.exports` 导出模块。\n* **环境**：主要用于 `Node.js`。\n* **执行**：模块是同步加载的。\n* 模块在运行时动态加载。\n\n```js\n// my-module.js\nconst value = 42;\nmodule.exports = { value };\n\n// main.js\nconst myModule = require('./my-module.js');\nconsole.log(myModule.value); // 42\n```\n\n### ES 模块\n\nES 模块（ECMAScript 模块）是 ES6（ECMAScript 2015）中引入的标准化模块系统。它们使用 `import` 和 `export` 语句来处理模块依赖关系。\n\n* **语法**：使用 `import` 导入模块，使用 `export` 导出模块。\n* **环境**：可以在浏览器环境和 Node.js 中使用（使用某些配置）。\n* **执行**：模块是异步加载的。\n* **支持**：在 ES2015 中引入，现在在现代浏览器和 Node.js 中得到广泛支持。\n* 模块在编译时静态加载。\n* 由于静态分析和树摇，可以实现更好的性能。\n\n```js\n// my-module.js\nexport const value = 42;\n\n// main.js\nimport { value } from './my-module.js';\nconsole.log(value); // 42\n```\n\n## 总结\n\n虽然 CommonJS 最初是 Node.js 中的默认模块系统，但 ES 模块现在是新项目的推荐方法，因为它们提供了更好的工具、性能和生态系统兼容性。 然而，CommonJS 模块仍然广泛用于现有的代码库和库中，尤其是在遗留依赖项中。\n\n## 延伸阅读\n\n* [JavaScript modules - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n* [Modules, introduction - javascript.info](https://javascript.info/modules-intro)\n* [Modules - Eloquent Javascript](https://eloquentjavascript.net/10_modules.html)\n* [CommonJS vs. ES modules in Node.js](https://blog.logrocket.com/commonjs-vs-es-modules-node-js/)\n* [Understanding CommonJS vs. ES Modules in JavaScript](https://www.syncfusion.com/blogs/post/js-commonjs-vs-es-modules)\n"
  },
  {
    "path": "questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"5774a226\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"d28a87d\",\n        \"959ea2a5\",\n        \"98f624dc\",\n        \"cb5c1a5\",\n        \"cf4b5868\",\n        \"83b2d277\",\n        \"454d71bd\",\n        \"573fa2a9\",\n        \"684325e8\",\n        \"2a7816d0\",\n        \"31940765\",\n        \"a843e4fa\",\n        \"5ff12ab0\",\n        \"4fb4aa30\",\n        \"7e46d513\",\n        \"77c1efe2\",\n        \"684325e8\",\n        \"657a3b69\",\n        \"9d8dc24e\",\n        \"6e2b15fe\",\n        \"e6bf7e83\",\n        \"cb5c1a5\",\n        \"25d7cd36\",\n        \"83b2d277\",\n        \"b99eac1f\",\n        \"32ca29c1\",\n        \"573fa2a9\",\n        \"91c903bb\",\n        \"fa071102\",\n        \"ee23a9aa\",\n        \"1f4770e5\",\n        \"60a334e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d28a87d\",\n        \"959ea2a5\",\n        \"98f624dc\",\n        \"cb5c1a5\",\n        \"cf4b5868\",\n        \"83b2d277\",\n        \"454d71bd\",\n        \"573fa2a9\",\n        \"684325e8\",\n        \"2a7816d0\",\n        \"31940765\",\n        \"a843e4fa\",\n        \"5ff12ab0\",\n        \"4fb4aa30\",\n        \"7e46d513\",\n        \"77c1efe2\",\n        \"684325e8\",\n        \"657a3b69\",\n        \"9d8dc24e\",\n        \"6e2b15fe\",\n        \"e6bf7e83\",\n        \"cb5c1a5\",\n        \"25d7cd36\",\n        \"83b2d277\",\n        \"b99eac1f\",\n        \"32ca29c1\",\n        \"573fa2a9\",\n        \"91c903bb\",\n        \"fa071102\",\n        \"ee23a9aa\",\n        \"1f4770e5\",\n        \"60a334e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/en-US.mdx",
    "content": "---\ntitle: Explain the differences on the usage of `foo` between `function foo() {}` and `var foo = function() {}` in JavaScript\n---\n\n## TL;DR\n\n`function foo() {}` a function declaration while the `var foo = function() {}` is a function expression. The key difference is that function declarations have its body hoisted but the bodies of function expressions are not (they have the same hoisting behavior as `var`-declared variables).\n\nIf you try to invoke a function expression before it is declared, you will get an `Uncaught TypeError: XXX is not a function` error.\n\nFunction declarations can be called in the enclosing scope even before they are declared.\n\n```js live\nfoo(); // 'FOOOOO'\nfunction foo() {\n  console.log('FOOOOO');\n}\n```\n\nFunction expressions if called before they are declared will result in an error.\n\n```js live\nfoo(); // Uncaught TypeError: foo is not a function\nvar foo = function () {\n  console.log('FOOOOO');\n};\n```\n\nAnother key difference is in the scope of the function name. Function expressions can be named by defining it after the `function` and before the parenthesis. However when using named function expressions, the function name is only accessible within the function itself. Trying to access it outside will result in an error or `undefined`.\n\n```js live\nconst myFunc = function namedFunc() {\n  console.log(namedFunc); // Works\n};\n\nmyFunc(); // Runs the function and logs the function reference\nconsole.log(namedFunc); // ReferenceError: namedFunc is not defined\n```\n\n**Note**: The examples uses `var` due to legacy reasons. Function expressions can be defined using `let` and `const` and the key difference is in the hoisting behavior of those keywords.\n\n---\n\n## Function declarations\n\nA function declaration is a statement that defines a function with a name. It is typically used to declare a function that can be called multiple times throughout the enclosing scope.\n\n```js live\nfunction foo() {\n  console.log('FOOOOO');\n}\nfoo(); // 'FOOOOO'\n```\n\n## Function expressions\n\nA function expression is an expression that defines a function and assigns it to a variable. It is often used when a function is needed only once or in a specific context.\n\n```js live\nvar foo = function () {\n  console.log('FOOOOO');\n};\nfoo(); // 'FOOOOO'\n```\n\n**Note**: The examples uses `var` due to legacy reasons. Function expressions can be defined using `let` and `const` and the key difference is in the hoisting behavior of those keywords.\n\n## Key differences\n\n### Hoisting\n\nThe key difference is that function declarations have its body hoisted but the bodies of function expressions are not (they have the same hoisting behavior as `var`-declared variables). For more explanation on hoisting, refer to the quiz question on [hoisting](/questions/quiz/explain-hoisting). If you try to invoke a function expression before it is defined, you will get an `Uncaught TypeError: XXX is not a function` error.\n\nFunction declarations:\n\n```js live\nfoo(); // 'FOOOOO'\nfunction foo() {\n  console.log('FOOOOO');\n}\n```\n\nFunction expressions:\n\n```js live\nfoo(); // Uncaught TypeError: foo is not a function\nvar foo = function () {\n  console.log('FOOOOO');\n};\n```\n\n### Name scope\n\nFunction expressions can be named by defining it after the `function` and before the parenthesis. However when using named function expressions, the function name is only accessible within the function itself. Trying to access it outside will result in `undefined` and calling it will result in an error.\n\n```js live\nconst myFunc = function namedFunc() {\n  console.log(namedFunc); // Works\n};\n\nmyFunc(); // Runs the function and logs the function reference\nconsole.log(namedFunc); // ReferenceError: namedFunc is not defined\n```\n\n## When to use each\n\n- Function declarations:\n  - When you want to create a function on the global scope and make it available throughout the enclosing scope.\n  - If a function is reusable and needs to be called multiple times.\n- Function expressions:\n  - If a function is only needed once or in a specific context.\n  - Use to limit the function availability to subsequent code and keep the enclosing scope clean.\n\nIn general, it's preferable to use function declarations to avoid the mental overhead of determining if a function can be called. The practical usages of function expressions is quite rare.\n\n## Further reading\n\n- [Function declaration | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)\n- [Function expression | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)\n"
  },
  {
    "path": "questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 150,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/pt-BR.mdx",
    "content": "---\ntitle: Explique as diferenças no uso de `foo` entre `function foo() {}` e `var foo = function() {}`\n---\n\nO primeiro é uma declaração de funções, enquanto o segundo é uma expressão de funções. A diferença chave é que as declarações de funções tem seu corpo hoisted, mas os corpos das expressões de função não são (elas têm o mesmo comportamento hoisting que as variáveis). Para obter mais explicações sobre o hoisting, consulte a pergunta sobre [hoisting](/questions/quiz/explain-hoisting). Se você tentar invocar uma expressão de função antes de ela ser definida, você receberá um erro `Uncaught TypeError: XXX não é um erro de função`.\n\n## Declaração de Função\n\n```js\nfoo(); // 'FOOOO'\nfunction foo() {\n  console.log('FOOOOO');\n}\n```\n\n## Expressão de Função\n\n```js\nfoo(); // Uncaught TypeError: foo não é uma função\nvar foo = function () {\n  console.log('FOOOOO');\n};\n```\n"
  },
  {
    "path": "questions/explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function/zh-CN.mdx",
    "content": "---\ntitle: '解释 JavaScript 中 `function foo() {}` 和 `var foo = function() {}` 之间 `foo` 的用法差异'\n---\n\n## 总结\n\n`function foo() {}` 是一个函数声明，而 `var foo = function() {}` 是一个函数表达式。 关键区别在于函数声明具有函数体提升，但函数表达式的函数体没有（它们具有与 `var` 声明的变量相同的提升行为）。\n\n如果尝试在函数表达式声明之前调用它，将会得到一个 `Uncaught TypeError: XXX is not a function` 错误。\n\n即使在函数声明之前，也可以在封闭范围内调用函数声明。\n\n```js live\nfoo(); // 'FOOOOO'\nfunction foo() {\n  console.log('FOOOOO');\n}\n```\n\n如果函数表达式在声明之前被调用，将会导致错误。\n\n```js live\nfoo(); // Uncaught TypeError: foo is not a function\nvar foo = function () {\n  console.log('FOOOOO');\n};\n```\n\n另一个关键区别在于函数名称的范围。 函数表达式可以通过在 `function` 之后和括号之前定义它来命名。 但是，当使用命名函数表达式时，函数名称只能在函数本身内部访问。 尝试在外部访问它将导致错误或 `undefined`。\n\n```js live\nconst myFunc = function namedFunc() {\n  console.log(namedFunc); // Works\n};\n\nmyFunc(); // Runs the function and logs the function reference\nconsole.log(namedFunc); // ReferenceError: namedFunc is not defined\n```\n\n**注意**：由于历史原因，示例使用 `var`。 函数表达式可以使用 `let` 和 `const` 定义，关键区别在于这些关键字的提升行为。\n\n***\n\n## 函数声明\n\n函数声明是一个使用名称定义函数的语句。 它通常用于声明可以在封闭范围内多次调用的函数。\n\n```js live\nfunction foo() {\n  console.log('FOOOOO');\n}\nfoo(); // 'FOOOOO'\n```\n\n## 函数表达式\n\n函数表达式是一个定义函数并将其分配给变量的表达式。 当只需要一次或在特定上下文中使用函数时，通常使用它。\n\n```js live\nvar foo = function () {\n  console.log('FOOOOO');\n};\nfoo(); // 'FOOOOO'\n```\n\n**注意**：由于历史原因，示例使用 `var`。 函数表达式可以使用 `let` 和 `const` 定义，关键区别在于这些关键字的提升行为。\n\n## 关键区别\n\n### 提升\n\n关键的区别在于函数声明有函数体提升，但函数表达式的函数体没有（它们具有与`var`声明的变量相同的提升行为）。有关提升的更多说明，请参阅关于[提升](/questions/quiz/explain-hoisting)的测验问题。如果尝试在函数表达式定义之前调用它，将会得到一个`Uncaught TypeError: XXX is not a function`错误。\n\n函数声明：\n\n```js live\nfoo(); // 'FOOOOO'\nfunction foo() {\n  console.log('FOOOOO');\n}\n```\n\n函数表达式：\n\n```js live\nfoo(); // Uncaught TypeError: foo is not a function\nvar foo = function () {\n  console.log('FOOOOO');\n};\n```\n\n### 命名范围\n\n函数表达式可以通过在`function`之后和括号之前定义它来命名。但是，当使用命名函数表达式时，函数名称只能在函数本身内部访问。尝试在外部访问它将导致`undefined`，调用它将导致错误。\n\n```js live\nconst myFunc = function namedFunc() {\n  console.log(namedFunc); // Works\n};\n\nmyFunc(); // Runs the function and logs the function reference\nconsole.log(namedFunc); // ReferenceError: namedFunc is not defined\n```\n\n## 何时使用\n\n* 函数声明：\n  * 当您想在全局范围内创建一个函数，并在整个封闭范围内使用它时。\n  * 如果一个函数是可重用的，并且需要多次调用。\n* 函数表达式：\n  * 如果一个函数只需要一次或在特定上下文中。\n  * 用于将函数可用性限制为后续代码，并保持封闭范围的清洁。\n\n总的来说，最好使用函数声明来避免确定是否可以调用函数的精神负担。函数表达式的实际用法非常罕见。\n\n## 延伸阅读\n\n* [函数声明 | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)\n* [函数表达式 | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)\n"
  },
  {
    "path": "questions/explain-the-different-states-of-a-promise/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"cc83687d\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"b1472188\",\n        \"d8beae83\",\n        \"2a7816d0\",\n        \"531a7c0c\",\n        \"fa4c55a4\",\n        \"447d2aab\",\n        \"2df653b6\",\n        \"c93719ec\",\n        \"f70f8a4c\",\n        \"7144b344\",\n        \"665bc377\",\n        \"79c3ee71\",\n        \"db21ae1d\",\n        \"1f4770e5\",\n        \"a900f8fa\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"b1472188\",\n        \"d8beae83\",\n        \"2a7816d0\",\n        \"531a7c0c\",\n        \"fa4c55a4\",\n        \"447d2aab\",\n        \"2df653b6\",\n        \"c93719ec\",\n        \"f70f8a4c\",\n        \"7144b344\",\n        \"665bc377\",\n        \"79c3ee71\",\n        \"db21ae1d\",\n        \"1f4770e5\",\n        \"a900f8fa\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-different-states-of-a-promise/en-US.mdx",
    "content": "---\ntitle: Explain the different states of a Promise\n---\n\n## TL;DR\n\nA `Promise` in JavaScript can be in one of three states: `pending`, `fulfilled`, or `rejected`. When a `Promise` is created, it starts in the `pending` state. If the operation completes successfully, the `Promise` transitions to the `fulfilled` state, and if it fails, it transitions to the `rejected` state. Here's a quick example:\n\n```js\nlet promise = new Promise((resolve, reject) => {\n  // some asynchronous operation\n  if (success) {\n    resolve('Success!');\n  } else {\n    reject('Error!');\n  }\n});\n```\n\n---\n\n## Different states of a Promise\n\n### Pending\n\nWhen a `Promise` is first created, it is in the `pending` state. This means that the asynchronous operation has not yet completed.\n\n```js\nlet promise = new Promise((resolve, reject) => {\n  // asynchronous operation\n});\n```\n\n### Fulfilled\n\nA `Promise` transitions to the `fulfilled` state when the asynchronous operation completes successfully. The `resolve` function is called to indicate this.\n\n```js\nlet promise = new Promise((resolve, reject) => {\n  resolve('Success!');\n});\n```\n\n### Rejected\n\nA `Promise` transitions to the `rejected` state when the asynchronous operation fails. The `reject` function is called to indicate this.\n\n```js\nlet promise = new Promise((resolve, reject) => {\n  reject('Error!');\n});\n```\n\n## Further reading\n\n- [MDN Web Docs: Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\n- [JavaScript.info: Promises](https://javascript.info/promise-basics)\n- [Promise/A+ Specification](https://promisesaplus.com/)\n"
  },
  {
    "path": "questions/explain-the-different-states-of-a-promise/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-different-states-of-a-promise\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"async\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Asynchronous JavaScript\"\n}\n"
  },
  {
    "path": "questions/explain-the-different-states-of-a-promise/zh-CN.mdx",
    "content": "---\ntitle: 解释 Promise 的不同状态\n---\n\n## 总结\n\nJavaScript 中的 `Promise` 可以处于三种状态之一：`pending`（待定）、`fulfilled`（已实现）或 `rejected`（已拒绝）。创建 `Promise` 时，它首先处于 `pending` 状态。如果操作成功完成，`Promise` 将转换为 `fulfilled` 状态，如果失败，则转换为 `rejected` 状态。 这是一个快速示例：\n\n```js\nlet promise = new Promise((resolve, reject) => {\n  // some asynchronous operation\n  if (success) {\n    resolve('Success!');\n  } else {\n    reject('Error!');\n  }\n});\n```\n\n***\n\n## Promise 的不同状态\n\n### 待定\n\n首次创建 `Promise` 时，它处于 `pending` 状态。 这意味着异步操作尚未完成。\n\n```js\nlet promise = new Promise((resolve, reject) => {\n  // asynchronous operation\n});\n```\n\n### 已实现\n\n当异步操作成功完成时，`Promise` 转换为 `fulfilled` 状态。 调用 `resolve` 函数来指示这一点。\n\n```js\nlet promise = new Promise((resolve, reject) => {\n  resolve('Success!');\n});\n```\n\n### 已拒绝\n\n当异步操作失败时，`Promise` 转换为 `rejected` 状态。 调用 `reject` 函数来指示这一点。\n\n```js\nlet promise = new Promise((resolve, reject) => {\n  reject('Error!');\n});\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\n* [JavaScript.info: Promises](https://javascript.info/promise-basics)\n* [Promise/A+ Specification](https://promisesaplus.com/)\n"
  },
  {
    "path": "questions/explain-the-different-ways-the-this-keyword-can-be-bound/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"9128e9\",\n        \"d45e572a\",\n        \"2a7816d0\",\n        \"543c624d\",\n        \"f6031b1a\",\n        \"a0d202c9\",\n        \"590c84ab\",\n        \"431e8ca9\",\n        \"e851d6d4\",\n        \"e3a09af8\",\n        \"93ce039d\",\n        \"2418943c\",\n        \"655f8caf\",\n        \"a87a1422\",\n        \"1b983f3a\",\n        \"722ad486\",\n        \"fe9ccd30\",\n        \"68e90143\",\n        \"ddfba541\",\n        \"8a141fe0\",\n        \"fb9680c5\",\n        \"48d5a19f\",\n        \"d7a0818b\",\n        \"1f4770e5\",\n        \"520d0c3e\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"9128e9\",\n        \"d45e572a\",\n        \"2a7816d0\",\n        \"543c624d\",\n        \"f6031b1a\",\n        \"a0d202c9\",\n        \"590c84ab\",\n        \"431e8ca9\",\n        \"e851d6d4\",\n        \"e3a09af8\",\n        \"93ce039d\",\n        \"2418943c\",\n        \"655f8caf\",\n        \"a87a1422\",\n        \"1b983f3a\",\n        \"722ad486\",\n        \"fe9ccd30\",\n        \"68e90143\",\n        \"ddfba541\",\n        \"8a141fe0\",\n        \"fb9680c5\",\n        \"48d5a19f\",\n        \"d7a0818b\",\n        \"1f4770e5\",\n        \"520d0c3e\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"bc05d31c\"\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-different-ways-the-this-keyword-can-be-bound/en-US.mdx",
    "content": "---\ntitle: Explain the different ways the `this` keyword can be bound\n---\n\n## TL;DR\n\nThe `this` keyword in JavaScript can be bound in several ways:\n\n- Default binding: In non-strict mode, `this` refers to the global object (window in browsers). In strict mode, `this` is `undefined`.\n- Implicit binding: When a function is called as a method of an object, `this` refers to the object.\n- Explicit binding: Using `call`, `apply`, or `bind` methods to explicitly set `this`.\n- New binding: When a function is used as a constructor with the `new` keyword, `this` refers to the newly created object.\n- Arrow functions: Arrow functions do not have their own `this` and inherit `this` from the surrounding lexical context.\n\n---\n\n## Default binding\n\nIn non-strict mode, if a function is called without any context, `this` refers to the global object (window in browsers). In strict mode, `this` is `undefined`.\n\n```js\nfunction showThis() {\n  console.log(this);\n}\n\nshowThis(); // In non-strict mode: window, in strict mode: undefined\n```\n\n## Implicit binding\n\nWhen a function is called as a method of an object, `this` refers to the object.\n\n```js live\nconst obj = {\n  name: 'Alice',\n  greet: function () {\n    console.log(this.name);\n  },\n};\n\nobj.greet(); // 'Alice'\n```\n\n## Explicit binding\n\nUsing `call`, `apply`, or `bind` methods, you can explicitly set `this`.\n\n### Using `call`\n\n```js live\nfunction greet() {\n  console.log(this.name);\n}\n\nconst person = { name: 'Bob' };\n\ngreet.call(person); // 'Bob'\n```\n\n### Using `apply`\n\n```js live\nfunction greet(greeting) {\n  console.log(greeting + ', ' + this.name);\n}\n\nconst person = { name: 'Charlie' };\n\ngreet.apply(person, ['Hello']); // 'Hello, Charlie'\n```\n\n### Using `bind`\n\n```js live\nfunction greet() {\n  console.log(this.name);\n}\n\nconst person = { name: 'Dave' };\n\nconst boundGreet = greet.bind(person);\nboundGreet(); // 'Dave'\n```\n\n## New binding\n\nWhen a function is used as a constructor with the `new` keyword, `this` refers to the newly created object.\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person = new Person('Eve');\nconsole.log(person.name); // 'Eve'\n```\n\n## Arrow functions\n\nArrow functions do not have their own `this` and inherit `this` from the surrounding lexical context.\n\n```js live\nconst obj = {\n  firstName: 'Frank',\n  greet: () => {\n    console.log(this.firstName);\n  },\n};\n\nobj.greet(); // undefined, because `this` is inherited from the global scope\n```\n\n## Further reading\n\n- [MDN Web Docs: this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\n- [JavaScript.info: Object methods, \"this\"](https://javascript.info/object-methods)\n- [You Don't Know JS: this & Object Prototypes](https://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/this%20%26%20object%20prototypes)\n"
  },
  {
    "path": "questions/explain-the-different-ways-the-this-keyword-can-be-bound/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-different-ways-the-this-keyword-can-be-bound\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"closure\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"This Keyword\"\n}\n"
  },
  {
    "path": "questions/explain-the-different-ways-the-this-keyword-can-be-bound/zh-CN.mdx",
    "content": "---\ntitle: 解释 `this` 关键字可以绑定的不同方式\n---\n\n## TL;DR\n\n`this` 关键字在 JavaScript 中可以通过几种方式绑定:\n\n* 默认绑定：在非严格模式下，`this` 指向全局对象（在浏览器中是 window）。在严格模式下，`this` 是 `undefined`。\n* 隐式绑定：当一个函数作为对象的方法被调用时，`this` 指向该对象。\n* 显式绑定：使用 `call`、`apply` 或 `bind` 方法显式设置 `this`。\n* new 绑定：当一个函数与 `new` 关键字一起用作构造函数时，`this` 指向新创建的对象。\n* 箭头函数：箭头函数没有自己的 `this`，并从周围的词法环境继承 `this`。\n\n***\n\n## 默认绑定\n\n在非严格模式下，如果一个函数在没有任何上下文的情况下被调用，`this` 指向全局对象（在浏览器中是 window）。在严格模式下，`this` 是 `undefined`。\n\n```js\nfunction showThis() {\n  console.log(this);\n}\n\nshowThis(); // 在非严格模式下：window，在严格模式下：undefined\n```\n\n## 隐式绑定\n\n当一个函数作为对象的方法被调用时，`this` 指向该对象。\n\n```js live\nconst obj = {\n  name: 'Alice',\n  greet: function () {\n    console.log(this.name);\n  },\n};\n\nobj.greet(); // 'Alice'\n```\n\n## 显式绑定\n\n使用 `call`、`apply` 或 `bind` 方法，你可以显式地设置 `this`。\n\n### 使用 `call`\n\n```js live\nfunction greet() {\n  console.log(this.name);\n}\n\nconst person = { name: 'Bob' };\n\ngreet.call(person); // 'Bob'\n```\n\n### 使用 `apply`\n\n```js live\nfunction greet(greeting) {\n  console.log(greeting + ', ' + this.name);\n}\n\nconst person = { name: 'Charlie' };\n\ngreet.apply(person, ['Hello']); // 'Hello, Charlie'\n```\n\n### 使用 `bind`\n\n```js live\nfunction greet() {\n  console.log(this.name);\n}\n\nconst person = { name: 'Dave' };\n\nconst boundGreet = greet.bind(person);\nboundGreet(); // 'Dave'\n```\n\n## New 绑定\n\n当一个函数与 `new` 关键字一起用作构造函数时，`this` 指的是新创建的对象。\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person = new Person('Eve');\nconsole.log(person.name); // 'Eve'\n```\n\n## 箭头函数\n\n箭头函数没有自己的 `this`，并从周围的词法上下文中继承 `this`。\n\n```js live\nconst obj = {\n  firstName: 'Frank',\n  greet: () => {\n    console.log(this.firstName);\n  },\n};\n\nobj.greet(); // undefined, because `this` is inherited from the global scope\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\n* [JavaScript.info: Object methods, \"this\"](https://javascript.info/object-methods)\n* [You Don't Know JS: this & Object Prototypes](https://github.com/getify/You-Don't-Know-JS/tree/2nd-ed/this%20%26%20object%20prototypes)\n"
  },
  {
    "path": "questions/explain-the-event-phases-in-a-browser/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"b7cf7a15\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"ee4fe510\",\n        \"2a7816d0\",\n        \"5bb02508\",\n        \"66438aa2\",\n        \"3cd951ed\",\n        \"7d068ce3\",\n        \"da357585\",\n        \"d1726b58\",\n        \"7eeed40d\",\n        \"aed7bcf3\",\n        \"29c0c77c\",\n        \"a1f1ab00\",\n        \"3da3df22\",\n        \"a2811563\",\n        \"d4e6827e\",\n        \"1f4770e5\",\n        \"b11ac82e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"ee4fe510\",\n        \"2a7816d0\",\n        \"5bb02508\",\n        \"66438aa2\",\n        \"3cd951ed\",\n        \"7d068ce3\",\n        \"da357585\",\n        \"d1726b58\",\n        \"7eeed40d\",\n        \"aed7bcf3\",\n        \"29c0c77c\",\n        \"a1f1ab00\",\n        \"3da3df22\",\n        \"a2811563\",\n        \"d4e6827e\",\n        \"1f4770e5\",\n        \"b11ac82e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-event-phases-in-a-browser/en-US.mdx",
    "content": "---\ntitle: Explain the event phases in a browser\n---\n\n## TL;DR\n\nIn a browser, events go through three phases: capturing, target, and bubbling. During the capturing phase, the event travels from the root to the target element. In the target phase, the event reaches the target element. Finally, in the bubbling phase, the event travels back up from the target element to the root. You can control event handling using `addEventListener` with the `capture` option.\n\n---\n\n## Event phases in a browser\n\n### Capturing phase\n\nThe capturing phase, also known as the trickling phase, is the first phase of event propagation. During this phase, the event starts from the root of the DOM tree and travels down to the target element. Event listeners registered for this phase will be triggered in the order from the outermost ancestor to the target element.\n\n```js\nelement.addEventListener('click', handler, true); // true indicates capturing phase\n```\n\n### Target phase\n\nThe target phase is the second phase of event propagation. In this phase, the event has reached the target element itself. Event listeners registered directly on the target element will be triggered during this phase.\n\n```js\nelement.addEventListener('click', handler); // default is target phase\n```\n\n### Bubbling phase\n\nThe bubbling phase is the final phase of event propagation. During this phase, the event travels back up from the target element to the root of the DOM tree. Event listeners registered for this phase will be triggered in the order from the target element to the outermost ancestor.\n\n```js\nelement.addEventListener('click', handler, false); // false indicates bubbling phase\n```\n\n### Controlling event propagation\n\nYou can control event propagation using methods like `stopPropagation` and `stopImmediatePropagation`. These methods can be called within an event handler to stop the event from propagating further.\n\n```js\nelement.addEventListener('click', function (event) {\n  event.stopPropagation(); // Stops the event from propagating further\n});\n```\n\n## Further reading\n\n- [MDN Web Docs: Event bubbling and capturing](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture)\n- [JavaScript.info: Bubbling and capturing](https://javascript.info/bubbling-and-capturing)\n- [W3C: DOM Level 3 Events Specification](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)\n"
  },
  {
    "path": "questions/explain-the-event-phases-in-a-browser/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-event-phases-in-a-browser\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"browser\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"DOM Manipulation & Events\"\n}\n"
  },
  {
    "path": "questions/explain-the-event-phases-in-a-browser/zh-CN.mdx",
    "content": "---\ntitle: 解释浏览器中的事件阶段\n---\n\n## TL;DR\n\n在浏览器中，事件经历三个阶段：捕获、目标和冒泡。在捕获阶段，事件从根节点传递到目标元素。在目标阶段，事件到达目标元素。最后，在冒泡阶段，事件从目标元素传递回根节点。您可以使用带有 `capture` 选项的 `addEventListener` 来控制事件处理。\n\n***\n\n## 浏览器中的事件阶段\n\n### 捕获阶段\n\n捕获阶段，也称为渗透阶段，是事件传播的第一个阶段。在此阶段，事件从 DOM 树的根开始，向下传递到目标元素。在此阶段注册的事件监听器将按照从最外层祖先到目标元素的顺序触发。\n\n```js\nelement.addEventListener('click', handler, true); // true indicates capturing phase\n```\n\n### 目标阶段\n\n目标阶段是事件传播的第二个阶段。在此阶段，事件已到达目标元素本身。直接在目标元素上注册的事件监听器将在此阶段触发。\n\n```js\nelement.addEventListener('click', handler); // default is target phase\n```\n\n### 冒泡阶段\n\n冒泡阶段是事件传播的最后一个阶段。在此阶段，事件从目标元素传递回 DOM 树的根。在此阶段注册的事件监听器将按照从目标元素到最外层祖先的顺序触发。\n\n```js\nelement.addEventListener('click', handler, false); // false indicates bubbling phase\n```\n\n### 控制事件传播\n\n您可以使用 `stopPropagation` 和 `stopImmediatePropagation` 等方法来控制事件传播。这些方法可以在事件处理程序中调用，以阻止事件进一步传播。\n\n```js\nelement.addEventListener('click', function (event) {\n  event.stopPropagation(); // Stops the event from propagating further\n});\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Event bubbling and capturing](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_bubbling_and_capture)\n* [JavaScript.info: Bubbling and capturing](https://javascript.info/bubbling-and-capturing)\n* [W3C: DOM Level 3 Events Specification](https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)\n"
  },
  {
    "path": "questions/explain-the-observer-pattern-and-its-use-cases/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"a08e4a16\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"fb4b2c4c\",\n        \"2a7816d0\",\n        \"56b6c25\",\n        \"74a21fe1\",\n        \"9027660\",\n        \"9fd9ba3\",\n        \"9b5019f0\",\n        \"7b60470b\",\n        \"ab56268a\",\n        \"c81ac723\",\n        \"59f141d\",\n        \"f1adbdff\",\n        \"a92588a9\",\n        \"a1194e21\",\n        \"4119a3f8\",\n        \"458e2b0a\",\n        \"b0df54c6\",\n        \"17e9083a\",\n        \"1f4770e5\",\n        \"5bc832d9\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"fb4b2c4c\",\n        \"2a7816d0\",\n        \"56b6c25\",\n        \"74a21fe1\",\n        \"9027660\",\n        \"9fd9ba3\",\n        \"9b5019f0\",\n        \"7b60470b\",\n        \"ab56268a\",\n        \"c81ac723\",\n        \"59f141d\",\n        \"f1adbdff\",\n        \"a92588a9\",\n        \"a1194e21\",\n        \"4119a3f8\",\n        \"458e2b0a\",\n        \"b0df54c6\",\n        \"17e9083a\",\n        \"1f4770e5\",\n        \"5bc832d9\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-observer-pattern-and-its-use-cases/en-US.mdx",
    "content": "---\ntitle: Explain the Observer pattern and its use cases\n---\n\n## TL;DR\n\nThe Observer pattern is a design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them of any state changes. This pattern is useful for implementing distributed event-handling systems, such as updating the user interface in response to data changes or implementing event-driven architectures.\n\n---\n\n## What is the Observer pattern?\n\nThe Observer pattern is a behavioral design pattern that defines a one-to-many dependency between objects. When the state of the subject (the one) changes, all its observers (the many) are notified and updated automatically. This pattern is particularly useful for scenarios where changes in one object need to be reflected in multiple other objects without tightly coupling them.\n\n### Key components\n\n1. **Subject**: The object that holds the state and sends notifications to observers.\n2. **Observer**: The objects that need to be notified of changes in the subject.\n3. **ConcreteSubject**: A specific implementation of the subject.\n4. **ConcreteObserver**: A specific implementation of the observer.\n\n### Example\n\nHere is a simple example in JavaScript:\n\n```js live\nclass Subject {\n  constructor() {\n    this.observers = [];\n  }\n\n  addObserver(observer) {\n    this.observers.push(observer);\n  }\n\n  removeObserver(observer) {\n    this.observers = this.observers.filter((obs) => obs !== observer);\n  }\n\n  notifyObservers() {\n    this.observers.forEach((observer) => observer.update());\n  }\n}\n\nclass Observer {\n  update() {\n    console.log('Observer updated');\n  }\n}\n\n// Usage\nconst subject = new Subject();\nconst observer1 = new Observer();\nconst observer2 = new Observer();\n\nsubject.addObserver(observer1);\nsubject.addObserver(observer2);\n\nsubject.notifyObservers(); // Both observers will be updated\n```\n\n## Use cases\n\n### User interface updates\n\nIn front end development, the Observer pattern is commonly used to update the user interface in response to changes in data. For example, in a Model-View-Controller (MVC) architecture, the view can observe the model and update itself whenever the model's state changes.\n\n### Event handling\n\nThe Observer pattern is useful for implementing event-driven systems. For instance, in JavaScript, the `addEventListener` method allows you to register multiple event handlers (observers) for a single event (subject).\n\n### Real-time data feeds\n\nApplications that require real-time updates, such as stock tickers or chat applications, can benefit from the Observer pattern. Observers can subscribe to data feeds and get notified whenever new data is available.\n\n### Dependency management\n\nIn complex applications, managing dependencies between different modules can be challenging. The Observer pattern helps decouple these modules, making the system more modular and easier to maintain.\n\n## Further reading\n\n- [Observer pattern on Wikipedia](https://en.wikipedia.org/wiki/Observer_pattern)\n- [Observer pattern in JavaScript](https://www.dofactory.com/javascript/observer-design-pattern)\n- [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides\n"
  },
  {
    "path": "questions/explain-the-observer-pattern-and-its-use-cases/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-observer-pattern-and-its-use-cases\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Design Patterns\"\n}\n"
  },
  {
    "path": "questions/explain-the-observer-pattern-and-its-use-cases/zh-CN.mdx",
    "content": "---\ntitle: 解释观察者模式及其用例\n---\n\n## 总结\n\n观察者模式是一种设计模式，其中一个对象（称为主题）维护其依赖项（称为观察者）的列表，并通知它们任何状态更改。此模式对于实现分布式事件处理系统非常有用，例如响应数据更改更新用户界面或实现事件驱动的架构。\n\n***\n\n## 什么是观察者模式？\n\n观察者模式是一种行为设计模式，它定义了对象之间的一对多依赖关系。当主题（一个）的状态发生变化时，它的所有观察者（多个）都会自动收到通知并更新。此模式特别适用于需要在不紧密耦合的情况下，将一个对象中的更改反映到多个其他对象中的场景。\n\n### 关键组件\n\n1. **主题**：保存状态并向观察者发送通知的对象。\n2. **观察者**：需要接收主题更改通知的对象。\n3. **具体主题**：主题的具体实现。\n4. **具体观察者**：观察者的具体实现。\n\n### 示例\n\n这是一个简单的 JavaScript 示例：\n\n```js live\nclass Subject {\n  constructor() {\n    this.observers = [];\n  }\n\n  addObserver(observer) {\n    this.observers.push(observer);\n  }\n\n  removeObserver(observer) {\n    this.observers = this.observers.filter((obs) => obs !== observer);\n  }\n\n  notifyObservers() {\n    this.observers.forEach((observer) => observer.update());\n  }\n}\n\nclass Observer {\n  update() {\n    console.log('Observer updated');\n  }\n}\n\n// Usage\nconst subject = new Subject();\nconst observer1 = new Observer();\nconst observer2 = new Observer();\n\nsubject.addObserver(observer1);\nsubject.addObserver(observer2);\n\nsubject.notifyObservers(); // Both observers will be updated\n```\n\n## 用例\n\n### 用户界面更新\n\n在前端开发中，观察者模式通常用于响应数据更改来更新用户界面。例如，在模型-视图-控制器 (MVC) 架构中，视图可以观察模型，并在模型状态发生变化时自行更新。\n\n### 事件处理\n\n观察者模式对于实现事件驱动系统非常有用。例如，在 JavaScript 中，`addEventListener` 方法允许您为单个事件（主题）注册多个事件处理程序（观察者）。\n\n### 实时数据馈送\n\n需要实时更新的应用程序（例如股票行情或聊天应用程序）可以从观察者模式中受益。观察者可以订阅数据馈送，并在有新数据可用时收到通知。\n\n### 依赖管理\n\n在复杂的应用程序中，管理不同模块之间的依赖关系可能具有挑战性。观察者模式有助于解耦这些模块，使系统更具模块化，更易于维护。\n\n## 延伸阅读\n\n* [维基百科上的观察者模式](https://en.wikipedia.org/wiki/Observer_pattern)\n* [JavaScript 中的观察者模式](https://www.dofactory.com/javascript/observer-design-pattern)\n* [设计模式：可复用面向对象软件要素](https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612) 作者：Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides\n"
  },
  {
    "path": "questions/explain-the-same-origin-policy-with-regards-to-javascript/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"733ca1c5\",\n        \"2a7816d0\",\n        \"a1c851e2\",\n        \"eb53477\",\n        \"d6658a2b\",\n        \"b041beb2\",\n        \"b70350cd\",\n        \"4e5cfec0\",\n        \"4e8ede6c\",\n        \"79fdd407\",\n        \"9b5019f0\",\n        \"6ef3431\",\n        \"bb53a3a4\",\n        \"68f59f31\",\n        \"847199cc\",\n        \"a84e4517\",\n        \"4ef53dec\",\n        \"e26e7ec\",\n        \"47acaca9\",\n        \"1f4770e5\",\n        \"674822f8\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"733ca1c5\",\n        \"2a7816d0\",\n        \"a1c851e2\",\n        \"eb53477\",\n        \"d6658a2b\",\n        \"b041beb2\",\n        \"b70350cd\",\n        \"4e5cfec0\",\n        \"4e8ede6c\",\n        \"79fdd407\",\n        \"9b5019f0\",\n        \"6ef3431\",\n        \"bb53a3a4\",\n        \"68f59f31\",\n        \"847199cc\",\n        \"a84e4517\",\n        \"4ef53dec\",\n        \"e26e7ec\",\n        \"47acaca9\",\n        \"1f4770e5\",\n        \"674822f8\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"9a5ac9b\"\n  }\n}\n"
  },
  {
    "path": "questions/explain-the-same-origin-policy-with-regards-to-javascript/en-US.mdx",
    "content": "---\ntitle: Explain the same-origin policy with regards to JavaScript\n---\n\n## TL;DR\n\nThe same-origin policy is a security measure implemented in web browsers to prevent malicious scripts on one page from accessing data on another page. It ensures that web pages can only make requests to the same origin, where the origin is defined by the combination of the protocol, domain, and port. For example, a script from `http://example.com` cannot access data from `http://anotherdomain.com`.\n\n---\n\n## What is the same-origin policy?\n\nThe same-origin policy is a critical security concept for web applications. It restricts how documents or scripts loaded from one origin can interact with resources from another origin. This policy helps to prevent malicious activities such as cross-site scripting (XSS) and cross-site request forgery (CSRF).\n\n### Definition of origin\n\nAn origin is defined by the scheme (protocol), host (domain), and port of a URL. For example, the origin of `http://example.com:80/page` is:\n\n- Scheme: `http`\n- Host: `example.com`\n- Port: `80`\n\nTwo URLs have the same origin if and only if all three components (scheme, host, and port) are identical.\n\n### How it works\n\nWhen a web page makes a request to another URL, the browser checks if the request is to the same origin. If the request is to a different origin, the browser blocks the request unless the server explicitly allows it using mechanisms like Cross-Origin Resource Sharing (CORS).\n\n### Example\n\nConsider the following example:\n\n- `http://example.com/page1` can access `http://example.com/page2` because they share the same origin.\n- `http://example.com/page1` cannot access `http://anotherdomain.com/page` because they have different origins.\n\n### Exceptions\n\nThere are some exceptions to the same-origin policy, such as:\n\n- Cross-Origin Resource Sharing (CORS): A mechanism that allows servers to specify who can access their resources.\n- JSONP: A technique used to request data from a server residing in a different domain.\n- WebSockets: A protocol that allows for full-duplex communication channels over a single TCP connection.\n\n### Code example\n\nHere is a simple example demonstrating the same-origin policy:\n\n```html\n<!-- index.html -->\n<script>\n  // This will work because the request is to the same origin\n  fetch('/api/data')\n    .then((response) => response.json())\n    .then((data) => console.log(data));\n\n  // This will be blocked by the browser because the request is to a different origin\n  fetch('http://anotherdomain.com/api/data')\n    .then((response) => response.json())\n    .then((data) => console.log(data))\n    .catch((error) => console.error('Error:', error));\n</script>\n```\n\n## Further reading\n\n- [MDN Web Docs: Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)\n- [MDN Web Docs: Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)\n- [OWASP: Cross-Site Scripting (XSS)](https://owasp.org/www-community/attacks/xss/)\n- [OWASP: Cross-Site Request Forgery (CSRF)](https://owasp.org/www-community/attacks/csrf)\n"
  },
  {
    "path": "questions/explain-the-same-origin-policy-with-regards-to-javascript/metadata.json",
    "content": "{\n  \"slug\": \"explain-the-same-origin-policy-with-regards-to-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": false,\n  \"topics\": [\"javascript\", \"networking\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/explain-the-same-origin-policy-with-regards-to-javascript/pt-BR.mdx",
    "content": "---\ntitle: Explique a política de mesma origem em relação ao JavaScript\n---\n\nA política de mesma origem impede o JavaScript de fazer solicitações além dos limites de domínio. Uma origem é definida como uma combinação de esquema URI, nome do host e número da porta. Essa política impede que um script malicioso em uma página obtenha acesso a dados sensíveis em outra página da web por meio do Document Object Model dessa página.\n"
  },
  {
    "path": "questions/explain-the-same-origin-policy-with-regards-to-javascript/zh-CN.mdx",
    "content": "---\ntitle: 解释 JavaScript 方面相同的来源策略\n---\n\n## TL;DR\n\n同源策略是 Web 浏览器中实施的一项安全措施，旨在防止一个页面上的恶意脚本访问另一个页面上的数据。它确保网页只能向同一来源发出请求，其中来源由协议、域和端口的组合定义。例如，来自 `http://example.com` 的脚本无法访问来自 `http://anotherdomain.com` 的数据。\n\n***\n\n## 什么是同源策略？\n\n同源策略是 Web 应用程序的一个关键安全概念。它限制了从一个来源加载的文档或脚本与来自另一个来源的资源交互的方式。此策略有助于防止恶意活动，例如跨站点脚本 (XSS) 和跨站点请求伪造 (CSRF)。\n\n### 来源的定义\n\n来源由 URL 的方案（协议）、主机（域）和端口定义。例如，`http://example.com:80/page` 的来源是：\n\n* 方案：`http`\n* 主机：`example.com`\n* 端口：`80`\n\n当且仅当所有三个组件（方案、主机和端口）都相同时，两个 URL 具有相同的来源。\n\n### 它是如何工作的\n\n当网页向另一个 URL 发出请求时，浏览器会检查该请求是否来自同一来源。如果该请求来自不同的来源，浏览器会阻止该请求，除非服务器使用跨域资源共享 (CORS) 等机制明确允许该请求。\n\n### 例子\n\n考虑以下示例：\n\n* `http://example.com/page1` 可以访问 `http://example.com/page2`，因为它们共享相同的来源。\n* `http://example.com/page1` 无法访问 `http://anotherdomain.com/page`，因为它们具有不同的来源。\n\n### 异常\n\n同源策略有一些例外，例如：\n\n* 跨域资源共享 (CORS)：一种允许服务器指定谁可以访问其资源的机制。\n* JSONP：一种用于从位于不同域中的服务器请求数据的技术。\n* WebSockets：一种允许通过单个 TCP 连接进行全双工通信通道的协议。\n\n### 代码示例\n\n这是一个简单的示例，演示了同源策略：\n\n```html\n<!-- index.html -->\n<script>\n  // This will work because the request is to the same origin\n  fetch('/api/data')\n    .then((response) => response.json())\n    .then((data) => console.log(data));\n\n  // This will be blocked by the browser because the request is to a different origin\n  fetch('http://anotherdomain.com/api/data')\n    .then((response) => response.json())\n    .then((data) => console.log(data))\n    .catch((error) => console.error('Error:', error));\n</script>\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy)\n* [MDN Web Docs: Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)\n* [OWASP: Cross-Site Scripting (XSS)](https://owasp.org/www-community/attacks/xss/)\n* [OWASP: Cross-Site Request Forgery (CSRF)](https://owasp.org/www-community/attacks/csrf)\n"
  },
  {
    "path": "questions/explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"ec3f5c7a\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"31268891\",\n        \"2a7816d0\",\n        \"44fd9eec\",\n        \"25841bc3\",\n        \"fd42bf20\",\n        \"b6df0131\",\n        \"73cdcff1\",\n        \"2819c383\",\n        \"d36335be\",\n        \"7d1034c0\",\n        \"7c02898d\",\n        \"f4ab82a8\",\n        \"db9220f6\",\n        \"4d454d2\",\n        \"3ae0c8\",\n        \"bc54e4ba\",\n        \"aa1ef90c\",\n        \"d0e673fe\",\n        \"3f1eb7c5\",\n        \"ba4429ac\",\n        \"559863ed\",\n        \"aa1ef90c\",\n        \"ef600ac6\",\n        \"fb53c1c1\",\n        \"de619341\",\n        \"4ce6f2db\",\n        \"1f4770e5\",\n        \"f1de3aab\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"31268891\",\n        \"2a7816d0\",\n        \"44fd9eec\",\n        \"25841bc3\",\n        \"fd42bf20\",\n        \"b6df0131\",\n        \"73cdcff1\",\n        \"2819c383\",\n        \"d36335be\",\n        \"7d1034c0\",\n        \"7c02898d\",\n        \"f4ab82a8\",\n        \"db9220f6\",\n        \"4d454d2\",\n        \"3ae0c8\",\n        \"bc54e4ba\",\n        \"aa1ef90c\",\n        \"d0e673fe\",\n        \"3f1eb7c5\",\n        \"ba4429ac\",\n        \"559863ed\",\n        \"aa1ef90c\",\n        \"ef600ac6\",\n        \"fb53c1c1\",\n        \"de619341\",\n        \"4ce6f2db\",\n        \"1f4770e5\",\n        \"f1de3aab\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly/en-US.mdx",
    "content": "---\ntitle: Explain what a single page app is and how to make one SEO-friendly\n---\n\n## TL;DR\n\nA single page application (SPA) is a web application that loads a single HTML page and dynamically updates content as the user interacts with the app. This approach provides a more fluid user experience but can be challenging for SEO because search engines may not execute JavaScript to render content. To make an SPA SEO-friendly, you can use server-side rendering (SSR) or static site generation (SSG) to ensure that search engines can index your content. Tools like Next.js for React or Nuxt.js for Vue.js can help achieve this.\n\n---\n\n## What is a single page app?\n\n### Definition\n\nA single page application (SPA) is a web application that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from the server. This results in a more fluid user experience, similar to a desktop application.\n\n### Key characteristics\n\n- The application loads a single HTML page and dynamically updates it as the user interacts with the app\n- Uses AJAX or Fetch API to communicate with the server and update the page without a full reload\n- Often relies on client-side routing to manage different views or states within the app\n\n### Benefits\n\n- Faster interactions after the initial load\n- Reduced server load due to fewer full-page requests\n- Improved user experience with smoother transitions\n\n## How to make an SPA SEO-friendly\n\n### Challenges\n\nSPAs can be challenging for SEO because search engines may not execute JavaScript to render content. This can result in search engines indexing an empty or incomplete page.\n\n### Solutions\n\n#### Server-side rendering (SSR)\n\nServer-side rendering involves rendering the initial HTML of the page on the server before sending it to the client. This ensures that search engines can index the fully rendered content.\n\n- **React**: Use Next.js, which provides built-in support for SSR\n- **Vue.js**: Use Nuxt.js, which also supports SSR out of the box\n\nExample with Next.js:\n\n```javascript\nimport React from 'react';\nimport { GetServerSideProps } from 'next';\n\nconst Page = ({ data }) => {\n  return (\n    <div>\n      <h1>{data.title}</h1>\n      <p>{data.content}</p>\n    </div>\n  );\n};\n\nexport const getServerSideProps: GetServerSideProps = async () => {\n  const res = await fetch('https://api.example.com/data');\n  const data = await res.json();\n\n  return {\n    props: {\n      data,\n    },\n  };\n};\n\nexport default Page;\n```\n\n#### Static site generation (SSG)\n\nStatic site generation involves generating the HTML for each page at build time. This approach is suitable for content that doesn't change frequently.\n\n- **React**: Use Next.js with its static generation capabilities\n- **Vue.js**: Use Nuxt.js with its static site generation feature\n\nExample with Next.js:\n\n```javascript\nimport React from 'react';\nimport { GetStaticProps } from 'next';\n\nconst Page = ({ data }) => {\n  return (\n    <div>\n      <h1>{data.title}</h1>\n      <p>{data.content}</p>\n    </div>\n  );\n};\n\nexport const getStaticProps: GetStaticProps = async () => {\n  const res = await fetch('https://api.example.com/data');\n  const data = await res.json();\n\n  return {\n    props: {\n      data,\n    },\n  };\n};\n\nexport default Page;\n```\n\n#### Pre-rendering with tools\n\nSome tools can pre-render your SPA and serve the pre-rendered HTML to search engines.\n\n- **Prerender.io**: A service that pre-renders your JavaScript application and serves the static HTML to search engines\n- **Rendertron**: A headless Chrome rendering solution that can be used to pre-render your SPA\n\n## Further reading\n\n- [Next.js Documentation](https://nextjs.org/docs)\n- [Nuxt.js Documentation](https://nuxtjs.org/docs)\n- [Prerender.io](https://prerender.io/)\n- [Rendertron](https://github.com/GoogleChrome/rendertron)\n"
  },
  {
    "path": "questions/explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly/metadata.json",
    "content": "{\n  \"slug\": \"explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": false,\n  \"topics\": [\"javascript\", \"html\"],\n  \"importance\": \"medium\",\n  \"ranking\": 999,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly/pt-BR.mdx",
    "content": "---\ntitle: Explique o que é um aplicativo de página única e como torná-lo amigável para SEO\n---\n\nOs desenvolvedores web atualmente se referem aos produtos que constroem como aplicativos web, em vez de sites. Embora não haja uma diferença estrita entre os dois termos, os aplicativos web tendem a ser altamente interativos e dinâmicos, permitindo que o usuário execute ações e receba uma resposta para sua ação. Tradicionalmente, o navegador recebe o HTML do servidor e o renderiza. Quando o usuário navegar para outra URL, é necessária uma atualização de página inteira e o servidor envia novo HTML para a nova página. Isso é chamado de renderização no lado do servidor.\n\nNo entanto, em SPAs modernas, é usado o rendering no lado do cliente (client-side rendering) em vez disso. O navegador carrega a página inicial do servidor, juntamente com os scripts (frameworks, bibliotecas, código do aplicativo) e folhas de estilo necessárias para todo o aplicativo. Quando o usuário navega para outras páginas, uma atualização de página não é acionada. A URL da página é atualizada através da [API Histórico HTML5](https://developer.mozilla.org/en-US/docs/Web/API/History_API). Novos dados necessários para a nova página, geralmente no formato JSON, são recuperados pelo navegador via [AJAX](https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started) pedidos ao servidor. O SPA, em seguida, atualiza dinamicamente a página com dados via JavaScript, que já foi baixado na carga inicial da página. Esse modelo é semelhante a como os aplicativos nativos dos dispositivos móveis funcionam.\n\n## Prós\n\n- O aplicativo parece mais responsivo e os usuários não veem o flash entre as navegações de página devido às atualizações completas da página.\n- São feitas menos solicitações HTTP ao servidor, pois os mesmos recursos não precisam ser baixados novamente a cada carga de página.\n- Há uma clara separação das responsabilidades entre o cliente e o servidor, permitindo a fácil construção de novos clientes para diferentes plataformas (por exemplo, dispositivos móveis, chatbots, relógios inteligentes) sem precisar modificar o código do servidor. Você também pode modificar a pilha de tecnologia no cliente e no servidor independentemente, desde que o contrato da API não seja quebrado.\n\n## Contras\n\n- Há uma carga inicial de página mais pesada devido ao carregamento do framework, código do aplicativo e recursos necessários para várias páginas.\n- Há uma etapa adicional a ser feita no seu servidor, que é configurá-lo para rotear todas as solicitações para um único ponto de entrada e permitir que o roteamento do lado do cliente assuma a partir daí.\n- As SPAs dependem do JavaScript para renderizar conteúdo, mas nem todos os mecanismos de pesquisa executam JavaScript durante a rastreamento e podem ver conteúdo vazio em sua página. Isso prejudica inadvertidamente a otimização de mecanismos de pesquisa (SEO) do seu aplicativo. No entanto, na maioria das vezes, ao construir aplicativos, o SEO não é o fator mais importante, pois nem todo o conteúdo precisa ser indexável pelos mecanismos de pesquisa. Para contornar esse problema, você pode renderizar seu aplicativo no servidor ou usar serviços como [Prerender](https://prerender.io/) para \"renderizar seu JavaScript em um navegador, salvar o HTML estático e retorná-lo aos crawlers\".\n"
  },
  {
    "path": "questions/explain-what-a-single-page-app-is-and-how-to-make-one-seo-friendly/zh-CN.mdx",
    "content": "---\ntitle: 解释什么是单页应用程序以及如何使其对 SEO 友好\n---\n\n## TL;DR\n\n单页应用程序 (SPA) 是一种 Web 应用程序，它加载单个 HTML 页面，并在用户与应用程序交互时动态更新内容。这种方法提供了更流畅的用户体验，但对于 SEO 来说可能具有挑战性，因为搜索引擎可能不会执行 JavaScript 来呈现内容。要使 SPA 对 SEO 友好，您可以使用服务器端渲染 (SSR) 或静态站点生成 (SSG) 来确保搜索引擎可以索引您的内容。像 Next.js for React 或 Nuxt.js for Vue.js 这样的工具可以帮助实现这一点。\n\n***\n\n## 什么是单页应用程序？\n\n### 定义\n\n单页应用程序 (SPA) 是一种 Web 应用程序，它通过动态重写当前页面而不是从服务器加载整个新页面来与用户交互。这会产生更流畅的用户体验，类似于桌面应用程序。\n\n### 关键特征\n\n* 应用程序加载单个 HTML 页面，并在用户与应用程序交互时动态更新它\n* 使用 AJAX 或 Fetch API 与服务器通信并更新页面，无需完全重新加载\n* 通常依赖客户端路由来管理应用程序内的不同视图或状态\n\n### 优点\n\n* 初始加载后交互更快\n* 由于页面请求减少，服务器负载降低\n* 通过更流畅的过渡改善用户体验\n\n## 如何使 SPA 对 SEO 友好\n\n### 挑战\n\n对于 SEO 来说，SPA 具有挑战性，因为搜索引擎可能不会执行 JavaScript 来呈现内容。这可能导致搜索引擎索引一个空的或不完整的页面。\n\n### 解决方案\n\n#### 服务器端渲染 (SSR)\n\n服务器端渲染涉及在将页面发送到客户端之前在服务器上呈现页面的初始 HTML。这确保了搜索引擎可以索引完全呈现的内容。\n\n* **React**：使用 Next.js，它提供对 SSR 的内置支持\n* **Vue.js**：使用 Nuxt.js，它也支持开箱即用的 SSR\n\nNext.js 示例：\n\n```javascript\nimport React from 'react';\nimport { GetServerSideProps } from 'next';\n\nconst Page = ({ data }) => {\n  return (\n    <div>\n      <h1>{data.title}</h1>\n      <p>{data.content}</p>\n    </div>\n  );\n};\n\nexport const getServerSideProps: GetServerSideProps = async () => {\n  const res = await fetch('https://api.example.com/data');\n  const data = await res.json();\n\n  return {\n    props: {\n      data,\n    },\n  };\n};\n\nexport default Page;\n```\n\n#### 静态站点生成 (SSG)\n\n静态站点生成涉及在构建时为每个页面生成 HTML。这种方法适用于内容不经常更改的情况。\n\n* **React**：使用 Next.js 及其静态生成功能\n* **Vue.js**：使用 Nuxt.js 及其静态站点生成功能\n\nNext.js 示例：\n\n```javascript\nimport React from 'react';\nimport { GetStaticProps } from 'next';\n\nconst Page = ({ data }) => {\n  return (\n    <div>\n      <h1>{data.title}</h1>\n      <p>{data.content}</p>\n    </div>\n  );\n};\n\nexport const getStaticProps: GetStaticProps = async () => {\n  const res = await fetch('https://api.example.com/data');\n  const data = await res.json();\n\n  return {\n    props: {\n      data,\n    },\n  };\n};\n\nexport default Page;\n```\n\n#### 使用工具进行预渲染\n\n一些工具可以预渲染您的 SPA 并将预渲染的 HTML 提供给搜索引擎。\n\n* **Prerender.io**：一项预渲染您的 JavaScript 应用程序并将静态 HTML 提供给搜索引擎的服务\n* **Rendertron**：一个无头 Chrome 渲染解决方案，可用于预渲染您的 SPA\n\n## 延伸阅读\n\n* [Next.js 文档](https://nextjs.org/docs)\n* [Nuxt.js 文档](https://nuxtjs.org/docs)\n* [Prerender.io](https://prerender.io/)\n* [Rendertron](https://github.com/GoogleChrome/rendertron)\n"
  },
  {
    "path": "questions/explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"35c13a17\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"4d121f85\",\n        \"2a7816d0\",\n        \"fff110b0\",\n        \"ea3ed444\",\n        \"a715cecb\",\n        \"19a9f610\",\n        \"6613b3bd\",\n        \"77c6f040\",\n        \"87561c27\",\n        \"4bd5d872\",\n        \"19446346\",\n        \"fc4dacf3\",\n        \"1d39369a\",\n        \"f4eec989\",\n        \"ae769b85\",\n        \"1f4770e5\",\n        \"b0878d66\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4d121f85\",\n        \"2a7816d0\",\n        \"fff110b0\",\n        \"ea3ed444\",\n        \"a715cecb\",\n        \"19a9f610\",\n        \"6613b3bd\",\n        \"77c6f040\",\n        \"87561c27\",\n        \"4bd5d872\",\n        \"19446346\",\n        \"fc4dacf3\",\n        \"1d39369a\",\n        \"f4eec989\",\n        \"ae769b85\",\n        \"1f4770e5\",\n        \"b0878d66\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife/en-US.mdx",
    "content": "---\ntitle: \"Explain why the following doesn't work as an IIFE: `function foo(){}();`. What needs to be changed to properly make it an IIFE?\"\n---\n\n## TL;DR\n\nThe code `function foo(){}();` doesn't work as an Immediately Invoked Function Expression (IIFE) because the JavaScript parser treats `function foo(){}` as a function declaration, not an expression. To make it an IIFE, you need to wrap the function in parentheses to turn it into a function expression: `(function foo(){})();`.\n\n---\n\n## Why the code doesn't work as an IIFE\n\n### Function declaration vs. function expression\n\nIn JavaScript, a function declaration and a function expression are treated differently by the parser. The code `function foo(){}` is interpreted as a function declaration. Function declarations are not immediately invoked; they are hoisted to the top of their scope and can be called later in the code.\n\n### Syntax error\n\nWhen you try to immediately invoke a function declaration by adding `();` at the end, it results in a syntax error because the parser expects a function expression to be invoked immediately, not a declaration.\n\n## How to properly make it an IIFE\n\n### Wrapping in parentheses\n\nTo convert the function declaration into a function expression, you need to wrap the function declaration in parentheses. This tells the JavaScript parser to treat it as an expression. Here is the corrected code:\n\n```javascript\n(function foo(){})();\n```\n\n### Alternative syntax\n\nYou can also use an alternative syntax by placing the parentheses around the original line:\n\n```javascript\n(function foo(){}());\n```\n\nBoth of these syntaxes are valid and will correctly create an IIFE.\n\n## Further reading\n\n- [MDN Web Docs: IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)\n- [JavaScript Function Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)\n- [JavaScript Function Declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)\n"
  },
  {
    "path": "questions/explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife/metadata.json",
    "content": "{\n  \"slug\": \"explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": false,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife/pt-BR.mdx",
    "content": "---\ntitle: 'Explique porque o seguinte não funciona como um IIFE: `function foo(){ }();`. O que precisa ser alterado para torná-lo corretamente um IIFE?'\n---\n\nIIFE significa expressões de função imediatamente invocadas. O interpretador JavaScript lê `function foo(){ }();` como `function foo(){ }` e `();`, onde o primeiro é uma declaração de função e o último (um par de parênteses) é uma tentativa de chamar uma função, mas não há nome especificado, portanto, ele retorna `Uncaught SyntaxError: Unexpected token )`.\n\nAqui estão duas maneiras de corrigir que envolve a adição de mais parênteses: `(function foo(){ })()` e `(function foo(){ }())`. Declarações que começam com `function` são consideradas como _function declarations_ ao envolver essa função dentro de `()`, ela se torna uma _function expression_ que pode ser executada com o `()` subsequente. Essas funções não são expostas no escopo global e você pode até omitir o nome delas se não precisar fazer referência a si mesmas dentro do corpo.\n\nVocê também pode usar o operador `void`: `void function foo(){ }();`. Infelizmente, há um problema com essa abordagem. A avaliação da expressão fornecida é sempre undefined, então, se sua função IIFE retornar algo, você não poderá usá-la. Um exemplo:\n\n```js\nconst foo = void (function bar() {\n  return 'foo';\n})();\n\nconsole.log(foo); // indefinido\n```\n"
  },
  {
    "path": "questions/explain-why-the-following-doesnt-work-as-an-iife-function-foo--what-needs-to-be-changed-to-properly-make-it-an-iife/zh-CN.mdx",
    "content": "---\ntitle: '解释为什么以下代码不能作为 IIFE 工作：`function foo(){}();`。需要更改什么才能使其成为一个正确的 IIFE？'\n---\n\n## TL;DR\n\n代码 `function foo(){}();` 不能作为立即调用函数表达式 (IIFE) 工作，因为 JavaScript 解析器将 `function foo(){}` 视为函数声明，而不是表达式。要使其成为 IIFE，你需要将函数用括号括起来，将其转换为函数表达式：`(function foo(){})();`。\n\n***\n\n## 为什么代码不能作为 IIFE 工作\n\n### 函数声明 vs. 函数表达式\n\n在 JavaScript 中，函数声明和函数表达式被解析器区别对待。代码 `function foo(){}` 被解释为函数声明。函数声明不会立即调用；它们会被提升到其作用域的顶部，并且可以在代码的后面调用。\n\n### 语法错误\n\n当你尝试通过在末尾添加 `();` 来立即调用函数声明时，会导致语法错误，因为解析器期望立即调用函数表达式，而不是声明。\n\n## 如何正确地将其制作为 IIFE\n\n### 用括号括起来\n\n要将函数声明转换为函数表达式，你需要将函数声明用括号括起来。这告诉 JavaScript 解析器将其视为一个表达式。以下是更正后的代码：\n\n```javascript\n(function foo(){})();\n```\n\n### 替代语法\n\n你也可以使用替代语法，将括号放在原始行周围：\n\n```javascript\n(function foo(){}());\n```\n\n这两种语法都是有效的，并且将正确地创建 IIFE。\n\n## 延伸阅读\n\n* [MDN Web Docs: IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE)\n* [JavaScript Function Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)\n* [JavaScript Function Declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)\n"
  },
  {
    "path": "questions/how-can-closures-be-used-to-create-private-variables/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"cb9cfc50\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"638551f9\",\n        \"2fa59015\",\n        \"2a7816d0\",\n        \"90c7d505\",\n        \"e71ffef0\",\n        \"5ee31a12\",\n        \"6f1a231\",\n        \"a8147b5f\",\n        \"9bd8967b\",\n        \"9b5019f0\",\n        \"193e6095\",\n        \"244a3088\",\n        \"2deb5771\",\n        \"9e55773d\",\n        \"2819c383\",\n        \"71bb9ada\",\n        \"1f4770e5\",\n        \"a51a8ee2\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"638551f9\",\n        \"2fa59015\",\n        \"2a7816d0\",\n        \"90c7d505\",\n        \"e71ffef0\",\n        \"5ee31a12\",\n        \"6f1a231\",\n        \"a8147b5f\",\n        \"9bd8967b\",\n        \"9b5019f0\",\n        \"193e6095\",\n        \"244a3088\",\n        \"2deb5771\",\n        \"9e55773d\",\n        \"2819c383\",\n        \"71bb9ada\",\n        \"1f4770e5\",\n        \"a51a8ee2\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-can-closures-be-used-to-create-private-variables/en-US.mdx",
    "content": "---\ntitle: How can closures be used to create private variables?\n---\n\n## TL;DR\n\nClosures in JavaScript can be used to create private variables by defining a function within another function. The inner function has access to the outer function's variables, but those variables are not accessible from outside the outer function. This allows you to encapsulate and protect the variables from being accessed or modified directly.\n\n```js live\nfunction createCounter() {\n  let count = 0; // private variable\n\n  return {\n    increment: function () {\n      count++;\n      return count;\n    },\n    decrement: function () {\n      count--;\n      return count;\n    },\n    getCount: function () {\n      return count;\n    },\n  };\n}\n\nconst counter = createCounter();\nconsole.log(counter.increment()); // 1\nconsole.log(counter.getCount()); // 1\nconsole.log(counter.count); // undefined\n```\n\n---\n\n## How can closures be used to create private variables?\n\n### Understanding closures\n\nA closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function's variables. This includes:\n\n- Variables declared within the outer function's scope\n- Parameters of the outer function\n- Variables from the global scope\n\n### Creating private variables\n\nTo create private variables using closures, you can define a function that returns an object containing methods. These methods can access and modify the private variables, but the variables themselves are not accessible from outside the function.\n\n### Example\n\nHere's a detailed example to illustrate how closures can be used to create private variables:\n\n```js live\nfunction createCounter() {\n  let count = 0; // private variable\n\n  return {\n    increment: function () {\n      count++;\n      return count;\n    },\n    decrement: function () {\n      count--;\n      return count;\n    },\n    getCount: function () {\n      return count;\n    },\n  };\n}\n\nconst counter = createCounter();\nconsole.log(counter.increment()); // 1\nconsole.log(counter.increment()); // 2\nconsole.log(counter.decrement()); // 1\nconsole.log(counter.getCount()); // 1\nconsole.log(counter.count); // undefined\n```\n\n### Explanation\n\n1. **Outer function**: `createCounter` is the outer function that defines a private variable `count`.\n2. **Inner functions**: The object returned by `createCounter` contains methods (`increment`, `decrement`, and `getCount`) that form closures. These methods have access to the `count` variable.\n3. **Encapsulation**: The `count` variable is not accessible directly from outside the `createCounter` function. It can only be accessed and modified through the methods provided.\n\n### Benefits\n\n- **Encapsulation**: Private variables help in encapsulating the state and behavior of an object, preventing unintended interference.\n- **Data integrity**: By restricting direct access to variables, you can ensure that they are modified only through controlled methods.\n\n## Further reading\n\n- [MDN Web Docs: Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n- [JavaScript.info: Closures](https://javascript.info/closure)\n- [Eloquent JavaScript: Functions and Closures](https://eloquentjavascript.net/03_functions.html#h_jxlmhe5yFI)\n"
  },
  {
    "path": "questions/how-can-closures-be-used-to-create-private-variables/metadata.json",
    "content": "{\n  \"slug\": \"how-can-closures-be-used-to-create-private-variables\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"closure\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Closures & Scope\"\n}\n"
  },
  {
    "path": "questions/how-can-closures-be-used-to-create-private-variables/zh-CN.mdx",
    "content": "---\ntitle: 如何使用闭包创建私有变量？\n---\n\n## TL;DR\n\nJavaScript 中的闭包可以通过在另一个函数中定义一个函数来创建私有变量。内部函数可以访问外部函数的变量，但这些变量无法从外部函数外部访问。这允许您封装和保护变量，防止它们被直接访问或修改。\n\n```js live\nfunction createCounter() {\n  let count = 0; // private variable\n\n  return {\n    increment: function () {\n      count++;\n      return count;\n    },\n    decrement: function () {\n      count--;\n      return count;\n    },\n    getCount: function () {\n      return count;\n    },\n  };\n}\n\nconst counter = createCounter();\nconsole.log(counter.increment()); // 1\nconsole.log(counter.getCount()); // 1\nconsole.log(counter.count); // undefined\n```\n\n***\n\n## 如何使用闭包创建私有变量？\n\n### 了解闭包\n\n闭包是 JavaScript 中的一个特性，其中内部函数可以访问外部（封闭）函数的变量。这包括：\n\n* 在外部函数作用域内声明的变量\n* 外部函数的参数\n* 来自全局作用域的变量\n\n### 创建私有变量\n\n要使用闭包创建私有变量，您可以定义一个返回包含方法的对象的函数。这些方法可以访问和修改私有变量，但变量本身无法从函数外部访问。\n\n### 示例\n\n这是一个详细的示例，说明如何使用闭包创建私有变量：\n\n```js live\nfunction createCounter() {\n  let count = 0; // private variable\n\n  return {\n    increment: function () {\n      count++;\n      return count;\n    },\n    decrement: function () {\n      count--;\n      return count;\n    },\n    getCount: function () {\n      return count;\n    },\n  };\n}\n\nconst counter = createCounter();\nconsole.log(counter.increment()); // 1\nconsole.log(counter.increment()); // 2\nconsole.log(counter.decrement()); // 1\nconsole.log(counter.getCount()); // 1\nconsole.log(counter.count); // undefined\n```\n\n### 解释\n\n1. **外部函数**：`createCounter` 是定义私有变量 `count` 的外部函数。\n2. **内部函数**：`createCounter` 返回的对象包含形成闭包的方法（`increment`、`decrement` 和 `getCount`）。这些方法可以访问 `count` 变量。\n3. **封装**：`count` 变量无法直接从 `createCounter` 函数外部访问。它只能通过提供的方法进行访问和修改。\n\n### 优点\n\n* **封装**：私有变量有助于封装对象的状态和行为，防止意外干扰。\n* **数据完整性**：通过限制对变量的直接访问，您可以确保它们仅通过受控方法进行修改。\n\n## 延伸阅读\n\n* [MDN Web Docs: Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n* [JavaScript.info: Closures](https://javascript.info/closure)\n* [Eloquent JavaScript: Functions and Closures](https://eloquentjavascript.net/03_functions.html#h_jxlmhe5yFI)\n"
  },
  {
    "path": "questions/how-can-you-avoid-problems-related-to-hoisting/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"cab6c24d\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"1dec1891\",\n        \"e24c7c03\",\n        \"2a7816d0\",\n        \"cef60fa1\",\n        \"809fb48e\",\n        \"6fde55e0\",\n        \"c5534a15\",\n        \"8140b131\",\n        \"4ff37942\",\n        \"23bf8661\",\n        \"47194317\",\n        \"379ca7a1\",\n        \"d71d5ff8\",\n        \"3cdf6c68\",\n        \"53fa9c61\",\n        \"8810ed0d\",\n        \"eb39de0f\",\n        \"71a7f690\",\n        \"1f4770e5\",\n        \"cca0e26d\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"1dec1891\",\n        \"e24c7c03\",\n        \"2a7816d0\",\n        \"cef60fa1\",\n        \"809fb48e\",\n        \"6fde55e0\",\n        \"c5534a15\",\n        \"8140b131\",\n        \"4ff37942\",\n        \"23bf8661\",\n        \"47194317\",\n        \"379ca7a1\",\n        \"d71d5ff8\",\n        \"3cdf6c68\",\n        \"53fa9c61\",\n        \"8810ed0d\",\n        \"eb39de0f\",\n        \"71a7f690\",\n        \"1f4770e5\",\n        \"cca0e26d\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-can-you-avoid-problems-related-to-hoisting/en-US.mdx",
    "content": "---\ntitle: How can you avoid problems related to hoisting?\n---\n\n## TL;DR\n\nTo avoid problems related to hoisting, always declare variables at the top of their scope using `let` or `const` instead of `var`. This ensures that variables are block-scoped and not hoisted to the top of their containing function or global scope. Additionally, declare functions before they are called to avoid issues with function hoisting.\n\n```js live\n// Use let or const\nlet x = 10;\nconst y = 20;\nconsole.log(x, y); // Output: 10 20\n\n// Declare functions before calling them\nfunction myFunction() {\n  console.log('Hello, world!');\n}\nmyFunction(); // Output: 'Hello, world!'\n```\n\n---\n\n## How can you avoid problems related to hoisting?\n\n### Understand hoisting\n\nHoisting is JavaScript's default behavior of moving declarations to the top of the current scope (script or function). This can lead to unexpected results if not properly managed.\n\n### Use `let` and `const` instead of `var`\n\n`let` and `const` are block-scoped, meaning they are only accessible within the block they are defined. This prevents them from being hoisted to the top of the function or global scope, reducing the risk of unexpected behavior.\n\n```js live\nconsole.log(x); // undefined. (Hoisted but uninitialized, risk of unexpected behavior)\nconsole.log(y); // ReferenceError: Cannot access 'y' before initialization. (Not hoisted)\nconsole.log(z); // ReferenceError: Cannot access 'z' before initialization. (Not hoisted)\n\n// Avoid using var\nvar x = 10; // Hoisted to the top of the function or global scope\n\n// Use let or const\nlet y = 20; // Block-scoped, not hoisted to the top\nconst z = 30; // Block-scoped, not hoisted to the top\n```\n\n### Declare variables at the top of their scope\n\nTo avoid confusion and potential errors, always declare your variables at the top of their scope. This makes it clear where the variables are coming from and ensures they are initialized before use.\n\n```js live\nfunction example() {\n  let a = 1;\n  const b = 2;\n\n  // Now use a and b\n  console.log(a + b);\n}\nexample(); // Output: 3\n```\n\n### Declare functions before calling them\n\nFunction declarations are hoisted, but function expressions are not. To avoid issues, always declare functions before calling them.\n\n```js live\n// Function declaration (hoisted)\nfunction myFunction() {\n  console.log('Hello, world!');\n}\nmyFunction(); // No issues here\n\n// Function expression (not hoisted)\nconst anotherFunction = function () {\n  console.log('Hello again!');\n};\nanotherFunction(); // No issues here\n```\n\n### Avoid using undeclared variables\n\nUsing undeclared variables can lead to unexpected behavior due to hoisting. Always declare your variables before using them.\n\n```js live\n// Avoid this\nfunction badExample() {\n  x = 10; // ReferenceError in strict mode\n  console.log(x);\n}\n\n// Do this instead\nfunction goodExample() {\n  let x = 10; // x is declared\n  console.log(x);\n}\n\ngoodExample();\nbadExample();\n```\n\n## Further reading\n\n- [MDN Web Docs: Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)\n- [MDN Web Docs: var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)\n- [MDN Web Docs: let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)\n- [MDN Web Docs: const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)\n"
  },
  {
    "path": "questions/how-can-you-avoid-problems-related-to-hoisting/metadata.json",
    "content": "{\n  \"slug\": \"how-can-you-avoid-problems-related-to-hoisting\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Hoisting\"\n}\n"
  },
  {
    "path": "questions/how-can-you-avoid-problems-related-to-hoisting/zh-CN.mdx",
    "content": "---\ntitle: 如何避免与变量提升相关的问题？\n---\n\n## TL;DR\n\n为了避免与变量提升相关的问题，请始终在作用域顶部使用 `let` 或 `const` 声明变量，而不是 `var`。 这可以确保变量是块作用域的，并且不会被提升到包含函数或全局作用域的顶部。 此外，在调用函数之前声明函数，以避免函数提升问题。\n\n```js live\n// Use let or const\nlet x = 10;\nconst y = 20;\nconsole.log(x, y); // Output: 10 20\n\n// Declare functions before calling them\nfunction myFunction() {\n  console.log('Hello, world!');\n}\nmyFunction(); // Output: 'Hello, world!'\n```\n\n***\n\n## 如何避免与变量提升相关的问题？\n\n### 了解变量提升\n\n变量提升是 JavaScript 将声明移至当前作用域（脚本或函数）顶部的默认行为。 如果管理不当，这可能会导致意外结果。\n\n### 使用 `let` 和 `const` 而不是 `var`\n\n`let` 和 `const` 是块作用域的，这意味着它们只能在定义它们的块中访问。 这可以防止它们被提升到函数或全局作用域的顶部，从而降低意外行为的风险。\n\n```js live\nconsole.log(x); // undefined. (Hoisted but uninitialized, risk of unexpected behavior)\nconsole.log(y); // ReferenceError: Cannot access 'y' before initialization. (Not hoisted)\nconsole.log(z); // ReferenceError: Cannot access 'z' before initialization. (Not hoisted)\n\n// Avoid using var\nvar x = 10; // Hoisted to the top of the function or global scope\n\n// Use let or const\nlet y = 20; // Block-scoped, not hoisted to the top\nconst z = 30; // Block-scoped, not hoisted to the top\n```\n\n### 在变量作用域的顶部声明变量\n\n为了避免混淆和潜在的错误，请始终在变量的作用域顶部声明变量。 这样可以清楚地说明变量的来源，并确保它们在使用前已初始化。\n\n```js live\nfunction example() {\n  let a = 1;\n  const b = 2;\n\n  // Now use a and b\n  console.log(a + b);\n}\nexample(); // Output: 3\n```\n\n### 在调用函数之前声明它们\n\n函数声明会被提升，但函数表达式不会。 为了避免出现问题，请始终在调用函数之前声明它们。\n\n```js live\n// Function declaration (hoisted)\nfunction myFunction() {\n  console.log('Hello, world!');\n}\nmyFunction(); // No issues here\n\n// Function expression (not hoisted)\nconst anotherFunction = function () {\n  console.log('Hello again!');\n};\nanotherFunction(); // No issues here\n```\n\n### 避免使用未声明的变量\n\n由于变量提升，使用未声明的变量可能会导致意外行为。 始终在使用变量之前声明它们。\n\n```js live\n// Avoid this\nfunction badExample() {\n  x = 10; // ReferenceError in strict mode\n  console.log(x);\n}\n\n// Do this instead\nfunction goodExample() {\n  let x = 10; // x is declared\n  console.log(x);\n}\n\ngoodExample();\nbadExample();\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)\n* [MDN Web Docs: var](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)\n* [MDN Web Docs: let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)\n* [MDN Web Docs: const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)\n"
  },
  {
    "path": "questions/how-can-you-create-custom-error-objects/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"ee312c2b\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"f508916b\",\n        \"88e52ef1\",\n        \"2a7816d0\",\n        \"9c7ddb56\",\n        \"83b881aa\",\n        \"1acc01cf\",\n        \"13fe1080\",\n        \"1745a880\",\n        \"befc42d8\",\n        \"d0b48bc5\",\n        \"3294d215\",\n        \"a1142c37\",\n        \"cfbb8b18\",\n        \"77590104\",\n        \"a87cc2bb\",\n        \"475e1dfb\",\n        \"1f4770e5\",\n        \"67003490\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"f508916b\",\n        \"88e52ef1\",\n        \"2a7816d0\",\n        \"9c7ddb56\",\n        \"83b881aa\",\n        \"1acc01cf\",\n        \"13fe1080\",\n        \"1745a880\",\n        \"befc42d8\",\n        \"d0b48bc5\",\n        \"3294d215\",\n        \"a1142c37\",\n        \"cfbb8b18\",\n        \"77590104\",\n        \"a87cc2bb\",\n        \"475e1dfb\",\n        \"1f4770e5\",\n        \"67003490\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-can-you-create-custom-error-objects/en-US.mdx",
    "content": "---\ntitle: How can you create custom error objects?\n---\n\n## TL;DR\n\nTo create custom error objects in JavaScript, you can extend the built-in `Error` class. This allows you to add custom properties and methods to your error objects. Here's a quick example:\n\n```js live\nclass CustomError extends Error {\n  constructor(message) {\n    super(message);\n    this.name = 'CustomError';\n  }\n}\n\ntry {\n  throw new CustomError('This is a custom error message');\n} catch (error) {\n  console.log(error.name); // CustomError\n  console.log(error.message); // This is a custom error message\n}\n```\n\n---\n\n## How can you create custom error objects?\n\n### Extending the `Error` class\n\nTo create a custom error object, you can extend the built-in `Error` class. This allows you to inherit the properties and methods of the `Error` class while adding your own custom properties and methods.\n\n```js\nclass CustomError extends Error {\n  constructor(message) {\n    super(message);\n    this.name = 'CustomError';\n  }\n}\n```\n\n### Adding custom properties\n\nYou can add custom properties to your custom error class to provide more context about the error.\n\n```js live\nclass CustomError extends Error {\n  constructor(message, errorCode) {\n    super(message);\n    this.name = 'CustomError';\n    this.errorCode = errorCode;\n  }\n}\n\ntry {\n  throw new CustomError('This is a custom error message', 404);\n} catch (error) {\n  console.log(error.name); // CustomError\n  console.log(error.message); // This is a custom error message\n  console.log(error.errorCode); // 404\n}\n```\n\n### Custom methods\n\nYou can also add custom methods to your custom error class to handle specific error-related logic.\n\n```js live\nclass CustomError extends Error {\n  constructor(message, errorCode) {\n    super(message);\n    this.name = 'CustomError';\n    this.errorCode = errorCode;\n  }\n\n  logError() {\n    console.error(`${this.name} [${this.errorCode}]: ${this.message}`);\n  }\n}\n\ntry {\n  throw new CustomError('This is a custom error message', 404);\n} catch (error) {\n  error.logError(); // CustomError [404]: This is a custom error message\n}\n```\n\n### Using `instanceof` to check for custom errors\n\nYou can use the `instanceof` operator to check if an error is an instance of your custom error class.\n\n```js live\nclass CustomError extends Error {\n  constructor(message, errorCode) {\n    super(message);\n    this.name = 'CustomError';\n    this.errorCode = errorCode;\n  }\n}\n\ntry {\n  throw new CustomError('This is a custom error message', 404);\n} catch (error) {\n  if (error instanceof CustomError) {\n    console.log('Caught a CustomError');\n  } else {\n    console.log('Caught a different type of error');\n  }\n}\n```\n\n## Further reading\n\n- [MDN Web Docs: Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)\n- [MDN Web Docs: Extending built-in classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#subclassing_built-in_classes)\n- [JavaScript.info: Custom errors](https://javascript.info/custom-errors)\n"
  },
  {
    "path": "questions/how-can-you-create-custom-error-objects/metadata.json",
    "content": "{\n  \"slug\": \"how-can-you-create-custom-error-objects\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Error Handling\"\n}\n"
  },
  {
    "path": "questions/how-can-you-create-custom-error-objects/zh-CN.mdx",
    "content": "---\ntitle: 如何创建自定义错误对象？\n---\n\n## TL;DR\n\n要在 JavaScript 中创建自定义错误对象，您可以扩展内置的 `Error` 类。 这允许您向错误对象添加自定义属性和方法。 这是一个快速示例：\n\n```js live\nclass CustomError extends Error {\n  constructor(message) {\n    super(message);\n    this.name = 'CustomError';\n  }\n}\n\ntry {\n  throw new CustomError('This is a custom error message');\n} catch (error) {\n  console.log(error.name); // CustomError\n  console.log(error.message); // This is a custom error message\n}\n```\n\n***\n\n## 如何创建自定义错误对象？\n\n### 扩展 `Error` 类\n\n要创建自定义错误对象，您可以扩展内置的 `Error` 类。 这允许您继承 `Error` 类的属性和方法，同时添加您自己的自定义属性和方法。\n\n```js\nclass CustomError extends Error {\n  constructor(message) {\n    super(message);\n    this.name = 'CustomError';\n  }\n}\n```\n\n### 添加自定义属性\n\n您可以向自定义错误类添加自定义属性，以提供有关错误的更多上下文。\n\n```js live\nclass CustomError extends Error {\n  constructor(message, errorCode) {\n    super(message);\n    this.name = 'CustomError';\n    this.errorCode = errorCode;\n  }\n}\n\ntry {\n  throw new CustomError('This is a custom error message', 404);\n} catch (error) {\n  console.log(error.name); // CustomError\n  console.log(error.message); // This is a custom error message\n  console.log(error.errorCode); // 404\n}\n```\n\n### 自定义方法\n\n您还可以向自定义错误类添加自定义方法来处理特定的错误相关逻辑。\n\n```js live\nclass CustomError extends Error {\n  constructor(message, errorCode) {\n    super(message);\n    this.name = 'CustomError';\n    this.errorCode = errorCode;\n  }\n\n  logError() {\n    console.error(`${this.name} [${this.errorCode}]: ${this.message}`);\n  }\n}\n\ntry {\n  throw new CustomError('This is a custom error message', 404);\n} catch (error) {\n  error.logError(); // CustomError [404]: This is a custom error message\n}\n```\n\n### 使用 `instanceof` 检查自定义错误\n\n您可以使用 `instanceof` 运算符来检查错误是否是您的自定义错误类的实例。\n\n```js live\nclass CustomError extends Error {\n  constructor(message, errorCode) {\n    super(message);\n    this.name = 'CustomError';\n    this.errorCode = errorCode;\n  }\n}\n\ntry {\n  throw new CustomError('This is a custom error message', 404);\n} catch (error) {\n  if (error instanceof CustomError) {\n    console.log('Caught a CustomError');\n  } else {\n    console.log('Caught a different type of error');\n  }\n}\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)\n* [MDN Web Docs: Extending built-in classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#subclassing_built-in_classes)\n* [JavaScript.info: Custom errors](https://javascript.info/custom-errors)\n"
  },
  {
    "path": "questions/how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"5092b247\",\n        \"2a7816d0\",\n        \"e6136bea\",\n        \"c3a9a22a\",\n        \"21dc1205\",\n        \"711730f0\",\n        \"a6561702\",\n        \"8f40557f\",\n        \"cb53abeb\",\n        \"16fef52f\",\n        \"ea975acc\",\n        \"9ad3f1de\",\n        \"5a325cbc\",\n        \"a45ac085\",\n        \"c7650aab\",\n        \"7fa271b6\",\n        \"f118ce2c\",\n        \"eca84932\",\n        \"3f433d8c\",\n        \"3826dfe3\",\n        \"8c9eed30\",\n        \"f692c6c3\",\n        \"4611eb18\",\n        \"5c5ca95e\",\n        \"d7d1861f\",\n        \"525aeb8a\",\n        \"23b347d4\",\n        \"1f4770e5\",\n        \"e8fd4d88\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"5092b247\",\n        \"2a7816d0\",\n        \"e6136bea\",\n        \"c3a9a22a\",\n        \"21dc1205\",\n        \"711730f0\",\n        \"a6561702\",\n        \"8f40557f\",\n        \"cb53abeb\",\n        \"16fef52f\",\n        \"ea975acc\",\n        \"9ad3f1de\",\n        \"5a325cbc\",\n        \"a45ac085\",\n        \"c7650aab\",\n        \"7fa271b6\",\n        \"f118ce2c\",\n        \"eca84932\",\n        \"3f433d8c\",\n        \"3826dfe3\",\n        \"8c9eed30\",\n        \"f692c6c3\",\n        \"4611eb18\",\n        \"5c5ca95e\",\n        \"d7d1861f\",\n        \"525aeb8a\",\n        \"23b347d4\",\n        \"1f4770e5\",\n        \"e8fd4d88\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"e798c866\"\n  }\n}\n"
  },
  {
    "path": "questions/how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications/en-US.mdx",
    "content": "---\ntitle: How can you implement secure authentication and authorization in JavaScript applications?\n---\n\n## TL;DR\n\nTo implement secure authentication and authorization in JavaScript applications, use HTTPS to encrypt data in transit, and store sensitive data like tokens securely using `localStorage` or `sessionStorage`. Implement token-based authentication using JWTs, and validate tokens on the server side. Use libraries like OAuth for third-party authentication and ensure proper role-based access control (RBAC) for authorization.\n\n---\n\n## How can you implement secure authentication and authorization in JavaScript applications?\n\n### Use HTTPS\n\nEnsure that your application uses HTTPS to encrypt data in transit. This prevents man-in-the-middle attacks and ensures that data exchanged between the client and server is secure.\n\n### Token-based authentication\n\nUse JSON Web Tokens (JWT) for token-based authentication. JWTs are compact, URL-safe tokens that can be used to securely transmit information between parties.\n\n#### Example of generating a JWT\n\n```js\nconst jwt = require('jsonwebtoken');\n\nconst token = jwt.sign({ userId: 123 }, 'your-256-bit-secret', {\n  expiresIn: '1h',\n});\n```\n\n#### Example of verifying a JWT\n\n```js\nconst jwt = require('jsonwebtoken');\n\ntry {\n  const decoded = jwt.verify(token, 'your-256-bit-secret');\n  console.log(decoded);\n} catch (err) {\n  console.error('Invalid token');\n}\n```\n\n### Secure storage\n\nStore sensitive data like tokens securely. Use `localStorage` or `sessionStorage` for storing tokens, but be aware of their vulnerabilities. For more security, consider using HttpOnly cookies.\n\n#### Example of storing a token in `localStorage`\n\n```js\nlocalStorage.setItem('token', token);\n```\n\n#### Example of retrieving a token from `localStorage`\n\n```js\nconst token = localStorage.getItem('token');\n```\n\n### Server-side validation\n\nAlways validate tokens on the server side to ensure they are not tampered with. This adds an extra layer of security.\n\n### OAuth for third-party authentication\n\nUse OAuth for third-party authentication. Libraries like Passport.js can simplify the implementation of OAuth in your application.\n\n#### Example of using Passport.js for Google OAuth\n\n```js\nconst passport = require('passport');\nconst GoogleStrategy = require('passport-google-oauth20').Strategy;\n\npassport.use(\n  new GoogleStrategy(\n    {\n      clientID: 'YOUR_GOOGLE_CLIENT_ID',\n      clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET',\n      callbackURL: 'http://www.example.com/auth/google/callback',\n    },\n    function (accessToken, refreshToken, profile, done) {\n      User.findOrCreate({ googleId: profile.id }, function (err, user) {\n        return done(err, user);\n      });\n    },\n  ),\n);\n```\n\n### Role-based access control (RBAC)\n\nImplement role-based access control to ensure that users have the appropriate permissions to access resources.\n\n#### Example of RBAC middleware in Express.js\n\n```js\nfunction checkRole(role) {\n  return function (req, res, next) {\n    if (req.user && req.user.role === role) {\n      next();\n    } else {\n      res.status(403).send('Forbidden');\n    }\n  };\n}\n\n// Usage\napp.get('/admin', checkRole('admin'), (req, res) => {\n  res.send('Welcome, admin!');\n});\n```\n\n## Further reading\n\n- [JWT.io](https://jwt.io/)\n- [Passport.js documentation](http://www.passportjs.org/docs/)\n- [OWASP Secure Coding Practices-Quick Reference Guide](https://owasp.org/www-project-secure-coding-practices-quick-reference-guide/)\n- [MDN Web Docs on HTTPS](https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security)\n"
  },
  {
    "path": "questions/how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications/metadata.json",
    "content": "{\n  \"slug\": \"how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"advanced\",\n  \"topics\": [\"javascript\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Security\"\n}\n"
  },
  {
    "path": "questions/how-can-you-implement-secure-authentication-and-authorization-in-javascript-applications/zh-CN.mdx",
    "content": "---\ntitle: 如何在 JavaScript 应用程序中实现安全的身份验证和授权？\n---\n\n## TL;DR\n\n要在 JavaScript 应用程序中实现安全的身份验证和授权，请使用 HTTPS 加密传输中的数据，并使用 `localStorage` 或 `sessionStorage` 安全地存储令牌等敏感数据。使用 JWT 实现基于令牌的身份验证，并在服务器端验证令牌。使用 OAuth 等库进行第三方身份验证，并确保为授权使用适当的基于角色的访问控制 (RBAC)。\n\n***\n\n## 如何在 JavaScript 应用程序中实现安全的身份验证和授权？\n\n### 使用 HTTPS\n\n确保您的应用程序使用 HTTPS 加密传输中的数据。这可以防止中间人攻击，并确保客户端和服务器之间交换的数据是安全的。\n\n### 基于令牌的身份验证\n\n使用 JSON Web 令牌 (JWT) 进行基于令牌的身份验证。JWT 是紧凑的、URL 安全的令牌，可用于在各方之间安全地传输信息。\n\n#### 生成 JWT 的示例\n\n```js\nconst jwt = require('jsonwebtoken');\n\nconst token = jwt.sign({ userId: 123 }, 'your-256-bit-secret', {\n  expiresIn: '1h',\n});\n```\n\n#### 验证 JWT 的示例\n\n```js\nconst jwt = require('jsonwebtoken');\n\ntry {\n  const decoded = jwt.verify(token, 'your-256-bit-secret');\n  console.log(decoded);\n} catch (err) {\n  console.error('Invalid token');\n}\n```\n\n### 安全存储\n\n安全地存储令牌等敏感数据。使用 `localStorage` 或 `sessionStorage` 存储令牌，但要注意它们存在的漏洞。为了提高安全性，请考虑使用 HttpOnly cookie。\n\n#### 将令牌存储在 `localStorage` 中的示例\n\n```js\nlocalStorage.setItem('token', token);\n```\n\n#### 从 `localStorage` 检索令牌的示例\n\n```js\nconst token = localStorage.getItem('token');\n```\n\n### 服务器端验证\n\n始终在服务器端验证令牌，以确保它们未被篡改。这增加了额外的安全层。\n\n### 用于第三方身份验证的 OAuth\n\n使用 OAuth 进行第三方身份验证。像 Passport.js 这样的库可以简化应用程序中 OAuth 的实现。\n\n#### 使用 Passport.js 进行 Google OAuth 的示例\n\n```js\nconst passport = require('passport');\nconst GoogleStrategy = require('passport-google-oauth20').Strategy;\n\npassport.use(\n  new GoogleStrategy(\n    {\n      clientID: 'YOUR_GOOGLE_CLIENT_ID',\n      clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET',\n      callbackURL: 'http://www.example.com/auth/google/callback',\n    },\n    function (accessToken, refreshToken, profile, done) {\n      User.findOrCreate({ googleId: profile.id }, function (err, user) {\n        return done(err, user);\n      });\n    },\n  ),\n);\n```\n\n### 基于角色的访问控制 (RBAC)\n\n实施基于角色的访问控制，以确保用户拥有访问资源的适当权限。\n\n#### Express.js 中 RBAC 中间件的示例\n\n```js\nfunction checkRole(role) {\n  return function (req, res, next) {\n    if (req.user && req.user.role === role) {\n      next();\n    } else {\n      res.status(403).send('Forbidden');\n    }\n  };\n}\n\n// Usage\napp.get('/admin', checkRole('admin'), (req, res) => {\n  res.send('Welcome, admin!');\n});\n```\n\n## 延伸阅读\n\n* [JWT.io](https://jwt.io/)\n* [Passport.js documentation](http://www.passportjs.org/docs/)\n* [OWASP Secure Coding Practices-Quick Reference Guide](https://owasp.org/www-project-secure-coding-practices-quick-reference-guide/)\n* [MDN Web Docs on HTTPS](https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security)\n"
  },
  {
    "path": "questions/how-can-you-optimize-dom-manipulation-for-better-performance/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"44f2282c\",\n        \"2a7816d0\",\n        \"bfc71049\",\n        \"88060c42\",\n        \"d2b977ef\",\n        \"3d4c94ed\",\n        \"6c91fbda\",\n        \"5494e869\",\n        \"828135ce\",\n        \"cf5c3931\",\n        \"6047ba4d\",\n        \"67c16a77\",\n        \"11d27bfa\",\n        \"fb9d3d6d\",\n        \"a42d2d9\",\n        \"417ae958\",\n        \"f3f85893\",\n        \"21c6396a\",\n        \"1d560b1c\",\n        \"5248ed8e\",\n        \"46ef02ea\",\n        \"1f4770e5\",\n        \"76bbbc39\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"44f2282c\",\n        \"2a7816d0\",\n        \"bfc71049\",\n        \"88060c42\",\n        \"d2b977ef\",\n        \"3d4c94ed\",\n        \"6c91fbda\",\n        \"5494e869\",\n        \"828135ce\",\n        \"cf5c3931\",\n        \"6047ba4d\",\n        \"67c16a77\",\n        \"11d27bfa\",\n        \"fb9d3d6d\",\n        \"a42d2d9\",\n        \"417ae958\",\n        \"f3f85893\",\n        \"21c6396a\",\n        \"1d560b1c\",\n        \"5248ed8e\",\n        \"46ef02ea\",\n        \"1f4770e5\",\n        \"76bbbc39\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"41e3c3c2\"\n  }\n}\n"
  },
  {
    "path": "questions/how-can-you-optimize-dom-manipulation-for-better-performance/en-US.mdx",
    "content": "---\ntitle: How can you optimize DOM manipulation for better performance?\n---\n\n## TL;DR\n\nTo optimize DOM manipulation for better performance, minimize direct DOM access and updates. Use techniques like batching DOM changes, using `documentFragment` for multiple elements, and leveraging virtual DOM libraries like React. Also, consider using `requestAnimationFrame` for animations and avoid layout thrashing by reading and writing DOM properties separately.\n\n---\n\n## How can you optimize DOM manipulation for better performance?\n\n### Minimize direct DOM access\n\nAccessing the DOM is relatively slow, so try to minimize the number of times you read from or write to the DOM. Instead, store references to elements in variables and work with those.\n\n```js live\n// Creating an element for the example below\nconst newElement = document.createElement('div');\nnewElement.id = 'myElement';\ndocument.body.appendChild(newElement);\n\nconst element = document.getElementById('myElement'); // Access once\n// Then use the reference to edit style\nelement.style.color = 'red';\nelement.style.backgroundColor = 'blue';\n\nconsole.log(document.body); // Notice the edits\n```\n\n### Batch DOM changes\n\nInstead of making multiple changes to the DOM one at a time, batch them together. This reduces the number of reflows and repaints.\n\n```js live\n// Creating an element for the example below\nconst newElement = document.createElement('div');\nnewElement.id = 'myElement';\ndocument.body.appendChild(newElement);\n\nconst element = document.getElementById('myElement');\nelement.style.cssText = 'color: red; background-color: blue;';\n\nconsole.log(document.body); // Notice the edits\n```\n\n### Use `documentFragment`\n\nWhen adding multiple elements to the DOM, use a `documentFragment` to minimize reflows and repaints.\n\n```js live\nconst fragment = document.createDocumentFragment();\nfor (let i = 0; i < 100; i++) {\n  const newElement = document.createElement('div');\n  newElement.textContent = `Item ${i}`;\n  fragment.appendChild(newElement);\n}\ndocument.body.appendChild(fragment);\n\nconsole.log(document.body); // Notice that the divs have been added\n```\n\n### Leverage virtual DOM libraries\n\nLibraries like React use a virtual DOM to batch updates and minimize direct DOM manipulation, which can significantly improve performance.\n\n```js\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n\nconst App = () => (\n  <div>\n    <h1>Hello, world!</h1>\n  </div>\n);\n\nReactDOM.render(<App />, document.getElementById('root'));\n```\n\n### Use `requestAnimationFrame` for animations\n\nFor smoother animations, use `requestAnimationFrame` to ensure updates are synchronized with the browser's repaint cycle.\n\n```js\nfunction animate() {\n  // Update animation state\n  requestAnimationFrame(animate);\n}\nrequestAnimationFrame(animate);\n```\n\n### Avoid layout thrashing\n\nLayout thrashing occurs when you read and write to the DOM repeatedly in a way that forces the browser to recalculate styles and layout multiple times. To avoid this, separate read and write operations.\n\n```js live\n// Creating an element for the example below\nconst newElement = document.createElement('div');\nnewElement.id = 'myElement';\ndocument.body.appendChild(newElement);\n\nconst element = document.getElementById('myElement');\nconst height = element.clientHeight; // Read\nelement.style.height = `${height + 10}px`; // Write\n```\n\n## Further reading\n\n- [FreeCodeCamp: DOM Manipulation in JavaScript](https://www.freecodecamp.org/news/dom-manipulation-in-javascript/)\n- [Google Developers: Avoid large, complex layouts and layout thrashing](https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing)\n- [React documentation](https://react.dev/learn)\n- [MDN Web Docs: Using requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)\n"
  },
  {
    "path": "questions/how-can-you-optimize-dom-manipulation-for-better-performance/metadata.json",
    "content": "{\n  \"slug\": \"how-can-you-optimize-dom-manipulation-for-better-performance\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"advanced\",\n  \"topics\": [\"web-api\", \"javascript\", \"performance\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Performance Optimization\"\n}\n"
  },
  {
    "path": "questions/how-can-you-optimize-dom-manipulation-for-better-performance/zh-CN.mdx",
    "content": "---\ntitle: 如何优化 DOM 操作以获得更好的性能？\n---\n\n## TL;DR\n\n要优化 DOM 操作以获得更好的性能，请尽量减少直接访问和更新 DOM。使用诸如批处理 DOM 更改、使用 `documentFragment` 处理多个元素以及利用 React 等虚拟 DOM 库等技术。此外，还可以考虑使用 `requestAnimationFrame` 进行动画处理，并通过分别读取和写入 DOM 属性来避免布局抖动。\n\n***\n\n## 如何优化 DOM 操作以获得更好的性能？\n\n### 尽量减少直接 DOM 访问\n\n访问 DOM 相对较慢，因此请尽量减少从 DOM 读取或写入 DOM 的次数。相反，将对元素的引用存储在变量中，并使用这些变量。\n\n```js live\n// Creating an element for the example below\nconst newElement = document.createElement('div');\nnewElement.id = 'myElement';\ndocument.body.appendChild(newElement);\n\nconst element = document.getElementById('myElement'); // Access once\n// Then use the reference to edit style\nelement.style.color = 'red';\nelement.style.backgroundColor = 'blue';\n\nconsole.log(document.body); // Notice the edits\n```\n\n### 批处理 DOM 更改\n\n不要一次对 DOM 进行多次更改，而是将它们批处理在一起。这减少了重排和重绘的次数。\n\n```js live\n// Creating an element for the example below\nconst newElement = document.createElement('div');\nnewElement.id = 'myElement';\ndocument.body.appendChild(newElement);\n\nconst element = document.getElementById('myElement');\nelement.style.cssText = 'color: red; background-color: blue;';\n\nconsole.log(document.body); // Notice the edits\n```\n\n### 使用 `documentFragment`\n\n将多个元素添加到 DOM 时，使用 `documentFragment` 以最大限度地减少重排和重绘。\n\n```js live\nconst fragment = document.createDocumentFragment();\nfor (let i = 0; i < 100; i++) {\n  const newElement = document.createElement('div');\n  newElement.textContent = `Item ${i}`;\n  fragment.appendChild(newElement);\n}\ndocument.body.appendChild(fragment);\n\nconsole.log(document.body); // Notice that the divs have been added\n```\n\n### 利用虚拟 DOM 库\n\nReact 等库使用虚拟 DOM 来批处理更新并最大限度地减少直接 DOM 操作，这可以显著提高性能。\n\n```js\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n\nconst App = () => (\n  <div>\n    <h1>Hello, world!</h1>\n  </div>\n);\n\nReactDOM.render(<App />, document.getElementById('root'));\n```\n\n### 使用 `requestAnimationFrame` 进行动画处理\n\n为了获得更流畅的动画效果，请使用 `requestAnimationFrame` 确保更新与浏览器的重绘周期同步。\n\n```js\nfunction animate() {\n  // Update animation state\n  requestAnimationFrame(animate);\n}\nrequestAnimationFrame(animate);\n```\n\n### 避免布局抖动\n\n当您以迫使浏览器多次重新计算样式和布局的方式反复读取和写入 DOM 时，就会发生布局抖动。为避免这种情况，请将读取和写入操作分开。\n\n```js live\n// Creating an element for the example below\nconst newElement = document.createElement('div');\nnewElement.id = 'myElement';\ndocument.body.appendChild(newElement);\n\nconst element = document.getElementById('myElement');\nconst height = element.clientHeight; // Read\nelement.style.height = `${height + 10}px`; // Write\n```\n\n## 延伸阅读\n\n* [FreeCodeCamp: DOM Manipulation in JavaScript](https://www.freecodecamp.org/news/dom-manipulation-in-javascript/)\n* [Google Developers: Avoid large, complex layouts and layout thrashing](https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing)\n* [React documentation](https://react.dev/learn)\n* [MDN Web Docs: Using requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)\n"
  },
  {
    "path": "questions/how-can-you-optimize-network-requests-for-better-performance/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"98bd25f4\",\n        \"2a7816d0\",\n        \"4780cd69\",\n        \"9c37698e\",\n        \"b2025924\",\n        \"7e2467ee\",\n        \"34e56c4c\",\n        \"ea55ad9a\",\n        \"ccf8b2\",\n        \"fccff875\",\n        \"3f543125\",\n        \"d731b34e\",\n        \"7c97aef3\",\n        \"45332e17\",\n        \"8abe2715\",\n        \"262c12fa\",\n        \"1e93d8a5\",\n        \"5d29152e\",\n        \"7fd1cd0\",\n        \"1ab1a4f3\",\n        \"2a39d652\",\n        \"1f4770e5\",\n        \"e643bd02\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"98bd25f4\",\n        \"2a7816d0\",\n        \"4780cd69\",\n        \"9c37698e\",\n        \"b2025924\",\n        \"7e2467ee\",\n        \"34e56c4c\",\n        \"ea55ad9a\",\n        \"ccf8b2\",\n        \"fccff875\",\n        \"3f543125\",\n        \"d731b34e\",\n        \"7c97aef3\",\n        \"45332e17\",\n        \"8abe2715\",\n        \"262c12fa\",\n        \"1e93d8a5\",\n        \"5d29152e\",\n        \"7fd1cd0\",\n        \"1ab1a4f3\",\n        \"2a39d652\",\n        \"1f4770e5\",\n        \"e643bd02\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"c8386077\"\n  }\n}\n"
  },
  {
    "path": "questions/how-can-you-optimize-network-requests-for-better-performance/en-US.mdx",
    "content": "---\ntitle: How can you optimize network requests for better performance?\n---\n\n## TL;DR\n\nTo optimize network requests for better performance, you can minimize the number of requests, use caching, compress data, and leverage modern web technologies like HTTP/2 and service workers. For example, you can combine multiple CSS files into one to reduce the number of requests, use `Cache-Control` headers to cache static assets, and enable Gzip compression on your server to reduce the size of the data being transferred.\n\n---\n\n## How can you optimize network requests for better performance?\n\n### Minimize the number of requests\n\nReducing the number of network requests can significantly improve performance. Here are some strategies:\n\n- **Combine files**: Merge multiple CSS or JavaScript files into a single file.\n- **Image sprites**: Combine multiple images into a single sprite sheet and use CSS to display the correct part of the image.\n- **Inline small assets**: Use data URIs to inline small images or fonts directly into your CSS or HTML.\n\n### Use caching\n\nCaching can reduce the need to make network requests for resources that have not changed:\n\n- **HTTP caching**: Use `Cache-Control` and `ETag` headers to control how and when resources are cached by the browser.\n- **Service workers**: Implement service workers to cache assets and API responses, allowing your app to work offline and load faster on subsequent visits.\n\n### Compress data\n\nReducing the size of the data being transferred can speed up network requests:\n\n- **Gzip/Brotli compression**: Enable Gzip or Brotli compression on your server to compress HTML, CSS, and JavaScript files.\n- **Minification**: Minify CSS, JavaScript, and HTML files to remove unnecessary characters and reduce file size.\n\n### Leverage modern web technologies\n\nModern web technologies can help optimize network performance:\n\n- **HTTP/2**: Use HTTP/2 to take advantage of multiplexing, header compression, and server push, which can reduce latency and improve load times.\n- **CDNs**: Use Content Delivery Networks (CDNs) to serve static assets from locations closer to the user, reducing latency.\n\n### Optimize images\n\nImages often account for a large portion of the data transferred:\n\n- **Responsive images**: Use the `srcset` attribute to serve different image sizes based on the user's device.\n- **Image formats**: Use modern image formats like WebP or AVIF, which offer better compression than traditional formats like JPEG or PNG.\n- **Lazy loading**: Implement lazy loading to defer loading images until they are needed.\n\n### Reduce payload size\n\nReducing the amount of data sent in each request can improve performance:\n\n- **API optimization**: Optimize API responses to include only the necessary data.\n- **GraphQL**: Use GraphQL to request only the specific data needed by the client.\n\n## Further reading\n\n- [MDN Web Docs: HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching)\n- [Google Developers: Optimizing content efficiency](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/)\n- [MDN: HTTP/2](https://developer.mozilla.org/en-US/docs/Glossary/HTTP_2)\n- [MDN Web Docs: Service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)\n- [Google Developers: Image optimization](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/image-optimization)\n"
  },
  {
    "path": "questions/how-can-you-optimize-network-requests-for-better-performance/metadata.json",
    "content": "{\n  \"slug\": \"how-can-you-optimize-network-requests-for-better-performance\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"advanced\",\n  \"topics\": [\"javascript\", \"networking\", \"performance\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Performance Optimization\"\n}\n"
  },
  {
    "path": "questions/how-can-you-optimize-network-requests-for-better-performance/zh-CN.mdx",
    "content": "---\ntitle: 如何优化网络请求以获得更好的性能？\n---\n\n## TL;DR\n\n为了优化网络请求以获得更好的性能，您可以尽量减少请求数量、使用缓存、压缩数据，并利用 HTTP/2 和 Service Worker 等现代 Web 技术。例如，您可以将多个 CSS 文件合并成一个以减少请求数量，使用 `Cache-Control` 标头缓存静态资源，并在您的服务器上启用 Gzip 压缩以减少传输的数据大小。\n\n***\n\n## 如何优化网络请求以获得更好的性能？\n\n### 尽量减少请求数量\n\n减少网络请求的数量可以显著提高性能。以下是一些策略：\n\n* **合并文件**：将多个 CSS 或 JavaScript 文件合并成一个文件。\n* **图像精灵**：将多个图像合并成一个精灵表，并使用 CSS 显示图像的正确部分。\n* **内联小资源**：使用数据 URI 将小图像或字体直接内联到您的 CSS 或 HTML 中。\n\n### 使用缓存\n\n缓存可以减少对尚未更改的资源进行网络请求的需求：\n\n* **HTTP 缓存**：使用 `Cache-Control` 和 `ETag` 标头来控制浏览器缓存资源的方式和时间。\n* **Service Worker**：实现 Service Worker 来缓存资源和 API 响应，允许您的应用程序离线工作，并在后续访问时更快地加载。\n\n### 压缩数据\n\n减少传输的数据大小可以加速网络请求：\n\n* **Gzip/Brotli 压缩**：在您的服务器上启用 Gzip 或 Brotli 压缩以压缩 HTML、CSS 和 JavaScript 文件。\n* **最小化**：最小化 CSS、JavaScript 和 HTML 文件以删除不必要的字符并减小文件大小。\n\n### 利用现代 Web 技术\n\n现代 Web 技术可以帮助优化网络性能：\n\n* **HTTP/2**：使用 HTTP/2 来利用多路复用、标头压缩和服务器推送，这可以减少延迟并提高加载时间。\n* **CDN**：使用内容分发网络 (CDN) 从更靠近用户的位置提供静态资源，从而减少延迟。\n\n### 优化图像\n\n图像通常占用了很大一部分已传输的数据：\n\n* **响应式图像**：使用 `srcset` 属性根据用户的设备提供不同的图像大小。\n* **图像格式**：使用现代图像格式，如 WebP 或 AVIF，它们比 JPEG 或 PNG 等传统格式提供更好的压缩。\n* **懒加载**：实现懒加载以推迟加载图像，直到需要它们。\n\n### 减少有效负载大小\n\n减少每个请求中发送的数据量可以提高性能：\n\n* **API 优化**：优化 API 响应，仅包含必要的数据。\n* **GraphQL**：使用 GraphQL 仅请求客户端所需的数据。\n\n## 延伸阅读\n\n* [MDN Web Docs: HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching)\n* [Google Developers: Optimizing content efficiency](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/)\n* [MDN: HTTP/2](https://developer.mozilla.org/en-US/docs/Glossary/HTTP_2)\n* [MDN Web Docs: Service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)\n* [Google Developers: Image optimization](https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/image-optimization)\n"
  },
  {
    "path": "questions/how-can-you-prevent-clickjacking-attacks/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"722ba670\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"cf69a850\",\n        \"fbbc8b6e\",\n        \"d2a4f12b\",\n        \"2a7816d0\",\n        \"6ad936a2\",\n        \"cbb8d7bb\",\n        \"307b535d\",\n        \"30f8fee0\",\n        \"5f9a4064\",\n        \"45b272a8\",\n        \"e76b9a8\",\n        \"fbbc8b6e\",\n        \"64a91812\",\n        \"17402b8\",\n        \"e76b9a8\",\n        \"d2a4f12b\",\n        \"7da0887f\",\n        \"e76b9a8\",\n        \"68d3a59d\",\n        \"d8c3445e\",\n        \"1538d6fc\",\n        \"e76b9a8\",\n        \"3d0b6f3\",\n        \"1f4770e5\",\n        \"a3e41a8a\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"cf69a850\",\n        \"fbbc8b6e\",\n        \"d2a4f12b\",\n        \"2a7816d0\",\n        \"6ad936a2\",\n        \"cbb8d7bb\",\n        \"307b535d\",\n        \"30f8fee0\",\n        \"5f9a4064\",\n        \"45b272a8\",\n        \"e76b9a8\",\n        \"fbbc8b6e\",\n        \"64a91812\",\n        \"17402b8\",\n        \"e76b9a8\",\n        \"d2a4f12b\",\n        \"7da0887f\",\n        \"e76b9a8\",\n        \"68d3a59d\",\n        \"d8c3445e\",\n        \"1538d6fc\",\n        \"e76b9a8\",\n        \"3d0b6f3\",\n        \"1f4770e5\",\n        \"a3e41a8a\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-can-you-prevent-clickjacking-attacks/en-US.mdx",
    "content": "---\ntitle: How can you prevent clickjacking attacks?\n---\n\n## TL;DR\n\nTo prevent clickjacking attacks, you can use the `X-Frame-Options` HTTP header to control whether your site can be embedded in iframes. Set it to `DENY` to prevent all framing, or `SAMEORIGIN` to allow framing only from the same origin. Additionally, you can use the `Content-Security-Policy` (CSP) header with the `frame-ancestors` directive to specify which origins are allowed to frame your content.\n\n```http\nX-Frame-Options: DENY\n```\n\n```http\nContent-Security-Policy: frame-ancestors 'self'\n```\n\n---\n\n## What is clickjacking?\n\nClickjacking is a type of attack where a malicious site tricks users into clicking on something different from what the user perceives, potentially leading to unauthorized actions or information disclosure. This is often achieved by embedding the target site in an invisible iframe and overlaying it with deceptive content.\n\n## How to prevent clickjacking attacks\n\n### Using the `X-Frame-Options` header\n\nThe `X-Frame-Options` HTTP header can be used to control whether a browser should be allowed to render a page in a `<frame>`, `<iframe>`, `<embed>`, or `<object>`. This header has three possible values:\n\n- `DENY`: Prevents the page from being displayed in a frame, regardless of the site attempting to do so.\n- `SAMEORIGIN`: Allows the page to be displayed in a frame on the same origin as the page itself.\n- `ALLOW-FROM uri`: Allows the page to be displayed in a frame only on the specified origin.\n\nExample:\n\n```http\nX-Frame-Options: DENY\n```\n\n### Using the `Content-Security-Policy` header\n\nThe `Content-Security-Policy` (CSP) header provides a more flexible and modern approach to prevent clickjacking. The `frame-ancestors` directive specifies valid parents that may embed a page using `<frame>`, `<iframe>`, `<object>`, `<embed>`, or `<applet>` tags.\n\nExample:\n\n```http\nContent-Security-Policy: frame-ancestors 'self'\n```\n\nThis directive can also specify multiple origins or use wildcards for more complex scenarios.\n\nExample:\n\n```http\nContent-Security-Policy: frame-ancestors 'self' https://trusted.com\n```\n\n### Combining both headers\n\nFor maximum compatibility and security, it is recommended to use both `X-Frame-Options` and `Content-Security-Policy` headers together.\n\nExample:\n\n```http\nX-Frame-Options: SAMEORIGIN\nContent-Security-Policy: frame-ancestors 'self'\n```\n\n## Further reading\n\n- [MDN Web Docs: X-Frame-Options](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options)\n- [MDN Web Docs: Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n- [OWASP: Clickjacking Defense Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html)\n"
  },
  {
    "path": "questions/how-can-you-prevent-clickjacking-attacks/metadata.json",
    "content": "{\n  \"slug\": \"how-can-you-prevent-clickjacking-attacks\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"advanced\",\n  \"topics\": [\"javascript\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Security\"\n}\n"
  },
  {
    "path": "questions/how-can-you-prevent-clickjacking-attacks/zh-CN.mdx",
    "content": "---\ntitle: 如何防止点击劫持攻击？\n---\n\n## TL;DR\n\n为了防止点击劫持攻击，您可以使用 `X-Frame-Options` HTTP 标头来控制您的网站是否可以嵌入在 iframe 中。将其设置为 `DENY` 以防止所有框架，或设置为 `SAMEORIGIN` 以仅允许来自同一来源的框架。此外，您可以使用带有 `frame-ancestors` 指令的 `Content-Security-Policy` (CSP) 标头来指定允许哪些来源来构建您的内容。\n\n```http\nX-Frame-Options: DENY\n```\n\n```http\nContent-Security-Policy: frame-ancestors 'self'\n```\n\n***\n\n## 什么是点击劫持？\n\n点击劫持是一种攻击，恶意网站会诱骗用户点击与用户感知不同的内容，从而可能导致未经授权的操作或信息泄露。这通常是通过将目标网站嵌入到不可见的 iframe 中并用欺骗性内容覆盖它来实现的。\n\n## 如何防止点击劫持攻击\n\n### 使用 `X-Frame-Options` 标头\n\n`X-Frame-Options` HTTP 标头可用于控制是否应允许浏览器在 `<frame>`、`<iframe>`、`<embed>` 或 `<object>` 中呈现页面。此标头有三个可能的值：\n\n* `DENY`：阻止页面在框架中显示，无论尝试这样做的站点是什么。\n* `SAMEORIGIN`：允许页面在与页面本身相同的来源的框架中显示。\n* `ALLOW-FROM uri`：仅允许页面在指定的来源的框架中显示。\n\n示例：\n\n```http\nX-Frame-Options: DENY\n```\n\n### 使用 `Content-Security-Policy` 标头\n\n`Content-Security-Policy` (CSP) 标头提供了一种更灵活、更现代的方法来防止点击劫持。`frame-ancestors` 指令指定可以使用 `<frame>`、`<iframe>`、`<object>`、`<embed>` 或 `<applet>` 标签嵌入页面的有效父级。\n\n示例：\n\n```http\nContent-Security-Policy: frame-ancestors 'self'\n```\n\n此指令还可以指定多个来源或使用通配符来处理更复杂的场景。\n\n示例：\n\n```http\nContent-Security-Policy: frame-ancestors 'self' https://trusted.com\n```\n\n### 结合使用这两个标头\n\n为了获得最大的兼容性和安全性，建议同时使用 `X-Frame-Options` 和 `Content-Security-Policy` 标头。\n\n示例：\n\n```http\nX-Frame-Options: SAMEORIGIN\nContent-Security-Policy: frame-ancestors 'self'\n```\n\n## 延伸阅读\n\n* [MDN Web 文档：X-Frame-Options](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/X-Frame-Options)\n* [MDN Web 文档：Content-Security-Policy](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CSP)\n* [OWASP：Clickjacking 防御备忘单](https://cheatsheetseries.owasp.org/cheatsheets/Clickjacking_Defense_Cheat_Sheet.html)\n"
  },
  {
    "path": "questions/how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"cd166929\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"8eb0ebb\",\n        \"2a7816d0\",\n        \"5b3c7cb1\",\n        \"3dd28c0f\",\n        \"24dabda0\",\n        \"e499d2f3\",\n        \"baa16ae1\",\n        \"45e67a27\",\n        \"320b639b\",\n        \"c077b67\",\n        \"f88561af\",\n        \"49551b38\",\n        \"7078b0fa\",\n        \"2f4be55f\",\n        \"256510fd\",\n        \"8098cbe6\",\n        \"18ed1b70\",\n        \"94c5ba5a\",\n        \"823641ab\",\n        \"49199f7d\",\n        \"5bde760f\",\n        \"321cba78\",\n        \"e79014e7\",\n        \"1f4770e5\",\n        \"b94ece34\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"8eb0ebb\",\n        \"2a7816d0\",\n        \"5b3c7cb1\",\n        \"3dd28c0f\",\n        \"24dabda0\",\n        \"e499d2f3\",\n        \"baa16ae1\",\n        \"45e67a27\",\n        \"320b639b\",\n        \"c077b67\",\n        \"f88561af\",\n        \"49551b38\",\n        \"7078b0fa\",\n        \"2f4be55f\",\n        \"256510fd\",\n        \"8098cbe6\",\n        \"18ed1b70\",\n        \"94c5ba5a\",\n        \"823641ab\",\n        \"49199f7d\",\n        \"5bde760f\",\n        \"321cba78\",\n        \"e79014e7\",\n        \"1f4770e5\",\n        \"b94ece34\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications/en-US.mdx",
    "content": "---\ntitle: How can you prevent SQL injection vulnerabilities in JavaScript applications?\n---\n\n## TL;DR\n\nTo prevent SQL injection vulnerabilities in JavaScript applications, always use parameterized queries or prepared statements instead of string concatenation to construct SQL queries. This ensures that user input is treated as data and not executable code. Additionally, use ORM libraries that handle SQL injection prevention for you, and always validate and sanitize user inputs.\n\n---\n\n## How can you prevent SQL injection vulnerabilities in JavaScript applications?\n\n### Use parameterized queries or prepared statements\n\nParameterized queries or prepared statements ensure that user input is treated as data and not executable code. This is the most effective way to prevent SQL injection.\n\n#### Example using Node.js with the `mysql` library:\n\n```js\nconst mysql = require('mysql');\nconst connection = mysql.createConnection({\n  host: 'localhost',\n  user: 'root',\n  password: 'password',\n  database: 'test',\n});\n\nconst userId = 1;\nconst query = 'SELECT * FROM users WHERE id = ?';\n\nconnection.query(query, [userId], (error, results) => {\n  if (error) throw error;\n  console.log(results);\n});\n```\n\n### Use ORM libraries\n\nObject-Relational Mapping (ORM) libraries like Sequelize, TypeORM, or Mongoose (for MongoDB) abstract away SQL queries and handle SQL injection prevention internally.\n\n#### Example using Sequelize:\n\n```js\nconst { Sequelize, DataTypes } = require('sequelize');\nconst sequelize = new Sequelize('database', 'username', 'password', {\n  host: 'localhost',\n  dialect: 'mysql',\n});\n\nconst User = sequelize.define('User', {\n  username: {\n    type: DataTypes.STRING,\n    allowNull: false,\n  },\n});\n\nUser.findAll({\n  where: {\n    id: 1,\n  },\n}).then((users) => {\n  console.log(users);\n});\n```\n\n### Validate and sanitize user inputs\n\nAlways validate and sanitize user inputs to ensure they conform to expected formats and do not contain malicious code.\n\n#### Example using `validator` library:\n\n```js\nconst validator = require('validator');\n\nconst userInput = 'someUserInput';\nif (validator.isAlphanumeric(userInput)) {\n  // Proceed with using the input\n} else {\n  // Handle invalid input\n}\n```\n\n### Use stored procedures\n\nStored procedures are precompiled SQL statements stored in the database. They can help prevent SQL injection by separating the SQL logic from user input.\n\n#### Example:\n\n```sql\nCREATE PROCEDURE GetUserById(IN userId INT)\nBEGIN\n  SELECT * FROM users WHERE id = userId;\nEND;\n```\n\n### Use security libraries and frameworks\n\nLeverage security libraries and frameworks that provide built-in protection against SQL injection.\n\n#### Example using Express.js with `express-validator`:\n\n```js\nconst { body, validationResult } = require('express-validator');\n\napp.post(\n  '/user',\n  [body('username').isAlphanumeric(), body('email').isEmail()],\n  (req, res) => {\n    const errors = validationResult(req);\n    if (!errors.isEmpty()) {\n      return res.status(400).json({ errors: errors.array() });\n    }\n    // Proceed with safe input\n  },\n);\n```\n\n## Further reading\n\n- [OWASP SQL Injection Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html)\n- [Node.js MySQL Documentation](https://github.com/mysqljs/mysql)\n- [Sequelize Documentation](https://sequelize.org/master/)\n- [Express Validator Documentation](https://express-validator.github.io/docs/)\n- [Validator.js Documentation](https://github.com/validatorjs/validator.js)\n"
  },
  {
    "path": "questions/how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications/metadata.json",
    "content": "{\n  \"slug\": \"how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Security\"\n}\n"
  },
  {
    "path": "questions/how-can-you-prevent-sql-injection-vulnerabilities-in-javascript-applications/zh-CN.mdx",
    "content": "---\ntitle: 如何防止在 JavaScript 应用程序中发生 SQL 注入漏洞？\n---\n\n## TL;DR\n\n为了防止 JavaScript 应用程序中出现 SQL 注入漏洞，请始终使用参数化查询或预处理语句，而不是使用字符串连接来构造 SQL 查询。这可确保用户输入被视为数据而不是可执行代码。此外，使用处理 SQL 注入预防的 ORM 库，并始终验证和清理用户输入。\n\n***\n\n## 如何防止在 JavaScript 应用程序中发生 SQL 注入漏洞？\n\n### 使用参数化查询或预处理语句\n\n参数化查询或预处理语句可确保用户输入被视为数据而不是可执行代码。这是防止 SQL 注入的最有效方法。\n\n#### 使用 Node.js 和 `mysql` 库的示例：\n\n```js\nconst mysql = require('mysql');\nconst connection = mysql.createConnection({\n  host: 'localhost',\n  user: 'root',\n  password: 'password',\n  database: 'test',\n});\n\nconst userId = 1;\nconst query = 'SELECT * FROM users WHERE id = ?';\n\nconnection.query(query, [userId], (error, results) => {\n  if (error) throw error;\n  console.log(results);\n});\n```\n\n### 使用 ORM 库\n\n对象关系映射 (ORM) 库（如 Sequelize、TypeORM 或 Mongoose (用于 MongoDB)）抽象了 SQL 查询，并在内部处理 SQL 注入预防。\n\n#### 使用 Sequelize 的示例：\n\n```js\nconst { Sequelize, DataTypes } = require('sequelize');\nconst sequelize = new Sequelize('database', 'username', 'password', {\n  host: 'localhost',\n  dialect: 'mysql',\n});\n\nconst User = sequelize.define('User', {\n  username: {\n    type: DataTypes.STRING,\n    allowNull: false,\n  },\n});\n\nUser.findAll({\n  where: {\n    id: 1,\n  },\n}).then((users) => {\n  console.log(users);\n});\n```\n\n### 验证和清理用户输入\n\n始终验证和清理用户输入，以确保它们符合预期格式，并且不包含恶意代码。\n\n#### 使用 `validator` 库的示例：\n\n```js\nconst validator = require('validator');\n\nconst userInput = 'someUserInput';\nif (validator.isAlphanumeric(userInput)) {\n  // Proceed with using the input\n} else {\n  // Handle invalid input\n}\n```\n\n### 使用存储过程\n\n存储过程是存储在数据库中的预编译 SQL 语句。它们可以通过将 SQL 逻辑与用户输入分开来帮助防止 SQL 注入。\n\n#### 示例：\n\n```sql\nCREATE PROCEDURE GetUserById(IN userId INT)\nBEGIN\n  SELECT * FROM users WHERE id = userId;\nEND;\n```\n\n### 使用安全库和框架\n\n利用提供内置 SQL 注入保护的安全库和框架。\n\n#### 使用 Express.js 和 `express-validator` 的示例：\n\n```js\nconst { body, validationResult } = require('express-validator');\n\napp.post(\n  '/user',\n  [body('username').isAlphanumeric(), body('email').isEmail()],\n  (req, res) => {\n    const errors = validationResult(req);\n    if (!errors.isEmpty()) {\n      return res.status(400).json({ errors: errors.array() });\n    }\n    // Proceed with safe input\n  },\n);\n```\n\n## 延伸阅读\n\n* [Validator.js 文档](https://github.com/validatorjs/validator.js)\n"
  },
  {
    "path": "questions/how-can-you-share-code-between-files/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"3597530c\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"f2fac493\",\n        \"e59129d\",\n        \"b2998e25\",\n        \"b809df68\",\n        \"2a7816d0\",\n        \"feff2220\",\n        \"545d6966\",\n        \"266557de\",\n        \"ef0b0578\",\n        \"f5228623\",\n        \"53463c08\",\n        \"f875e8b1\",\n        \"5aecda15\",\n        \"4c36d999\",\n        \"fd1a3ce2\",\n        \"6c88082e\",\n        \"2b757c50\",\n        \"3c1db723\",\n        \"545d6966\",\n        \"9227a6a9\",\n        \"b0e6b589\",\n        \"f5228623\",\n        \"a56088d4\",\n        \"9db06f93\",\n        \"290b81c3\",\n        \"ebc9910f\",\n        \"f26ce216\",\n        \"a18d7e96\",\n        \"4b235c5c\",\n        \"1f4770e5\",\n        \"559f3236\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"f2fac493\",\n        \"e59129d\",\n        \"b2998e25\",\n        \"b809df68\",\n        \"2a7816d0\",\n        \"feff2220\",\n        \"545d6966\",\n        \"266557de\",\n        \"ef0b0578\",\n        \"f5228623\",\n        \"53463c08\",\n        \"f875e8b1\",\n        \"5aecda15\",\n        \"4c36d999\",\n        \"fd1a3ce2\",\n        \"6c88082e\",\n        \"2b757c50\",\n        \"3c1db723\",\n        \"545d6966\",\n        \"9227a6a9\",\n        \"b0e6b589\",\n        \"f5228623\",\n        \"a56088d4\",\n        \"9db06f93\",\n        \"290b81c3\",\n        \"ebc9910f\",\n        \"f26ce216\",\n        \"a18d7e96\",\n        \"4b235c5c\",\n        \"1f4770e5\",\n        \"559f3236\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-can-you-share-code-between-files/en-US.mdx",
    "content": "---\ntitle: How can you share code between JavaScript files?\n---\n\n## TL;DR\n\nTo share code between JavaScript files, you can use modules. In modern JavaScript, you can use ES6 modules with `export` and `import` statements. For example, you can export a function from one file and import it into another:\n\n```javascript\n// file1.js\nexport function greet() {\n  console.log('Hello, world!');\n}\n\n// file2.js\nimport { greet } from './file1.js';\ngreet();\n```\n\nAlternatively, in Node.js, you can use `module.exports` and `require`:\n\n```javascript\n// file1.js\nmodule.exports = function greet() {\n  console.log('Hello, world!');\n};\n\n// file2.js\nconst greet = require('./file1.js');\ngreet();\n```\n\n---\n\n## Using ES6 modules\n\n### Exporting code\n\nTo share code, you can use the `export` keyword to export variables, functions, or classes from a module:\n\n```javascript\n// utils.js\nexport function add(a, b) {\n  return a + b;\n}\n\nexport const PI = 3.14;\n```\n\n### Importing code\n\nYou can then import the exported code in another file using the `import` keyword:\n\n```javascript\n// main.js\nimport { add, PI } from './utils.js';\n\nconsole.log(add(2, 3)); // 5\nconsole.log(PI); // 3.14\n```\n\n### Default exports\n\nYou can also export a single default value from a module:\n\n```javascript\n// math.js\nexport default function subtract(a, b) {\n  return a - b;\n}\n```\n\nAnd import it without curly braces:\n\n```javascript\n// main.js\nimport subtract from './math.js';\n\nconsole.log(subtract(5, 2)); // 3\n```\n\n## Using CommonJS modules in Node.js\n\n### Exporting code\n\nIn Node.js, you can use `module.exports` to export code:\n\n```javascript\n// utils.js\nmodule.exports.add = function (a, b) {\n  return a + b;\n};\n\nmodule.exports.PI = 3.14;\n```\n\n### Importing code\n\nYou can then import the exported code using `require`:\n\n```javascript\n// main.js\nconst utils = require('./utils.js');\n\nconsole.log(utils.add(2, 3)); // 5\nconsole.log(utils.PI); // 3.14\n```\n\n### Exporting a single value\n\nYou can also export a single value:\n\n```javascript\n// math.js\nmodule.exports = function subtract(a, b) {\n  return a - b;\n};\n```\n\nAnd import it directly:\n\n```javascript\n// main.js\nconst subtract = require('./math.js');\n\nconsole.log(subtract(5, 2)); // 3\n```\n\n## Further reading\n\n- [MDN Web Docs on ES6 modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n- [Node.js documentation on modules](https://nodejs.org/api/modules.html)\n- [JavaScript modules: A beginner’s guide](https://www.freecodecamp.org/news/javascript-modules-a-beginner-s-guide-783f7d7a5fcc/)\n"
  },
  {
    "path": "questions/how-can-you-share-code-between-files/metadata.json",
    "content": "{\n  \"slug\": \"how-can-you-share-code-between-files\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": false,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/how-can-you-share-code-between-files/pt-BR.mdx",
    "content": "---\ntitle: Como você pode compartilhar código entre arquivos?\n---\n\nIsto depende do ambiente JavaScript.\n\nNo cliente (ambiente do navegador), desde que as variáveis/funções sejam declaradas no escopo global (`window`), todos os scripts podem se referir a elas. Alternativamente, adote a Definição de Módulo Assíncrono (AMD) por meio do RequireJS para uma abordagem mais modular.\n\nNo servidor (Node.js), a maneira comum tem sido usar o CommonJS. Cada arquivo é tratado como um módulo e pode exportar variáveis e funções anexando-os ao objeto `module.exports`.\n\nES2015 define uma sintaxe de módulo que visa substituir tanto o AMD quanto o CommonJS. Isso eventualmente será suportado em ambos os ambientes de navegador e Node.\n"
  },
  {
    "path": "questions/how-can-you-share-code-between-files/zh-CN.mdx",
    "content": "---\ntitle: 如何在 JavaScript 文件之间共享代码？\n---\n\n## TL;DR\n\n要在 JavaScript 文件之间共享代码，您可以使用模块。在现代 JavaScript 中，您可以使用带有 `export` 和 `import` 语句的 ES6 模块。例如，您可以从一个文件导出一个函数并将其导入到另一个文件中：\n\n```javascript\n// file1.js\nexport function greet() {\n  console.log('Hello, world!');\n}\n\n// file2.js\nimport { greet } from './file1.js';\ngreet();\n```\n\n或者，在 Node.js 中，您可以使用 `module.exports` 和 `require`：\n\n```javascript\n// file1.js\nmodule.exports = function greet() {\n  console.log('Hello, world!');\n};\n\n// file2.js\nconst greet = require('./file1.js');\ngreet();\n```\n\n***\n\n## 使用 ES6 模块\n\n### 导出代码\n\n要共享代码，您可以使用 `export` 关键字从模块中导出变量、函数或类：\n\n```javascript\n// utils.js\nexport function add(a, b) {\n  return a + b;\n}\n\nexport const PI = 3.14;\n```\n\n### 导入代码\n\n然后，您可以使用 `import` 关键字在另一个文件中导入导出的代码：\n\n```javascript\n// main.js\nimport { add, PI } from './utils.js';\n\nconsole.log(add(2, 3)); // 5\nconsole.log(PI); // 3.14\n```\n\n### 默认导出\n\n您还可以从模块导出一个默认值：\n\n```javascript\n// math.js\nexport default function subtract(a, b) {\n  return a - b;\n}\n```\n\n并在没有大括号的情况下导入它：\n\n```javascript\n// main.js\nimport subtract from './math.js';\n\nconsole.log(subtract(5, 2)); // 3\n```\n\n## 在 Node.js 中使用 CommonJS 模块\n\n### 导出代码\n\n在 Node.js 中，您可以使用 `module.exports` 导出代码：\n\n```javascript\n// utils.js\nmodule.exports.add = function (a, b) {\n  return a + b;\n};\n\nmodule.exports.PI = 3.14;\n```\n\n### 导入代码\n\n然后，您可以使用 `require` 导入导出的代码：\n\n```javascript\n// main.js\nconst utils = require('./utils.js');\n\nconsole.log(utils.add(2, 3)); // 5\nconsole.log(utils.PI); // 3.14\n```\n\n### 导出单个值\n\n您也可以导出一个值：\n\n```javascript\n// math.js\nmodule.exports = function subtract(a, b) {\n  return a - b;\n};\n```\n\n并直接导入它：\n\n```javascript\n// main.js\nconst subtract = require('./math.js');\n\nconsole.log(subtract(5, 2)); // 3\n```\n\n## 延伸阅读\n\n* [MDN Web Docs on ES6 modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n* [Node.js documentation on modules](https://nodejs.org/api/modules.html)\n* [JavaScript modules: A beginner’s guide](https://www.freecodecamp.org/news/javascript-modules-a-beginner-s-guide-783f7d7a5fcc/)\n"
  },
  {
    "path": "questions/how-can-you-test-asynchronous-code-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"b7bb2a0c\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"cd53e4b8\",\n        \"790018e9\",\n        \"e3eaa85f\",\n        \"2a7816d0\",\n        \"153eb297\",\n        \"dce035e\",\n        \"34739f00\",\n        \"65822960\",\n        \"e7e6225c\",\n        \"2d3c5a3\",\n        \"4f6965d0\",\n        \"70e03492\",\n        \"e7e6225c\",\n        \"7f92b418\",\n        \"dcdb5674\",\n        \"dcc27677\",\n        \"e7e6225c\",\n        \"b6a5d2ff\",\n        \"65c7f3a1\",\n        \"ac281718\",\n        \"143d526c\",\n        \"1f4770e5\",\n        \"d88832a5\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"cd53e4b8\",\n        \"790018e9\",\n        \"e3eaa85f\",\n        \"2a7816d0\",\n        \"153eb297\",\n        \"dce035e\",\n        \"34739f00\",\n        \"65822960\",\n        \"e7e6225c\",\n        \"2d3c5a3\",\n        \"4f6965d0\",\n        \"70e03492\",\n        \"e7e6225c\",\n        \"7f92b418\",\n        \"dcdb5674\",\n        \"dcc27677\",\n        \"e7e6225c\",\n        \"b6a5d2ff\",\n        \"65c7f3a1\",\n        \"ac281718\",\n        \"143d526c\",\n        \"1f4770e5\",\n        \"d88832a5\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-can-you-test-asynchronous-code-in-javascript/en-US.mdx",
    "content": "---\ntitle: How can you test asynchronous code in JavaScript?\n---\n\n## TL;DR\n\nTo test asynchronous code in JavaScript, you can use testing frameworks like Jest or Mocha. These frameworks provide built-in support for handling asynchronous operations. You can use `async`/`await` or return promises in your test functions. For example, in Jest, you can write:\n\n```js\ntest('fetches data successfully', async () => {\n  const data = await fetchData();\n  expect(data).toBeDefined();\n});\n```\n\nAlternatively, you can use callbacks and the `done` function to signal the end of an asynchronous test.\n\n---\n\n## How can you test asynchronous code in JavaScript?\n\nTesting asynchronous code in JavaScript can be challenging, but modern testing frameworks like Jest and Mocha provide robust support for handling asynchronous operations. Here are some common methods to test asynchronous code:\n\n### Using `async`/`await`\n\nOne of the most straightforward ways to test asynchronous code is by using `async`/`await`. This approach makes your test code look synchronous, which can be easier to read and write.\n\n#### Example with Jest\n\n```js\n// fetchData.js\nexport const fetchData = async () => {\n  const response = await fetch('https://api.example.com/data');\n  return response.json();\n};\n\n// fetchData.test.js\nimport { fetchData } from './fetchData';\n\ntest('fetches data successfully', async () => {\n  const data = await fetchData();\n  expect(data).toBeDefined();\n});\n```\n\n### Returning a promise\n\nAnother way to handle asynchronous tests is by returning a promise from your test function. Jest and Mocha will wait for the promise to resolve before finishing the test.\n\n#### Example with Jest\n\n```js\n// fetchData.js\nexport const fetchData = () => {\n  return fetch('https://api.example.com/data').then((response) =>\n    response.json(),\n  );\n};\n\n// fetchData.test.js\nimport { fetchData } from './fetchData';\n\ntest('fetches data successfully', () => {\n  return fetchData().then((data) => {\n    expect(data).toBeDefined();\n  });\n});\n```\n\n### Using callbacks\n\nFor older codebases or specific scenarios, you might need to use callbacks. In Jest, you can use the `done` function to signal the end of an asynchronous test.\n\n#### Example with Jest\n\n```js\n// fetchData.js\nexport const fetchData = (callback) => {\n  fetch('https://api.example.com/data')\n    .then((response) => response.json())\n    .then((data) => callback(null, data))\n    .catch((error) => callback(error));\n};\n\n// fetchData.test.js\nimport { fetchData } from './fetchData';\n\ntest('fetches data successfully', (done) => {\n  fetchData((error, data) => {\n    expect(error).toBeNull();\n    expect(data).toBeDefined();\n    done();\n  });\n});\n```\n\n### Using Mocha\n\nMocha also supports `async`/`await`, returning promises, and using callbacks. Here is an example using `async`/`await` with Mocha:\n\n```js\n// fetchData.js\nexport const fetchData = async () => {\n  const response = await fetch('https://api.example.com/data');\n  return response.json();\n};\n\n// fetchData.test.js\nimport { fetchData } from './fetchData';\nimport { expect } from 'chai';\n\ndescribe('fetchData', () => {\n  it('fetches data successfully', async () => {\n    const data = await fetchData();\n    expect(data).to.be.an('object');\n  });\n});\n```\n\n## Further reading\n\n- [Jest documentation on testing asynchronous code](https://jestjs.io/docs/asynchronous)\n- [Mocha documentation on testing asynchronous code](https://mochajs.org/#asynchronous-code)\n- [MDN Web Docs on async/await](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await)\n- [Chai assertion library](https://www.chaijs.com/)\n"
  },
  {
    "path": "questions/how-can-you-test-asynchronous-code-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"how-can-you-test-asynchronous-code-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"async\", \"javascript\", \"testing\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Testing\"\n}\n"
  },
  {
    "path": "questions/how-can-you-test-asynchronous-code-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 如何在 JavaScript 中测试异步代码？\n---\n\n## TL;DR\n\n要在 JavaScript 中测试异步代码，你可以使用 Jest 或 Mocha 等测试框架。这些框架提供了对处理异步操作的内置支持。你可以在测试函数中使用 `async`/`await` 或返回 promise。例如，在 Jest 中，你可以编写：\n\n```js\ntest('fetches data successfully', async () => {\n  const data = await fetchData();\n  expect(data).toBeDefined();\n});\n```\n\n或者，你可以使用回调函数和 `done` 函数来指示异步测试的结束。\n\n***\n\n## 如何在 JavaScript 中测试异步代码？\n\n在 JavaScript 中测试异步代码可能具有挑战性，但像 Jest 和 Mocha 这样的现代测试框架为处理异步操作提供了强大的支持。以下是测试异步代码的一些常用方法：\n\n### 使用 `async`/`await`\n\n测试异步代码最直接的方法之一是使用 `async`/`await`。这种方法使你的测试代码看起来是同步的，这更容易阅读和编写。\n\n#### Jest 示例\n\n```js\n// fetchData.js\nexport const fetchData = async () => {\n  const response = await fetch('https://api.example.com/data');\n  return response.json();\n};\n\n// fetchData.test.js\nimport { fetchData } from './fetchData';\n\ntest('fetches data successfully', async () => {\n  const data = await fetchData();\n  expect(data).toBeDefined();\n});\n```\n\n### 返回一个 promise\n\n处理异步测试的另一种方法是从你的测试函数中返回一个 promise。Jest 和 Mocha 将等待 promise 在完成测试之前被解析。\n\n#### Jest 示例\n\n```js\n// fetchData.js\nexport const fetchData = () => {\n  return fetch('https://api.example.com/data').then((response) =>\n    response.json(),\n  );\n};\n\n// fetchData.test.js\nimport { fetchData } from './fetchData';\n\ntest('fetches data successfully', () => {\n  return fetchData().then((data) => {\n    expect(data).toBeDefined();\n  });\n});\n```\n\n### 使用回调函数\n\n对于旧的代码库或特定场景，你可能需要使用回调函数。在 Jest 中，你可以使用 `done` 函数来指示异步测试的结束。\n\n#### Jest 示例\n\n```js\n// fetchData.js\nexport const fetchData = (callback) => {\n  fetch('https://api.example.com/data')\n    .then((response) => response.json())\n    .then((data) => callback(null, data))\n    .catch((error) => callback(error));\n};\n\n// fetchData.test.js\nimport { fetchData } from './fetchData';\n\ntest('fetches data successfully', (done) => {\n  fetchData((error, data) => {\n    expect(error).toBeNull();\n    expect(data).toBeDefined();\n    done();\n  });\n});\n```\n\n### 使用 Mocha\n\nMocha 也支持 `async`/`await`、返回 promise 和使用回调函数。这是一个使用 `async`/`await` 和 Mocha 的示例：\n\n```js\n// fetchData.js\nexport const fetchData = async () => {\n  const response = await fetch('https://api.example.com/data');\n  return response.json();\n};\n\n// fetchData.test.js\nimport { fetchData } from './fetchData';\nimport { expect } from 'chai';\n\ndescribe('fetchData', () => {\n  it('fetches data successfully', async () => {\n    const data = await fetchData();\n    expect(data).to.be.an('object');\n  });\n});\n```\n\n## 延伸阅读\n\n* [Jest 关于测试异步代码的文档](https://jestjs.io/docs/asynchronous)\n* [Mocha 关于测试异步代码的文档](https://mochajs.org/#asynchronous-code)\n* [MDN Web Docs 关于 async/await](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await)\n* [Chai 断言库](https://www.chaijs.com/)\n"
  },
  {
    "path": "questions/how-do-currying-and-partial-application-differ-from-each-other/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"9fcd7e6e\",\n        \"2a7816d0\",\n        \"754f201a\",\n        \"1743fc64\",\n        \"dd75fb51\",\n        \"748ffe75\",\n        \"7b81a9eb\",\n        \"36d7fec4\",\n        \"5fd903ca\",\n        \"7caa40d3\",\n        \"748ffe75\",\n        \"ae4b5eab\",\n        \"bece61d8\",\n        \"67423e0a\",\n        \"7f8361a1\",\n        \"1f4770e5\",\n        \"64d0705a\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"9fcd7e6e\",\n        \"2a7816d0\",\n        \"754f201a\",\n        \"1743fc64\",\n        \"dd75fb51\",\n        \"748ffe75\",\n        \"7b81a9eb\",\n        \"36d7fec4\",\n        \"5fd903ca\",\n        \"7caa40d3\",\n        \"748ffe75\",\n        \"ae4b5eab\",\n        \"bece61d8\",\n        \"67423e0a\",\n        \"7f8361a1\",\n        \"1f4770e5\",\n        \"64d0705a\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"d34df27e\"\n  }\n}\n"
  },
  {
    "path": "questions/how-do-currying-and-partial-application-differ-from-each-other/en-US.mdx",
    "content": "---\ntitle: How do currying and partial application differ from each other?\n---\n\n## TL;DR\n\nCurrying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. For example, a function `f(a, b, c)` becomes `f(a)(b)(c)`. Partial application, on the other hand, fixes a few arguments of a function and produces another function with a smaller number of arguments. For example, if you partially apply `f(a, b, c)` with `a`, you get a new function `f'(b, c)`.\n\n---\n\n## Currying vs partial application\n\n### Currying\n\nCurrying is a technique where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument. This allows for more flexible function composition and reuse.\n\n#### Example\n\n```js live\nfunction add(a) {\n  return function (b) {\n    return function (c) {\n      return a + b + c;\n    };\n  };\n}\n\nconst result = add(1)(2)(3);\nconsole.log(result); // 6\n```\n\nIn this example, `add` is a curried function that takes three arguments one at a time.\n\n### Partial application\n\nPartial application is a technique where you fix a few arguments of a function, producing another function with a smaller number of arguments. This is useful for creating specialized functions from more general ones.\n\n#### Example\n\n```js live\nfunction add(a, b, c) {\n  return a + b + c;\n}\n\nconst addOne = add.bind(null, 1);\nconst result = addOne(2, 3);\nconsole.log(result); // 6\n```\n\nIn this example, `addOne` is a partially applied function that fixes the first argument of `add` to `1`.\n\n### Key differences\n\n- **Currying**: Transforms a function with multiple arguments into a sequence of functions, each taking a single argument.\n- **Partial application**: Fixes a few arguments of a function and produces another function with a smaller number of arguments.\n\n## Further reading\n\n- [JavaScript.info on currying and partial application](https://javascript.info/currying-partials)\n"
  },
  {
    "path": "questions/how-do-currying-and-partial-application-differ-from-each-other/metadata.json",
    "content": "{\n  \"slug\": \"how-do-currying-and-partial-application-differ-from-each-other\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"closure\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Currying & Partial Application\"\n}\n"
  },
  {
    "path": "questions/how-do-currying-and-partial-application-differ-from-each-other/zh-CN.mdx",
    "content": "---\ntitle: Currying 和部分应用之间有什么区别？\n---\n\n## 总结\n\nCurrying 将具有多个参数的函数转换为一系列函数，每个函数只接受一个参数。例如，函数 `f(a, b, c)` 变为 `f(a)(b)(c)`。另一方面，部分应用会固定函数的几个参数，并生成另一个具有较少参数的函数。例如，如果使用 `a` 部分应用 `f(a, b, c)`，则会得到一个新函数 `f'(b, c)`。\n\n***\n\n## Currying vs 部分应用\n\n### Currying\n\nCurrying 是一种将具有多个参数的函数转换为一系列函数的技术，每个函数只接受一个参数。这允许更灵活的函数组合和重用。\n\n#### 示例\n\n```js live\nfunction add(a) {\n  return function (b) {\n    return function (c) {\n      return a + b + c;\n    };\n  };\n}\n\nconst result = add(1)(2)(3);\nconsole.log(result); // 6\n```\n\n在此示例中，`add` 是一个 curried 函数，它一次接受三个参数。\n\n### 部分应用\n\n部分应用是一种技术，您可以在其中固定函数的几个参数，从而生成另一个具有较少参数的函数。这对于从更通用的函数创建专门的函数很有用。\n\n#### 示例\n\n```js live\nfunction add(a, b, c) {\n  return a + b + c;\n}\n\nconst addOne = add.bind(null, 1);\nconst result = addOne(2, 3);\nconsole.log(result); // 6\n```\n\n在此示例中，`addOne` 是一个部分应用的函数，它将 `add` 的第一个参数固定为 `1`。\n\n### 主要区别\n\n* **Currying**：将具有多个参数的函数转换为一系列函数，每个函数只接受一个参数。\n* **部分应用**：固定函数的几个参数，并生成另一个具有较少参数的函数。\n\n## 延伸阅读\n\n* [JavaScript.info on currying and partial application](https://javascript.info/currying-partials)\n"
  },
  {
    "path": "questions/how-do-iframe-on-a-page-communicate/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"4a79cb57\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"dc2f9c05\",\n        \"92a8f974\",\n        \"2a7816d0\",\n        \"69dc5012\",\n        \"d33a947e\",\n        \"5d100c93\",\n        \"e19e2160\",\n        \"a0d55074\",\n        \"3640ac51\",\n        \"ad9dff34\",\n        \"efcde362\",\n        \"3f4891b9\",\n        \"14b35049\",\n        \"cdbc8b7a\",\n        \"2a6b0356\",\n        \"ff7a01b\",\n        \"ee90fa1d\",\n        \"abc48e8e\",\n        \"c72464d1\",\n        \"3c1797a7\",\n        \"a0ec2f20\",\n        \"1f4770e5\",\n        \"367a32f6\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"dc2f9c05\",\n        \"92a8f974\",\n        \"2a7816d0\",\n        \"69dc5012\",\n        \"d33a947e\",\n        \"5d100c93\",\n        \"e19e2160\",\n        \"a0d55074\",\n        \"3640ac51\",\n        \"ad9dff34\",\n        \"efcde362\",\n        \"3f4891b9\",\n        \"14b35049\",\n        \"cdbc8b7a\",\n        \"2a6b0356\",\n        \"ff7a01b\",\n        \"ee90fa1d\",\n        \"abc48e8e\",\n        \"c72464d1\",\n        \"3c1797a7\",\n        \"a0ec2f20\",\n        \"1f4770e5\",\n        \"367a32f6\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-iframe-on-a-page-communicate/en-US.mdx",
    "content": "---\ntitle: How do `<iframe>` on a page communicate?\n---\n\n## TL;DR\n\n`<iframe>` elements on a page can communicate using the `postMessage` API. This allows for secure cross-origin communication between the parent page and the iframe. The `postMessage` method sends a message, and the `message` event listener receives it. Here's a simple example:\n\n```js\n// In the parent page\nconst iframe = document.querySelector('iframe');\niframe.contentWindow.postMessage('Hello from parent', '*');\n\n// In the iframe\nwindow.addEventListener('message', (event) => {\n  console.log(event.data); // 'Hello from parent'\n});\n```\n\n---\n\n## How do `<iframe>` on a page communicate?\n\n### Using the `postMessage` API\n\nThe `postMessage` API is the most common and secure way for iframes to communicate with each other or with their parent page. This method allows for cross-origin communication, which is essential for modern web applications.\n\n#### Sending a message\n\nTo send a message from the parent page to the iframe, you can use the `postMessage` method. Here’s an example:\n\n```js\n// In the parent page\nconst iframe = document.querySelector('iframe');\niframe.contentWindow.postMessage('Hello from parent', '*');\n```\n\nIn this example, the parent page selects the iframe and sends a message to it. The second parameter, `'*'`, is the target origin. It specifies the origin of the target window. Using `'*'` means the message can be received by any origin, but for security reasons, it's better to specify the exact origin.\n\n#### Receiving a message\n\nTo receive a message in the iframe, you need to add an event listener for the `message` event:\n\n```js\n// In the iframe\nwindow.addEventListener('message', (event) => {\n  console.log(event.data); // 'Hello from parent'\n});\n```\n\nThe `event` object contains the `data` property, which holds the message sent by the parent page.\n\n### Security considerations\n\nWhen using `postMessage`, it's crucial to consider security:\n\n- **Specify the target origin**: Instead of using `'*'`, specify the exact origin to ensure that only messages from trusted sources are received.\n- **Validate the message**: Always validate the message content to prevent malicious data from being processed.\n\n### Example with target origin\n\nHere’s an example with a specified target origin:\n\n```js\n// In the parent page\nconst iframe = document.querySelector('iframe');\nconst targetOrigin = 'https://example.com';\niframe.contentWindow.postMessage('Hello from parent', targetOrigin);\n\n// In the iframe\nwindow.addEventListener('message', (event) => {\n  if (event.origin === 'https://parent.com') {\n    console.log(event.data); // 'Hello from parent'\n  }\n});\n```\n\nIn this example, the parent page sends a message only to `https://example.com`, and the iframe processes the message only if it comes from `https://parent.com`.\n\n## Further reading\n\n- [MDN Web Docs: Window.postMessage()](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage)\n- [HTML Living Standard: postMessage](https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage)\n- [Cross-document messaging](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#cross-document_messaging)\n"
  },
  {
    "path": "questions/how-do-iframe-on-a-page-communicate/metadata.json",
    "content": "{\n  \"slug\": \"how-do-iframe-on-a-page-communicate\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"web-api\", \"javascript\", \"html\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/how-do-iframe-on-a-page-communicate/zh-CN.mdx",
    "content": "---\ntitle: 页面上的 `<iframe>` 如何通信？\n---\n\n## 总结\n\n页面上的 `<iframe>` 元素可以使用 `postMessage` API 进行通信。这允许父页面和 iframe 之间进行安全的跨源通信。`postMessage` 方法发送消息，而 `message` 事件侦听器接收消息。这是一个简单的例子：\n\n```js\n// 在父页面中\nconst iframe = document.querySelector('iframe');\niframe.contentWindow.postMessage('Hello from parent', '*');\n\n// 在 iframe 中\nwindow.addEventListener('message', (event) => {\n  console.log(event.data); // 'Hello from parent'\n});\n```\n\n***\n\n## 页面上的 `<iframe>` 如何通信？\n\n### 使用 `postMessage` API\n\n`postMessage` API 是 iframe 相互之间或与其父页面通信的最常见和最安全的方式。此方法允许跨源通信，这对于现代 Web 应用程序至关重要。\n\n#### 发送消息\n\n要将消息从父页面发送到 iframe，您可以使用 `postMessage` 方法。这是一个例子：\n\n```js\n// 在父页面中\nconst iframe = document.querySelector('iframe');\niframe.contentWindow.postMessage('Hello from parent', '*');\n```\n\n在此示例中，父页面选择 iframe 并向其发送消息。第二个参数 `'*'` 是目标 origin。它指定目标窗口的 origin。使用 `'*'` 意味着任何 origin 都可以接收消息，但出于安全原因，最好指定确切的 origin。\n\n#### 接收消息\n\n要在 iframe 中接收消息，您需要为 `message` 事件添加一个事件侦听器：\n\n```js\n// 在 iframe 中\nwindow.addEventListener('message', (event) => {\n  console.log(event.data); // 'Hello from parent'\n});\n```\n\n`event` 对象包含 `data` 属性，该属性保存父页面发送的消息。\n\n### 安全注意事项\n\n使用 `postMessage` 时，考虑安全性至关重要：\n\n* **指定目标 origin**：不要使用 `'*'`，而是指定确切的 origin，以确保仅接收来自受信任来源的消息。\n* **验证消息**：始终验证消息内容，以防止处理恶意数据。\n\n### 带有目标 origin 的示例\n\n这是一个带有指定目标来源的示例：\n\n```js\n// In the parent page\nconst iframe = document.querySelector('iframe');\nconst targetOrigin = 'https://example.com';\niframe.contentWindow.postMessage('Hello from parent', targetOrigin);\n\n// In the iframe\nwindow.addEventListener('message', (event) => {\n  if (event.origin === 'https://parent.com') {\n    console.log(event.data); // 'Hello from parent'\n  }\n});\n```\n\n在此示例中，父页面仅向 `https://example.com` 发送消息，并且 iframe 仅在消息来自 `https://parent.com` 时才处理该消息。\n\n## 延伸阅读\n\n* [MDN Web Docs: Window.postMessage()](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage)\n* [HTML Living Standard: postMessage](https://html.spec.whatwg.org/multipage/web-messaging.html#dom-window-postmessage)\n* [跨文档消息传递](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#cross-document_messaging)\n"
  },
  {
    "path": "questions/how-do-sets-and-maps-handle-equality-checks-for-objects/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"eddc3137\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"b257cf1e\",\n        \"f5f518ad\",\n        \"2a7816d0\",\n        \"cdcc63f7\",\n        \"e27a0718\",\n        \"8da9bd5c\",\n        \"111a2a57\",\n        \"4848954f\",\n        \"f5f518ad\",\n        \"ce98107a\",\n        \"eb78f3\",\n        \"b886a8a6\",\n        \"a00f9384\",\n        \"dec76046\",\n        \"84c38fac\",\n        \"d91450c7\",\n        \"1f4770e5\",\n        \"208f7528\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"b257cf1e\",\n        \"f5f518ad\",\n        \"2a7816d0\",\n        \"cdcc63f7\",\n        \"e27a0718\",\n        \"8da9bd5c\",\n        \"111a2a57\",\n        \"4848954f\",\n        \"f5f518ad\",\n        \"ce98107a\",\n        \"eb78f3\",\n        \"b886a8a6\",\n        \"a00f9384\",\n        \"dec76046\",\n        \"84c38fac\",\n        \"d91450c7\",\n        \"1f4770e5\",\n        \"208f7528\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-sets-and-maps-handle-equality-checks-for-objects/en-US.mdx",
    "content": "---\ntitle: How do `Set`s and `Map`s handle equality checks for objects?\n---\n\n## TL;DR\n\n`Set`s and `Map`s in JavaScript handle equality checks for objects based on reference equality, not deep equality. This means that two objects are considered equal only if they reference the same memory location. For example, if you add two different object literals with the same properties to a `Set`, they will be treated as distinct entries.\n\n```js live\nconst set = new Set();\nconst obj1 = { a: 1 };\nconst obj2 = { a: 1 };\n\nset.add(obj1);\nset.add(obj2);\n\nconsole.log(set.size); // Output: 2\n```\n\n---\n\n## How do `Set`s and `Map`s handle equality checks for objects?\n\n### Reference equality\n\nIn JavaScript, `Set`s and `Map`s use reference equality to determine if two objects are the same. This means that two objects are considered equal only if they reference the same memory location.\n\n### Example with `Set`\n\nWhen you add objects to a `Set`, the `Set` will only consider them equal if they are the same object reference.\n\n```js live\nconst set = new Set();\nconst obj1 = { a: 1 };\nconst obj2 = { a: 1 };\n\nset.add(obj1);\nset.add(obj2);\n\nconsole.log(set.size); // Output: 2\n```\n\nIn this example, `obj1` and `obj2` have the same properties, but they are different object references. Therefore, the `Set` treats them as distinct entries.\n\n### Example with `Map`\n\nSimilarly, when you use objects as keys in a `Map`, the `Map` will only consider them equal if they are the same object reference.\n\n```js live\nconst map = new Map();\nconst obj1 = { a: 1 };\nconst obj2 = { a: 1 };\n\nmap.set(obj1, 'value1');\nmap.set(obj2, 'value2');\n\nconsole.log(map.size); // Output: 2\nconsole.log(map.get(obj1)); // Output: 'value1'\nconsole.log(map.get(obj2)); // Output: 'value2'\n```\n\nIn this example, `obj1` and `obj2` are different object references, so the `Map` treats them as different keys.\n\n### Practical implications\n\n- If you need to check for deep equality (i.e., objects with the same properties and values), you will need to implement your own comparison logic or use a library like Lodash.\n- Be mindful of object references when using `Set`s and `Map`s, especially when dealing with complex data structures.\n\n## Further reading\n\n- [MDN Web Docs: Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)\n- [MDN Web Docs: Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n- [Lodash: isEqual](https://lodash.com/docs/4.17.15#isEqual)\n"
  },
  {
    "path": "questions/how-do-sets-and-maps-handle-equality-checks-for-objects/metadata.json",
    "content": "{\n  \"slug\": \"how-do-sets-and-maps-handle-equality-checks-for-objects\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Sets & Maps\"\n}\n"
  },
  {
    "path": "questions/how-do-sets-and-maps-handle-equality-checks-for-objects/zh-CN.mdx",
    "content": "---\ntitle: Set 和 Map 如何处理对象的相等性检查？\n---\n\n## TL;DR\n\nJavaScript 中的 `Set` 和 `Map` 根据引用相等性（而不是深度相等性）处理对象的相等性检查。这意味着只有当两个对象引用相同的内存位置时，才认为它们相等。例如，如果将两个具有相同属性的不同对象字面量添加到 `Set` 中，它们将被视为不同的条目。\n\n```js live\nconst set = new Set();\nconst obj1 = { a: 1 };\nconst obj2 = { a: 1 };\n\nset.add(obj1);\nset.add(obj2);\n\nconsole.log(set.size); // Output: 2\n```\n\n***\n\n## Set 和 Map 如何处理对象的相等性检查？\n\n### 引用相等性\n\n在 JavaScript 中，`Set` 和 `Map` 使用引用相等性来确定两个对象是否相同。这意味着只有当两个对象引用相同的内存位置时，才认为它们相等。\n\n### Set 示例\n\n当您将对象添加到 `Set` 时，`Set` 仅在它们是相同的对象引用时才认为它们相等。\n\n```js live\nconst set = new Set();\nconst obj1 = { a: 1 };\nconst obj2 = { a: 1 };\n\nset.add(obj1);\nset.add(obj2);\n\nconsole.log(set.size); // Output: 2\n```\n\n在此示例中，`obj1` 和 `obj2` 具有相同的属性，但它们是不同的对象引用。因此，`Set` 将它们视为不同的条目。\n\n### Map 示例\n\n同样，当您将对象用作 `Map` 中的键时，`Map` 仅在它们是相同的对象引用时才认为它们相等。\n\n```js live\nconst map = new Map();\nconst obj1 = { a: 1 };\nconst obj2 = { a: 1 };\n\nmap.set(obj1, 'value1');\nmap.set(obj2, 'value2');\n\nconsole.log(map.size); // Output: 2\nconsole.log(map.get(obj1)); // Output: 'value1'\nconsole.log(map.get(obj2)); // Output: 'value2'\n```\n\n在此示例中，`obj1` 和 `obj2` 是不同的对象引用，因此 `Map` 将它们视为不同的键。\n\n### 实际应用\n\n* 如果您需要检查深度相等性（即，具有相同属性和值的对象），则需要实现自己的比较逻辑或使用 Lodash 等库。\n* 在使用 `Set` 和 `Map` 时，请注意对象引用，尤其是在处理复杂数据结构时。\n\n## 延伸阅读\n\n* [MDN Web Docs: Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)\n* [MDN Web Docs: Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n* [Lodash: isEqual](https://lodash.com/docs/4.17.15#isEqual)\n"
  },
  {
    "path": "questions/how-do-you-abort-a-web-request-using-abortcontrollers/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"dc91ed05\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"bae7c876\",\n        \"e3798fa6\",\n        \"716bc398\",\n        \"df6c34a8\",\n        \"2a7816d0\",\n        \"bd08585c\",\n        \"17cfdb32\",\n        \"2dfd7d87\",\n        \"44adb60f\",\n        \"aca4a61c\",\n        \"943a40e8\",\n        \"e3798fa6\",\n        \"c81ac723\",\n        \"13d3181c\",\n        \"b3bf8350\",\n        \"82501121\",\n        \"d4a227e6\",\n        \"7e967733\",\n        \"537d5a74\",\n        \"25e5ba0a\",\n        \"f878d5b2\",\n        \"d9c2bda4\",\n        \"b35115b8\",\n        \"add698fb\",\n        \"962a7cae\",\n        \"1f4770e5\",\n        \"7787358c\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"bae7c876\",\n        \"e3798fa6\",\n        \"716bc398\",\n        \"df6c34a8\",\n        \"2a7816d0\",\n        \"bd08585c\",\n        \"17cfdb32\",\n        \"2dfd7d87\",\n        \"44adb60f\",\n        \"aca4a61c\",\n        \"943a40e8\",\n        \"e3798fa6\",\n        \"c81ac723\",\n        \"13d3181c\",\n        \"b3bf8350\",\n        \"82501121\",\n        \"d4a227e6\",\n        \"7e967733\",\n        \"537d5a74\",\n        \"25e5ba0a\",\n        \"f878d5b2\",\n        \"d9c2bda4\",\n        \"b35115b8\",\n        \"add698fb\",\n        \"962a7cae\",\n        \"1f4770e5\",\n        \"7787358c\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-abort-a-web-request-using-abortcontrollers/en-US.mdx",
    "content": "---\ntitle: How do you abort a web request using `AbortController` in JavaScript?\n---\n\n## TL;DR\n\n`AbortController` is used to cancel ongoing asynchronous operations like fetch requests.\n\n```js live\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nfetch('https://jsonplaceholder.typicode.com/todos/1', { signal })\n  .then((response) => {\n    // Handle response\n  })\n  .catch((error) => {\n    if (error.name === 'AbortError') {\n      console.log('Request aborted');\n    } else {\n      console.error('Error:', error);\n    }\n  });\n\n// Call abort() to abort the request\ncontroller.abort();\n```\n\nAborting web requests is useful for:\n\n- Canceling requests based on user actions.\n- Prioritizing the latest requests in scenarios with multiple simultaneous requests.\n- Canceling requests that are no longer needed, e.g. after the user has navigated away from the page.\n\n---\n\n## `AbortController`s\n\n`AbortController` allows graceful cancelation of ongoing asynchronous operations like fetch requests. It offers a mechanism to signal to the underlying network layer that the request is no longer required, preventing unnecessary resource consumption and improving user experience.\n\n## Using `AbortController`s\n\nUsing `AbortController`s involve the following steps:\n\n1. **Create an `AbortController` instance**: Initialize an `AbortController` instance, which creates a signal that can be used to abort requests.\n1. **Pass the signal to the request**: Pass the signal to the request, typically through the `signal` property in the request options.\n1. **Abort the request**: Call the `abort()` method on the `AbortController` instance to cancel the ongoing request.\n\nHere is an example of how to use `AbortController`s with the `fetch()` API:\n\n```js live\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nfetch('https://jsonplaceholder.typicode.com/todos/1', { signal })\n  .then((response) => {\n    // Handle response\n  })\n  .catch((error) => {\n    if (error.name === 'AbortError') {\n      console.log('Request aborted');\n    } else {\n      console.error('Error:', error);\n    }\n  });\n\n// Call abort() to abort the request\ncontroller.abort();\n```\n\n## Use cases\n\n### Canceling a `fetch()` request on a user action\n\nCancel requests that take too long or are no longer relevant due to user interactions (e.g., user cancels uploading of a huge file).\n\n```js live\n// HTML: <button id='cancel-button'>Cancel upload</button>\nconst btn = document.createElement('button');\nbtn.id = 'cancel-button';\nbtn.innerHTML = 'Cancel upload';\ndocument.body.appendChild(btn);\n\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nfetch('https://jsonplaceholder.typicode.com/todos/1', { signal })\n  .then((response) => {\n    // Handle successful response\n  })\n  .catch((error) => {\n    if (error.name === 'AbortError') {\n      console.log('Request canceled');\n    } else {\n      console.error('Network or other error:', error);\n    }\n  });\n\ndocument.getElementById('cancel-button').addEventListener('click', () => {\n  controller.abort();\n});\ndocument.getElementById('cancel-button').click(); // Simulate clicking the cancel button\n```\n\nWhen you click the \"Cancel upload\" button, in-flight request will be aborted.\n\n### Prioritizing latest requests in a race condition\n\nIn scenarios where multiple requests are initiated for the same data, use `AbortController` to prioritize the latest request and abort earlier ones.\n\n```js live\nlet latestController = null; // Keeps track of the latest controller\n\nfunction fetchData(url) {\n  if (latestController) {\n    latestController.abort(); // Abort any previous request\n  }\n\n  const controller = new AbortController();\n  latestController = controller;\n  const signal = controller.signal;\n\n  fetch(url, { signal })\n    .then((response) => response.json())\n    .then((data) => console.log('Fetched data:', data))\n    .catch((error) => {\n      if (error.name === 'AbortError') {\n        console.log('Request canceled');\n      } else {\n        console.error('Network or other error:', error);\n      }\n    });\n}\n\nfetchData('https://jsonplaceholder.typicode.com/posts/1');\n\n// Simulate race conditions with new requests that quickly cancel the previous one\nsetTimeout(() => {\n  fetchData('https://jsonplaceholder.typicode.com/posts/2');\n}, 5);\nsetTimeout(() => {\n  fetchData('https://jsonplaceholder.typicode.com/posts/3');\n}, 5);\n// Only the last request should (posts/3) will be allowed to complete\n```\n\nIn this example, when the `fetchData()` function is called multiple times triggering multiple fetch requests, `AbortController`s will cancel all the previous requests except the latest request. This is common in scenarios like type-ahead search or infinite scrolling, where new requests are triggered frequently.\n\n### Canceling requests that are no longer needed\n\nIn situations where the user has navigated away from the page, aborting the request can prevent unnecessary operations (e.g. success callback handling), and freeing up resources by lowering the likelihood of memory leaks.\n\n## Notes\n\n- `AbortController`s is not `fetch()`-specific, it can be used to abort other asynchronous tasks as well.\n- A singular `AbortContoller` instance can be reused on multiple async tasks and cancel all of them at once.\n- Calling `abort()` on `AbortController`s does not send any notification or signal to the server. The server is unaware of the cancelation and will continue processing the request until it completes or times out.\n\n## Further reading\n\n- [AbortController | MDN](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)\n- [Fetch: Abort | Javascript.info](https://javascript.info/fetch-abort)\n"
  },
  {
    "path": "questions/how-do-you-abort-a-web-request-using-abortcontrollers/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-abort-a-web-request-using-abortcontrollers\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"networking\"],\n  \"importance\": \"medium\",\n  \"ranking\": 300,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/how-do-you-abort-a-web-request-using-abortcontrollers/zh-CN.mdx",
    "content": "---\ntitle: 如何在 JavaScript 中使用 `AbortController` 终止 Web 请求？\n---\n\n## TL;DR\n\n`AbortController` 用于取消进行中的异步操作，例如 fetch 请求。\n\n```js live\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nfetch('https://jsonplaceholder.typicode.com/todos/1', { signal })\n  .then((response) => {\n    // Handle response\n  })\n  .catch((error) => {\n    if (error.name === 'AbortError') {\n      console.log('Request aborted');\n    } else {\n      console.error('Error:', error);\n    }\n  });\n\n// Call abort() to abort the request\ncontroller.abort();\n```\n\n终止 Web 请求对于以下情况很有用：\n\n* 根据用户操作取消请求。\n* 在有多个并发请求的情况下，优先处理最新的请求。\n* 取消不再需要的请求，例如，在用户已从页面导航离开之后。\n\n***\n\n## `AbortController`s\n\n`AbortController` 允许优雅地取消进行中的异步操作，例如 fetch 请求。 它提供了一种机制，向底层网络层发出信号，表明不再需要该请求，从而防止不必要的资源消耗并改善用户体验。\n\n## 使用 `AbortController`s\n\n使用 `AbortController` 涉及以下步骤：\n\n1. **创建 `AbortController` 实例**：初始化一个 `AbortController` 实例，它会创建一个可用于中止请求的信号。\n2. **将信号传递给请求**：将信号传递给请求，通常通过请求选项中的 `signal` 属性。\n3. **中止请求**：在 `AbortController` 实例上调用 `abort()` 方法以取消正在进行的请求。\n\n以下是如何将 `AbortController` 与 `fetch()` API 结合使用的示例：\n\n```js live\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nfetch('https://jsonplaceholder.typicode.com/todos/1', { signal })\n  .then((response) => {\n    // Handle response\n  })\n  .catch((error) => {\n    if (error.name === 'AbortError') {\n      console.log('Request aborted');\n    } else {\n      console.error('Error:', error);\n    }\n  });\n\n// Call abort() to abort the request\ncontroller.abort();\n```\n\n## 用例\n\n### 在用户操作时取消 `fetch()` 请求\n\n取消由于用户交互（例如，用户取消上传一个大文件）而导致耗时过长或不再相关的请求。\n\n```js live\n// HTML: <button id='cancel-button'>Cancel upload</button>\nconst btn = document.createElement('button');\nbtn.id = 'cancel-button';\nbtn.innerHTML = 'Cancel upload';\ndocument.body.appendChild(btn);\n\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nfetch('https://jsonplaceholder.typicode.com/todos/1', { signal })\n  .then((response) => {\n    // Handle successful response\n  })\n  .catch((error) => {\n    if (error.name === 'AbortError') {\n      console.log('Request canceled');\n    } else {\n      console.error('Network or other error:', error);\n    }\n  });\n\ndocument.getElementById('cancel-button').addEventListener('click', () => {\n  controller.abort();\n});\ndocument.getElementById('cancel-button').click(); // Simulate clicking the cancel button\n```\n\n当您单击“取消上传”按钮时，正在进行的请求将被中止。\n\n### 在竞争条件下优先处理最新请求\n\n在为相同数据启动多个请求的情况下，使用 `AbortController` 优先处理最新请求并中止较早的请求。\n\n```js live\nlet latestController = null; // Keeps track of the latest controller\n\nfunction fetchData(url) {\n  if (latestController) {\n    latestController.abort(); // Abort any previous request\n  }\n\n  const controller = new AbortController();\n  latestController = controller;\n  const signal = controller.signal;\n\n  fetch(url, { signal })\n    .then((response) => response.json())\n    .then((data) => console.log('Fetched data:', data))\n    .catch((error) => {\n      if (error.name === 'AbortError') {\n        console.log('Request canceled');\n      } else {\n        console.error('Network or other error:', error);\n      }\n    });\n}\n\nfetchData('https://jsonplaceholder.typicode.com/posts/1');\n\n// Simulate race conditions with new requests that quickly cancel the previous one\nsetTimeout(() => {\n  fetchData('https://jsonplaceholder.typicode.com/posts/2');\n}, 5);\nsetTimeout(() => {\n  fetchData('https://jsonplaceholder.typicode.com/posts/3');\n}, 5);\n// Only the last request should (posts/3) will be allowed to complete\n```\n\n在本例中，当多次调用 `fetchData()` 函数触发多个 fetch 请求时，`AbortController` 将取消所有之前的请求，除了最新的请求。这在诸如类型提示搜索或无限滚动等场景中很常见，在这些场景中，会频繁触发新的请求。\n\n### 取消不再需要的请求\n\n在用户已从页面导航出去的情况下，中止请求可以防止不必要的操作（例如，成功回调处理），并通过降低内存泄漏的可能性来释放资源。\n\n## 笔记\n\n* `AbortController` 不仅限于 `fetch()`，它也可以用于中止其他异步任务。\n* 一个单独的 `AbortContoller` 实例可以在多个异步任务上重复使用，并一次取消所有任务。\n* 在 `AbortController` 上调用 `abort()` 不会向服务器发送任何通知或信号。服务器不知道取消操作，并将继续处理请求，直到它完成或超时。\n\n## 延伸阅读\n\n* [AbortController | MDN](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)\n* [Fetch: Abort | Javascript.info](https://javascript.info/fetch-abort)\n"
  },
  {
    "path": "questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"944c644b\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"38163a0a\",\n        \"8def32e0\",\n        \"2a7816d0\",\n        \"8afe408d\",\n        \"57150fe8\",\n        \"8def32e0\",\n        \"c151373a\",\n        \"2608344a\",\n        \"1c30eb9b\",\n        \"3188acbe\",\n        \"105a896f\",\n        \"47f129\",\n        \"1f77a2b8\",\n        \"cc46a982\",\n        \"1f8d0cd7\",\n        \"1f4770e5\",\n        \"d40021a0\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"38163a0a\",\n        \"8def32e0\",\n        \"2a7816d0\",\n        \"8afe408d\",\n        \"57150fe8\",\n        \"8def32e0\",\n        \"c151373a\",\n        \"2608344a\",\n        \"1c30eb9b\",\n        \"3188acbe\",\n        \"105a896f\",\n        \"47f129\",\n        \"1f77a2b8\",\n        \"cc46a982\",\n        \"1f8d0cd7\",\n        \"1f4770e5\",\n        \"d40021a0\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/en-US.mdx",
    "content": "---\ntitle: How do you access the index of an element in an array during iteration?\n---\n\n## TL;DR\n\nTo access the index of an element in an array during iteration, you can use methods like `forEach`, `map`, `for...of` with `entries`, or a traditional `for` loop. For example, using `forEach`:\n\n```js live\nconst array = ['a', 'b', 'c'];\narray.forEach((element, index) => {\n  console.log(index, element);\n});\n```\n\n---\n\n## Using `forEach`\n\nThe `forEach` method executes a provided function once for each array element. The callback function takes three arguments: the current element, the index of the current element, and the array itself.\n\n```js live\nconst array = ['a', 'b', 'c'];\narray.forEach((element, index) => {\n  console.log(index, element);\n});\n```\n\n### Using `map`\n\nThe `map` method creates a new array populated with the results of calling a provided function on every element in the calling array. The callback function also takes three arguments: the current element, the index of the current element, and the array itself.\n\n```js live\nconst array = ['a', 'b', 'c'];\narray.map((element, index) => {\n  console.log(index, element);\n});\n```\n\n### Using `for...of` with `entries`\n\nThe `for...of` loop can be combined with the `entries` method to access both the index and the element.\n\n```js live\nconst array = ['a', 'b', 'c'];\nfor (const [index, element] of array.entries()) {\n  console.log(index, element);\n}\n```\n\n### Using a traditional `for` loop\n\nA traditional `for` loop gives you direct access to the index.\n\n```js live\nconst array = ['a', 'b', 'c'];\nfor (let index = 0; index < array.length; index++) {\n  console.log(index, array[index]);\n}\n```\n\n## Further reading\n\n- [MDN Web Docs: Array.prototype.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)\n- [MDN Web Docs: Array.prototype.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)\n- [MDN Web Docs: for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n- [MDN Web Docs: Array.prototype.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries)\n"
  },
  {
    "path": "questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-access-the-index-of-an-element-in-an-array-during-iteration\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Operators & Control Flow\"\n}\n"
  },
  {
    "path": "questions/how-do-you-access-the-index-of-an-element-in-an-array-during-iteration/zh-CN.mdx",
    "content": "---\ntitle: 如何在迭代过程中访问数组中元素的索引？\n---\n\n## TL;DR\n\n要在迭代过程中访问数组中元素的索引，可以使用 `forEach`、`map`、`for...of` 与 `entries` 或传统的 `for` 循环等方法。例如，使用 `forEach`：\n\n```js live\nconst array = ['a', 'b', 'c'];\narray.forEach((element, index) => {\n  console.log(index, element);\n});\n```\n\n***\n\n## 使用 `forEach`\n\n`forEach` 方法为数组的每个元素执行一次提供的函数。回调函数接受三个参数：当前元素、当前元素的索引和数组本身。\n\n```js live\nconst array = ['a', 'b', 'c'];\narray.forEach((element, index) => {\n  console.log(index, element);\n});\n```\n\n### 使用 `map`\n\n`map` 方法创建一个新数组，其中填充了在调用数组的每个元素上调用提供的函数的结果。回调函数也接受三个参数：当前元素、当前元素的索引和数组本身。\n\n```js live\nconst array = ['a', 'b', 'c'];\narray.map((element, index) => {\n  console.log(index, element);\n});\n```\n\n### 使用 `for...of` 与 `entries`\n\n`for...of` 循环可以与 `entries` 方法结合使用，以访问索引和元素。\n\n```js live\nconst array = ['a', 'b', 'c'];\nfor (const [index, element] of array.entries()) {\n  console.log(index, element);\n}\n```\n\n### 使用传统的 `for` 循环\n\n传统的 `for` 循环使您可以直接访问索引。\n\n```js live\nconst array = ['a', 'b', 'c'];\nfor (let index = 0; index < array.length; index++) {\n  console.log(index, array[index]);\n}\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Array.prototype.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)\n* [MDN Web Docs: Array.prototype.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)\n* [MDN Web Docs: for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n* [MDN Web Docs: Array.prototype.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries)\n"
  },
  {
    "path": "questions/how-do-you-add-remove-and-modify-html-elements-using-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"52206d51\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"ad01cafc\",\n        \"bd1a01ac\",\n        \"2a7816d0\",\n        \"2e6c2400\",\n        \"9d1c0301\",\n        \"842a85a9\",\n        \"598de6f9\",\n        \"9acc7143\",\n        \"961a5ab5\",\n        \"1b907146\",\n        \"f08c59c3\",\n        \"cd8c19b3\",\n        \"bc5b741e\",\n        \"d1c61dce\",\n        \"19d5c9fb\",\n        \"b99f6bdf\",\n        \"4187d33b\",\n        \"bf476af9\",\n        \"4550576a\",\n        \"1f4770e5\",\n        \"ddc93d9c\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"ad01cafc\",\n        \"bd1a01ac\",\n        \"2a7816d0\",\n        \"2e6c2400\",\n        \"9d1c0301\",\n        \"842a85a9\",\n        \"598de6f9\",\n        \"9acc7143\",\n        \"961a5ab5\",\n        \"1b907146\",\n        \"f08c59c3\",\n        \"cd8c19b3\",\n        \"bc5b741e\",\n        \"d1c61dce\",\n        \"19d5c9fb\",\n        \"b99f6bdf\",\n        \"4187d33b\",\n        \"bf476af9\",\n        \"4550576a\",\n        \"1f4770e5\",\n        \"ddc93d9c\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-add-remove-and-modify-html-elements-using-javascript/en-US.mdx",
    "content": "---\ntitle: How do you add, remove, and modify HTML elements using JavaScript?\n---\n\n## TL;DR\n\nTo add, remove, and modify HTML elements using JavaScript, you can use methods like `createElement`, `appendChild`, `removeChild`, and properties like `innerHTML` and `textContent`. For example, to add an element, you can create it using `document.createElement` and then append it to a parent element using `appendChild`. To remove an element, you can use `removeChild` on its parent. To modify an element, you can change its `innerHTML` or `textContent`.\n\n```js\n// Adding an element\nconst newElement = document.createElement('div');\nnewElement.textContent = 'Hello, World!';\ndocument.body.appendChild(newElement);\n\n// Removing an element\nconst elementToRemove = document.getElementById('elementId');\nelementToRemove.parentNode.removeChild(elementToRemove);\n\n// Modifying an element\nconst elementToModify = document.getElementById('elementId');\nelementToModify.innerHTML = 'New Content';\n```\n\n---\n\n## Adding, removing, and modifying HTML elements using JavaScript\n\n### Adding elements\n\nTo add an HTML element, you can use the `document.createElement` method to create a new element and then append it to a parent element using `appendChild`.\n\n```js live\n// Create a new div element\nconst newDiv = document.createElement('div');\n\n// Set its content\nnewDiv.textContent = 'Hello, World!';\n\n// Append the new element to the body\ndocument.body.appendChild(newDiv);\n\n// See the changed document by running the code\nconsole.log(document.body);\n```\n\nYou can also use `insertBefore` to insert the new element before an existing child element.\n\n```js\nconst parentElement = document.getElementById('parent');\nconst newElement = document.createElement('p');\nnewElement.textContent = 'Inserted Paragraph';\nconst referenceElement = document.getElementById('reference');\nparentElement.insertBefore(newElement, referenceElement);\n```\n\n### Removing elements\n\nTo remove an HTML element, you can use the `removeChild` method on its parent element.\n\n```js\n// Select the element to be removed\nconst elementToRemove = document.getElementById('elementId');\n\n// Remove the element\nelementToRemove.parentNode.removeChild(elementToRemove);\n```\n\nAlternatively, you can use the `remove` method directly on the element.\n\n```js\nconst elementToRemove = document.getElementById('elementId');\nelementToRemove.remove();\n```\n\n### Modifying elements\n\nTo modify an HTML element, you can change its properties such as `innerHTML`, `textContent`, or attributes.\n\n```js live\nconst elementToModify = document.createElement('div');\n\n// Change its inner HTML\nelementToModify.innerHTML = 'New Content';\n\n// Change its text content\nelementToModify.textContent = 'New Text Content';\n\n// Change an attribute\nelementToModify.setAttribute('class', 'new-class');\n\nconsole.log(elementToModify);\n```\n\nYou can also use methods like `classList.add`, `classList.remove`, and `classList.toggle` to modify the element's classes.\n\n```js\nconst element = document.getElementById('elementId');\n\n// Add a class\nelement.classList.add('new-class');\n\n// Remove a class\nelement.classList.remove('old-class');\n\n// Toggle a class\nelement.classList.toggle('active');\n```\n\n## Further reading\n\n- [MDN Web Docs: Document.createElement](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement)\n- [MDN Web Docs: Node.appendChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild)\n- [MDN Web Docs: Node.removeChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild)\n- [MDN Web Docs: Element.innerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML)\n- [MDN Web Docs: Element.textContent](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent)\n- [MDN Web Docs: Element.classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)\n"
  },
  {
    "path": "questions/how-do-you-add-remove-and-modify-html-elements-using-javascript/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-add-remove-and-modify-html-elements-using-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"web-api\", \"javascript\", \"html\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"DOM Manipulation & Events\"\n}\n"
  },
  {
    "path": "questions/how-do-you-add-remove-and-modify-html-elements-using-javascript/zh-CN.mdx",
    "content": "---\ntitle: 如何使用 JavaScript 添加、删除和修改 HTML 元素？\n---\n\n## TL;DR\n\n要使用 JavaScript 添加、删除和修改 HTML 元素，可以使用 `createElement`、`appendChild`、`removeChild` 等方法以及 `innerHTML` 和 `textContent` 等属性。例如，要添加一个元素，可以使用 `document.createElement` 创建它，然后使用 `appendChild` 将其附加到父元素。要删除一个元素，可以在其父元素上使用 `removeChild`。要修改一个元素，可以更改其 `innerHTML` 或 `textContent`。\n\n```js\n// Adding an element\nconst newElement = document.createElement('div');\nnewElement.textContent = 'Hello, World!';\ndocument.body.appendChild(newElement);\n\n// Removing an element\nconst elementToRemove = document.getElementById('elementId');\nelementToRemove.parentNode.removeChild(elementToRemove);\n\n// Modifying an element\nconst elementToModify = document.getElementById('elementId');\nelementToModify.innerHTML = 'New Content';\n```\n\n***\n\n## 使用 JavaScript 添加、删除和修改 HTML 元素\n\n### 添加元素\n\n要添加 HTML 元素，可以使用 `document.createElement` 方法创建一个新元素，然后使用 `appendChild` 将其附加到父元素。\n\n```js live\n// Create a new div element\nconst newDiv = document.createElement('div');\n\n// Set its content\nnewDiv.textContent = 'Hello, World!';\n\n// Append the new element to the body\ndocument.body.appendChild(newDiv);\n\n// See the changed document by running the code\nconsole.log(document.body);\n```\n\n您还可以使用 `insertBefore` 在现有子元素之前插入新元素。\n\n```js\nconst parentElement = document.getElementById('parent');\nconst newElement = document.createElement('p');\nnewElement.textContent = 'Inserted Paragraph';\nconst referenceElement = document.getElementById('reference');\nparentElement.insertBefore(newElement, referenceElement);\n```\n\n### 删除元素\n\n要删除 HTML 元素，可以在其父元素上使用 `removeChild` 方法。\n\n```js\n// Select the element to be removed\nconst elementToRemove = document.getElementById('elementId');\n\n// Remove the element\nelementToRemove.parentNode.removeChild(elementToRemove);\n```\n\n或者，您可以在该元素上直接使用 `remove` 方法。\n\n```js\nconst elementToRemove = document.getElementById('elementId');\nelementToRemove.remove();\n```\n\n### 修改元素\n\n要修改 HTML 元素，您可以更改其属性，例如 `innerHTML`、`textContent` 或属性。\n\n```js live\nconst elementToModify = document.createElement('div');\n\n// Change its inner HTML\nelementToModify.innerHTML = 'New Content';\n\n// Change its text content\nelementToModify.textContent = 'New Text Content';\n\n// Change an attribute\nelementToModify.setAttribute('class', 'new-class');\n\nconsole.log(elementToModify);\n```\n\n您还可以使用 `classList.add`、`classList.remove` 和 `classList.toggle` 等方法来修改元素的类。\n\n```js\nconst element = document.getElementById('elementId');\n\n// Add a class\nelement.classList.add('new-class');\n\n// Remove a class\nelement.classList.remove('old-class');\n\n// Toggle a class\nelement.classList.toggle('active');\n```\n\n## 延伸阅读\n\n* [MDN Web 文档：Document.createElement](https://developer.mozilla.org/zh-CN/docs/Web/API/Document/createElement)\n* [MDN Web 文档：Node.appendChild](https://developer.mozilla.org/zh-CN/docs/Web/API/Node/appendChild)\n* [MDN Web 文档：Node.removeChild](https://developer.mozilla.org/zh-CN/docs/Web/API/Node/removeChild)\n* [MDN Web 文档：Element.innerHTML](https://developer.mozilla.org/zh-CN/docs/Web/API/Element/innerHTML)\n* [MDN Web 文档：Element.textContent](https://developer.mozilla.org/zh-CN/docs/Web/API/Node/textContent)\n* [MDN Web 文档：Element.classList](https://developer.mozilla.org/zh-CN/docs/Web/API/Element/classList)\n"
  },
  {
    "path": "questions/how-do-you-add-remove-and-update-elements-in-an-array/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"f867d152\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"9c6cbc97\",\n        \"8c530221\",\n        \"77dbca1e\",\n        \"2a7816d0\",\n        \"42d739cd\",\n        \"d5d1d144\",\n        \"6a6e4bfc\",\n        \"29f48398\",\n        \"aa93d480\",\n        \"2d0b0765\",\n        \"10399246\",\n        \"15cbfb04\",\n        \"6c294d6\",\n        \"d01b2fce\",\n        \"6b5d1be4\",\n        \"d86b8d40\",\n        \"e44621ec\",\n        \"8a608c4e\",\n        \"8c47e77c\",\n        \"a9d80323\",\n        \"5f1b58e6\",\n        \"15cbfb04\",\n        \"80fa7e69\",\n        \"a1d66e98\",\n        \"5195f94c\",\n        \"1dfcd69f\",\n        \"da06c2a0\",\n        \"132fa112\",\n        \"1f4770e5\",\n        \"76e7d675\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"9c6cbc97\",\n        \"8c530221\",\n        \"77dbca1e\",\n        \"2a7816d0\",\n        \"42d739cd\",\n        \"d5d1d144\",\n        \"6a6e4bfc\",\n        \"29f48398\",\n        \"aa93d480\",\n        \"2d0b0765\",\n        \"10399246\",\n        \"15cbfb04\",\n        \"6c294d6\",\n        \"d01b2fce\",\n        \"6b5d1be4\",\n        \"d86b8d40\",\n        \"e44621ec\",\n        \"8a608c4e\",\n        \"8c47e77c\",\n        \"a9d80323\",\n        \"5f1b58e6\",\n        \"15cbfb04\",\n        \"80fa7e69\",\n        \"a1d66e98\",\n        \"5195f94c\",\n        \"1dfcd69f\",\n        \"da06c2a0\",\n        \"132fa112\",\n        \"1f4770e5\",\n        \"76e7d675\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-add-remove-and-update-elements-in-an-array/en-US.mdx",
    "content": "---\ntitle: How do you add, remove, and update elements in an array?\n---\n\n## TL;DR\n\nTo add elements to an array, you can use methods like `push`, `unshift`, or `splice`. To remove elements, you can use `pop`, `shift`, or `splice`. To update elements, you can directly access the array index and assign a new value.\n\n```js live\nlet arr = [1, 2, 3];\n\n// Add elements\narr.push(4); // [1, 2, 3, 4]\narr.unshift(0); // [0, 1, 2, 3, 4]\narr.splice(2, 0, 1.5); // [0, 1, 1.5, 2, 3, 4]\n\n// Remove elements\narr.pop(); // [0, 1, 1.5, 2, 3]\narr.shift(); // [1, 1.5, 2, 3]\narr.splice(1, 1); // [1, 2, 3]\n\n// Update elements\narr[1] = 5; // [1, 5, 3]\nconsole.log(arr); // Final state: [1, 5, 3]\n```\n\n**Note**: If you try to `console.log(arr)` after each operation in some environments (like Chrome DevTools), you may only see the final state of `arr`. This happens because the console sometimes keeps a live reference to the array instead of logging its state at the exact moment. To see intermediate states properly, store snapshots using `console.log([...arr])` or print values immediately after each operation.\n\n---\n\n## Adding elements to an array\n\n### Using `push`\n\nThe `push` method adds one or more elements to the end of an array and returns the new length of the array.\n\n```js live\nlet arr = [1, 2, 3];\nconsole.log(arr.push(4)); // Output: 4 (new length of array)\nconsole.log(arr); // [1, 2, 3, 4]\n```\n\n### Using `unshift`\n\nThe `unshift` method adds one or more elements to the beginning of an array and returns the new length of the array.\n\n```js live\nlet arr = [1, 2, 3];\nconsole.log(arr.unshift(0)); // Output: 4 (new length of array)\nconsole.log(arr); // [0, 1, 2, 3]\n```\n\n### Using `splice`\n\nThe `splice` method can add elements at any position in the array. The first parameter specifies the index at which to start changing the array, the second parameter specifies the number of elements to remove, and the rest are the elements to add.\n\n```js live\nlet arr = [1, 2, 3];\narr.splice(1, 0, 1.5); // Removes no element, but adds 1.5\nconsole.log(arr); // [1, 1.5, 2, 3]\n```\n\n## Removing elements from an array\n\n### Using `pop`\n\nThe `pop` method removes the last element from an array and returns that element.\n\n```js live\nlet arr = [1, 2, 3];\nconsole.log(arr.pop()); // Output: 3\nconsole.log(arr); // [1, 2]\n```\n\n### Using `shift`\n\nThe `shift` method removes the first element from an array and returns that element.\n\n```js live\nlet arr = [1, 2, 3];\nconsole.log(arr.shift()); // Output: 1\nconsole.log(arr); // [2, 3]\n```\n\n### Using `splice`\n\nThe `splice` method can also remove elements from any position in the array. The first parameter specifies the index at which to start changing the array, and the second parameter specifies the number of elements to remove.\n\n```js live\nlet arr = [1, 2, 3, 4];\nconsole.log(arr.splice(1, 2)); // Output: [2, 3]\nconsole.log(arr); // [1, 4]\n```\n\n## Updating elements in an array\n\n### Direct assignment\n\nYou can update elements in an array by directly accessing the index and assigning a new value.\n\n```js live\nlet arr = [1, 2, 3];\narr[1] = 5;\nconsole.log(arr); // [1, 5, 3]\n```\n\n## Further reading\n\n- [MDN Web Docs: Array.prototype.push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)\n- [MDN Web Docs: Array.prototype.unshift](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift)\n- [MDN Web Docs: Array.prototype.splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)\n- [MDN Web Docs: Array.prototype.pop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop)\n- [MDN Web Docs: Array.prototype.shift](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift)\n"
  },
  {
    "path": "questions/how-do-you-add-remove-and-update-elements-in-an-array/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-add-remove-and-update-elements-in-an-array\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/how-do-you-add-remove-and-update-elements-in-an-array/zh-CN.mdx",
    "content": "---\ntitle: 如何添加、删除和更新数组中的元素？\n---\n\n## TL;DR\n\n要向数组添加元素，可以使用 `push`、`unshift` 或 `splice` 等方法。要删除元素，可以使用 `pop`、`shift` 或 `splice`。要更新元素，可以直接访问数组索引并分配一个新值。\n\n```js live\nlet arr = [1, 2, 3];\n\n// Add elements\narr.push(4); // [1, 2, 3, 4]\narr.unshift(0); // [0, 1, 2, 3, 4]\narr.splice(2, 0, 1.5); // [0, 1, 1.5, 2, 3, 4]\n\n// Remove elements\narr.pop(); // [0, 1, 1.5, 2, 3]\narr.shift(); // [1, 1.5, 2, 3]\narr.splice(1, 1); // [1, 2, 3]\n\n// Update elements\narr[1] = 5; // [1, 5, 3]\nconsole.log(arr); // Final state: [1, 5, 3]\n```\n\n**注意**：如果在某些环境（如 Chrome DevTools）中尝试在每次操作后使用 `console.log(arr)`，您可能只能看到 `arr` 的最终状态。这是因为控制台有时会保留对数组的实时引用，而不是记录其确切时刻的状态。要正确查看中间状态，请使用 `console.log([...arr])` 存储快照，或在每次操作后立即打印值。\n\n***\n\n## 向数组添加元素\n\n### 使用 `push`\n\n`push` 方法将一个或多个元素添加到数组的末尾，并返回数组的新长度。\n\n```js live\nlet arr = [1, 2, 3];\nconsole.log(arr.push(4)); // Output: 4 (new length of array)\nconsole.log(arr); // [1, 2, 3, 4]\n```\n\n### 使用 `unshift`\n\n`unshift` 方法将一个或多个元素添加到数组的开头，并返回数组的新长度。\n\n```js live\nlet arr = [1, 2, 3];\nconsole.log(arr.unshift(0)); // Output: 4 (new length of array)\nconsole.log(arr); // [0, 1, 2, 3]\n```\n\n### 使用 `splice`\n\n`splice` 方法可以在数组中的任何位置添加元素。第一个参数指定开始更改数组的索引，第二个参数指定要删除的元素数量，其余的是要添加的元素。\n\n```js live\nlet arr = [1, 2, 3];\narr.splice(1, 0, 1.5); // Removes no element, but adds 1.5\nconsole.log(arr); // [1, 1.5, 2, 3]\n```\n\n## 从数组中删除元素\n\n### 使用 `pop`\n\n`pop` 方法从数组中删除最后一个元素并返回该元素。\n\n```js live\nlet arr = [1, 2, 3];\nconsole.log(arr.pop()); // Output: 3\nconsole.log(arr); // [1, 2]\n```\n\n### 使用 `shift`\n\n`shift` 方法从数组中删除第一个元素，并返回该元素。\n\n```js live\nlet arr = [1, 2, 3];\nconsole.log(arr.shift()); // Output: 1\nconsole.log(arr); // [2, 3]\n```\n\n### 使用 `splice`\n\n`splice` 方法也可以从数组中的任何位置删除元素。第一个参数指定开始更改数组的索引，第二个参数指定要删除的元素数量。\n\n```js live\nlet arr = [1, 2, 3, 4];\nconsole.log(arr.splice(1, 2)); // Output: [2, 3]\nconsole.log(arr); // [1, 4]\n```\n\n## 更新数组中的元素\n\n### 直接赋值\n\n您可以通过直接访问索引并分配新值来更新数组中的元素。\n\n```js live\nlet arr = [1, 2, 3];\narr[1] = 5;\nconsole.log(arr); // [1, 5, 3]\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Array.prototype.push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)\n* [MDN Web Docs: Array.prototype.unshift](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift)\n* [MDN Web Docs: Array.prototype.splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)\n* [MDN Web Docs: Array.prototype.pop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop)\n* [MDN Web Docs: Array.prototype.shift](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift)\n"
  },
  {
    "path": "questions/how-do-you-check-if-an-object-has-a-specific-property/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"37795a30\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"d3e286b8\",\n        \"c3030fc6\",\n        \"2a7816d0\",\n        \"f95d861f\",\n        \"48898820\",\n        \"fca4759a\",\n        \"502efdc2\",\n        \"8290aad7\",\n        \"d723dfa4\",\n        \"fde98498\",\n        \"972e8d49\",\n        \"d2a6ba28\",\n        \"aa9dd9ec\",\n        \"65593564\",\n        \"1f4770e5\",\n        \"c6a7da2c\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d3e286b8\",\n        \"c3030fc6\",\n        \"2a7816d0\",\n        \"f95d861f\",\n        \"48898820\",\n        \"fca4759a\",\n        \"502efdc2\",\n        \"8290aad7\",\n        \"d723dfa4\",\n        \"fde98498\",\n        \"972e8d49\",\n        \"d2a6ba28\",\n        \"aa9dd9ec\",\n        \"65593564\",\n        \"1f4770e5\",\n        \"c6a7da2c\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-check-if-an-object-has-a-specific-property/en-US.mdx",
    "content": "---\ntitle: How do you check if an object has a specific property?\n---\n\n## TL;DR\n\nTo check if an object has a specific property, you can use the `in` operator or the `hasOwnProperty` method. The `in` operator checks for both own and inherited properties, while `hasOwnProperty` checks only for own properties.\n\n```js live\nconst obj = { key: 'value' };\n\n// Using the `in` operator\nif ('key' in obj) {\n  console.log('Property exists');\n}\n\n// Using `hasOwnProperty`\nif (obj.hasOwnProperty('key')) {\n  console.log('Property exists');\n}\n```\n\n---\n\n## How do you check if an object has a specific property?\n\n### Using the `in` operator\n\nThe `in` operator checks if a property exists in an object, including properties in the object's prototype chain.\n\n```js live\nconst obj = { key: 'value' };\n\nif ('key' in obj) {\n  console.log('Property exists');\n}\n```\n\n### Using `hasOwnProperty`\n\nThe `hasOwnProperty` method checks if a property exists directly on the object, not in its prototype chain.\n\n```js live\nconst obj = { key: 'value' };\n\nif (obj.hasOwnProperty('key')) {\n  console.log('Property exists');\n}\n```\n\n### Differences between `in` and `hasOwnProperty`\n\n- The `in` operator checks for both own and inherited properties.\n- The `hasOwnProperty` method checks only for own properties.\n\n### Example with inherited properties\n\n```js live\nconst parentObj = { inheritedKey: 'inheritedValue' };\nconst childObj = Object.create(parentObj);\nchildObj.ownKey = 'ownValue';\n\nconsole.log('inheritedKey' in childObj); // true\nconsole.log(childObj.hasOwnProperty('inheritedKey')); // false\nconsole.log('ownKey' in childObj); // true\nconsole.log(childObj.hasOwnProperty('ownKey')); // true\n```\n\n## Further reading\n\n- [MDN Web Docs: in operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in)\n- [MDN Web Docs: Object.prototype.hasOwnProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)\n"
  },
  {
    "path": "questions/how-do-you-check-if-an-object-has-a-specific-property/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-check-if-an-object-has-a-specific-property\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/how-do-you-check-if-an-object-has-a-specific-property/zh-CN.mdx",
    "content": "---\ntitle: 如何检查对象是否具有特定属性？\n---\n\n## TL;DR\n\n要检查对象是否具有特定属性，可以使用 `in` 运算符或 `hasOwnProperty` 方法。`in` 运算符检查自有属性和继承属性，而 `hasOwnProperty` 仅检查自有属性。\n\n```js live\nconst obj = { key: 'value' };\n\n// 使用 `in` 运算符\nif ('key' in obj) {\n  console.log('Property exists');\n}\n\n// 使用 `hasOwnProperty`\nif (obj.hasOwnProperty('key')) {\n  console.log('Property exists');\n}\n```\n\n***\n\n## 如何检查对象是否具有特定属性？\n\n### 使用 `in` 运算符\n\n`in` 运算符检查属性是否存在于对象中，包括对象原型链中的属性。\n\n```js live\nconst obj = { key: 'value' };\n\nif ('key' in obj) {\n  console.log('Property exists');\n}\n```\n\n### 使用 `hasOwnProperty`\n\n`hasOwnProperty` 方法检查属性是否直接存在于对象上，而不是在其原型链中。\n\n```js live\nconst obj = { key: 'value' };\n\nif (obj.hasOwnProperty('key')) {\n  console.log('Property exists');\n}\n```\n\n### `in` 和 `hasOwnProperty` 之间的区别\n\n* `in` 运算符检查自有属性和继承属性。\n* `hasOwnProperty` 方法仅检查自有属性。\n\n### 具有继承属性的示例\n\n```js live\nconst parentObj = { inheritedKey: 'inheritedValue' };\nconst childObj = Object.create(parentObj);\nchildObj.ownKey = 'ownValue';\n\nconsole.log('inheritedKey' in childObj); // true\nconsole.log(childObj.hasOwnProperty('inheritedKey')); // false\nconsole.log('ownKey' in childObj); // true\nconsole.log(childObj.hasOwnProperty('ownKey')); // true\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: in operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in)\n* [MDN Web Docs: Object.prototype.hasOwnProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty)\n"
  },
  {
    "path": "questions/how-do-you-check-the-data-type-of-a-variable/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"bca54652\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3861efe0\",\n        \"2a7816d0\",\n        \"6d38e731\",\n        \"5c53eee5\",\n        \"17179c3d\",\n        \"e2f91808\",\n        \"1d3d0025\",\n        \"25c20d60\",\n        \"e9b10e7d\",\n        \"4c828591\",\n        \"9e29b63a\",\n        \"73c17ccf\",\n        \"8867e535\",\n        \"d81372eb\",\n        \"9ba2a2f9\",\n        \"58e8d0e\",\n        \"4596bbc\",\n        \"f111ab2e\",\n        \"1f4770e5\",\n        \"11567994\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3861efe0\",\n        \"2a7816d0\",\n        \"6d38e731\",\n        \"5c53eee5\",\n        \"17179c3d\",\n        \"e2f91808\",\n        \"1d3d0025\",\n        \"25c20d60\",\n        \"e9b10e7d\",\n        \"4c828591\",\n        \"9e29b63a\",\n        \"73c17ccf\",\n        \"8867e535\",\n        \"d81372eb\",\n        \"9ba2a2f9\",\n        \"58e8d0e\",\n        \"4596bbc\",\n        \"f111ab2e\",\n        \"1f4770e5\",\n        \"11567994\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-check-the-data-type-of-a-variable/en-US.mdx",
    "content": "---\ntitle: How do you check the data type of a variable?\n---\n\n## TL;DR\n\nTo check the data type of a variable in JavaScript, you can use the `typeof` operator. For example, `typeof variableName` will return a string indicating the type of the variable, such as `\"string\"`, `\"number\"`, `\"boolean\"`, `\"object\"`, `\"function\"`, `\"undefined\"`, or `\"symbol\"`. For arrays and `null`, you can use `Array.isArray(variableName)` and `variableName === null`, respectively.\n\n---\n\n## How do you check the data type of a variable?\n\n### Using the `typeof` operator\n\nThe `typeof` operator is the most common way to check the data type of a variable in JavaScript. It returns a string indicating the type of the operand.\n\n```js live\nlet str = 'Hello, world!';\nconsole.log(typeof str); // \"string\"\n\nlet num = 42;\nconsole.log(typeof num); // \"number\"\n\nlet bool = true;\nconsole.log(typeof bool); // \"boolean\"\n\nlet obj = { name: 'Alice' };\nconsole.log(typeof obj); // \"object\"\n\nlet func = function () {};\nconsole.log(typeof func); // \"function\"\n\nlet undef;\nconsole.log(typeof undef); // \"undefined\"\n\nlet sym = Symbol();\nconsole.log(typeof sym); // \"symbol\"\n```\n\n### Checking for `null`\n\nThe `typeof` operator returns `\"object\"` for `null`, which can be misleading. To specifically check for `null`, you should use a strict equality comparison.\n\n```js live\nlet n = null;\nconsole.log(n === null); // true\n```\n\n### Checking for arrays\n\nArrays are a special type of object in JavaScript. To check if a variable is an array, you can use the `Array.isArray` method.\n\n```js live\nlet arr = [1, 2, 3];\nconsole.log(Array.isArray(arr)); // true\n```\n\n### Checking for `NaN`\n\n`NaN` (Not-a-Number) is a special numeric value in JavaScript. To check if a value is `NaN`, you can use the `Number.isNaN` method.\n\n```js live\nlet notANumber = NaN;\nconsole.log(Number.isNaN(notANumber)); // true\n```\n\n### Checking for `null` and `undefined`\n\nTo check if a variable is either `null` or `undefined`, you can use a combination of the `==` operator and the `typeof` operator.\n\n```js live\nlet value = null;\nconsole.log(value == null); // true\n\nlet value2;\nconsole.log(typeof value2 === 'undefined'); // true\n```\n\n## Further reading\n\n- [MDN Web Docs: typeof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)\n- [MDN Web Docs: Array.isArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)\n- [MDN Web Docs: Number.isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN)\n- [MDN Web Docs: null](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null)\n"
  },
  {
    "path": "questions/how-do-you-check-the-data-type-of-a-variable/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-check-the-data-type-of-a-variable\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Data Types & Variables\"\n}\n"
  },
  {
    "path": "questions/how-do-you-check-the-data-type-of-a-variable/zh-CN.mdx",
    "content": "---\ntitle: 如何检查变量的数据类型？\n---\n\n## TL;DR\n\n要在 JavaScript 中检查变量的数据类型，可以使用 `typeof` 运算符。例如，`typeof variableName` 将返回一个字符串，指示变量的类型，例如 `\"string\"`、`\"number\"`、`\"boolean\"`、`\"object\"`、`\"function\"`、`\"undefined\"` 或 `\"symbol\"`。对于数组和 `null`，您可以分别使用 `Array.isArray(variableName)` 和 `variableName === null`。\n\n***\n\n## 如何检查变量的数据类型？\n\n### 使用 `typeof` 运算符\n\n`typeof` 运算符是检查 JavaScript 中变量数据类型最常用的方法。它返回一个字符串，指示操作数的类型。\n\n```js live\nlet str = 'Hello, world!';\nconsole.log(typeof str); // \"string\"\n\nlet num = 42;\nconsole.log(typeof num); // \"number\"\n\nlet bool = true;\nconsole.log(typeof bool); // \"boolean\"\n\nlet obj = { name: 'Alice' };\nconsole.log(typeof obj); // \"object\"\n\nlet func = function () {};\nconsole.log(typeof func); // \"function\"\n\nlet undef;\nconsole.log(typeof undef); // \"undefined\"\n\nlet sym = Symbol();\nconsole.log(typeof sym); // \"symbol\"\n```\n\n### 检查 `null`\n\n`typeof` 运算符对 `null` 返回 `\"object\"`，这可能会产生误导。要专门检查 `null`，您应该使用严格的相等比较。\n\n```js live\nlet n = null;\nconsole.log(n === null); // true\n```\n\n### 检查数组\n\n数组是 JavaScript 中一种特殊类型的对象。要检查变量是否为数组，可以使用 `Array.isArray` 方法。\n\n```js live\nlet arr = [1, 2, 3];\nconsole.log(Array.isArray(arr)); // true\n```\n\n### 检查 `NaN`\n\n`NaN` (Not-a-Number) 是 JavaScript 中的一个特殊的数值。要检查一个值是否为 `NaN`，可以使用 `Number.isNaN` 方法。\n\n```js live\nlet notANumber = NaN;\nconsole.log(Number.isNaN(notANumber)); // true\n```\n\n### 检查 `null` 和 `undefined`\n\n要检查变量是 `null` 还是 `undefined`，可以使用 `==` 运算符和 `typeof` 运算符的组合。\n\n```js live\nlet value = null;\nconsole.log(value == null); // true\n\nlet value2;\nconsole.log(typeof value2 === 'undefined'); // true\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: typeof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)\n* [MDN Web Docs: Array.isArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray)\n* [MDN Web Docs: Number.isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN)\n* [MDN Web Docs: null](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null)\n"
  },
  {
    "path": "questions/how-do-you-convert-a-set-to-an-array-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"7482a008\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"9f9e979b\",\n        \"4e7ceb05\",\n        \"2a7816d0\",\n        \"ff3155c3\",\n        \"5b5cb2f6\",\n        \"398d0e72\",\n        \"9dfc7c21\",\n        \"16f3aaf5\",\n        \"712c5871\",\n        \"adbdd43e\",\n        \"c500fc82\",\n        \"b08ab0aa\",\n        \"1f4770e5\",\n        \"84276796\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"9f9e979b\",\n        \"4e7ceb05\",\n        \"2a7816d0\",\n        \"ff3155c3\",\n        \"5b5cb2f6\",\n        \"398d0e72\",\n        \"9dfc7c21\",\n        \"16f3aaf5\",\n        \"712c5871\",\n        \"adbdd43e\",\n        \"c500fc82\",\n        \"b08ab0aa\",\n        \"1f4770e5\",\n        \"84276796\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-convert-a-set-to-an-array-in-javascript/en-US.mdx",
    "content": "---\ntitle: How do you convert a `Set` to an array in JavaScript?\n---\n\n## TL;DR\n\nTo convert a `Set` to an array in JavaScript, you can use the `Array.from()` method or the spread operator. For example:\n\n```js live\nconst mySet = new Set([1, 2, 3]);\nconst myArray = Array.from(mySet);\n// OR const myArray = [...mySet];\n\nconsole.log(myArray); // Output: [1, 2, 3]\n```\n\n---\n\n## How do you convert a `Set` to an array in JavaScript?\n\n### Using `Array.from()`\n\nThe `Array.from()` method creates a new, shallow-copied array instance from an array-like or iterable object, such as a `Set`.\n\n```js live\nconst mySet = new Set([1, 2, 3]);\nconst myArray = Array.from(mySet);\nconsole.log(myArray); // Output: [1, 2, 3]\n```\n\n### Using the spread operator\n\nThe spread operator (`...`) can be used to expand the elements of a `Set` into an array.\n\n```js live\nconst mySet = new Set([1, 2, 3]);\nconst myArray = [...mySet];\nconsole.log(myArray); // Output: [1, 2, 3]\n```\n\n### Performance considerations\n\nBoth methods are efficient and commonly used. However, the spread operator is often considered more concise and readable. Performance differences are generally negligible for most use cases, but for very large sets, you might want to benchmark both methods to see which performs better in your specific scenario.\n\n## Further reading\n\n- [MDN Web Docs: Array.from()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)\n- [MDN Web Docs: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n- [MDN Web Docs: Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)\n"
  },
  {
    "path": "questions/how-do-you-convert-a-set-to-an-array-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-convert-a-set-to-an-array-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Sets & Maps\"\n}\n"
  },
  {
    "path": "questions/how-do-you-convert-a-set-to-an-array-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 如何在 JavaScript 中将 `Set` 转换为数组？\n---\n\n## TL;DR\n\n要在 JavaScript 中将 `Set` 转换为数组，可以使用 `Array.from()` 方法或扩展运算符。例如：\n\n```js live\nconst mySet = new Set([1, 2, 3]);\nconst myArray = Array.from(mySet);\n// OR const myArray = [...mySet];\n\nconsole.log(myArray); // Output: [1, 2, 3]\n```\n\n***\n\n## 如何在 JavaScript 中将 `Set` 转换为数组？\n\n### 使用 `Array.from()`\n\n`Array.from()` 方法从类似数组或可迭代对象（例如 `Set`）创建一个新的、浅拷贝的数组实例。\n\n```js live\nconst mySet = new Set([1, 2, 3]);\nconst myArray = Array.from(mySet);\nconsole.log(myArray); // Output: [1, 2, 3]\n```\n\n### 使用扩展运算符\n\n扩展运算符 (`...`) 可用于将 `Set` 的元素展开到数组中。\n\n```js live\nconst mySet = new Set([1, 2, 3]);\nconst myArray = [...mySet];\nconsole.log(myArray); // Output: [1, 2, 3]\n```\n\n### 性能考量\n\n这两种方法都高效且常用。但是，扩展运算符通常被认为更简洁易读。对于大多数用例，性能差异通常可以忽略不计，但对于非常大的集合，您可能需要对这两种方法进行基准测试，以查看哪种方法在您的特定场景中表现更好。\n\n## 延伸阅读\n\n* [MDN Web Docs: Array.from()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)\n* [MDN Web Docs: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n* [MDN Web Docs: Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)\n"
  },
  {
    "path": "questions/how-do-you-convert-a-string-to-a-number-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"1fe46ad4\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"72bfbeba\",\n        \"2a7816d0\",\n        \"ff093738\",\n        \"18656ac0\",\n        \"69c14205\",\n        \"ee13ede1\",\n        \"4333a2ea\",\n        \"3a855bf6\",\n        \"e7e1ff92\",\n        \"aaa562b2\",\n        \"bbcd9075\",\n        \"c12a9d77\",\n        \"c53b841b\",\n        \"44e42eb2\",\n        \"7351b3ea\",\n        \"95a1b822\",\n        \"6484d89\",\n        \"afe9c39e\",\n        \"1f4770e5\",\n        \"181eade1\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"72bfbeba\",\n        \"2a7816d0\",\n        \"ff093738\",\n        \"18656ac0\",\n        \"69c14205\",\n        \"ee13ede1\",\n        \"4333a2ea\",\n        \"3a855bf6\",\n        \"e7e1ff92\",\n        \"aaa562b2\",\n        \"bbcd9075\",\n        \"c12a9d77\",\n        \"c53b841b\",\n        \"44e42eb2\",\n        \"7351b3ea\",\n        \"95a1b822\",\n        \"6484d89\",\n        \"afe9c39e\",\n        \"1f4770e5\",\n        \"181eade1\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-convert-a-string-to-a-number-in-javascript/en-US.mdx",
    "content": "---\ntitle: How do you convert a string to a number in JavaScript?\n---\n\n## TL;DR\n\nIn JavaScript, you can convert a string to a number using several methods. The most common ones are `Number()`, `parseInt()`, `parseFloat()`, and the unary plus operator (`+`). For example, `Number(\"123\")` converts the string `\"123\"` to the number `123`, and `parseInt(\"123.45\")` converts the string `\"123.45\"` to the integer `123`.\n\n---\n\n## How do you convert a string to a number in JavaScript?\n\n### Using the `Number()` function\n\nThe `Number()` function converts a string to a number. It can handle both integer and floating-point numbers.\n\n```js live\nlet str = '123';\nlet num = Number(str);\nconsole.log(num); // 123\n\nlet floatStr = '123.45';\nlet floatNum = Number(floatStr);\nconsole.log(floatNum); // 123.45\n```\n\n### Using the `parseInt()` function\n\nThe `parseInt()` function parses a string and returns an integer. It can also take a second argument, the radix (base) of the numeral system to be used.\n\n```js live\nlet str = '123';\nlet num = parseInt(str);\nconsole.log(num); // 123\n\nlet floatStr = '120.45';\nlet floatNum = parseInt(floatStr);\nconsole.log(floatNum); // 120\n\nlet binaryStr = '1010';\nlet binaryNum = parseInt(binaryStr, 2);\nconsole.log(binaryNum); // 10\n```\n\n### Using the `parseFloat()` function\n\nThe `parseFloat()` function parses a string and returns a floating-point number.\n\n```js live\nlet floatStr = '123.45';\nlet floatNum = parseFloat(floatStr);\nconsole.log(floatNum); // 123.45\n```\n\n### Using the unary plus operator (`+`)\n\nThe unary plus operator can be used to convert a string to a number. It is a shorthand method and works for both integers and floating-point numbers.\n\n```js live\nlet str = '123';\nlet num = +str;\nconsole.log(num); // 123\n\nlet floatStr = '123.45';\nlet floatNum = +floatStr;\nconsole.log(floatNum); // 123.45\n```\n\n### Handling non-numeric strings\n\nIf the string cannot be converted to a number, these methods will return `NaN` (Not-a-Number).\n\n```js live\nlet invalidStr = 'abc';\nconsole.log(Number(invalidStr)); // NaN\nconsole.log(parseInt(invalidStr)); // NaN\nconsole.log(parseFloat(invalidStr)); // NaN\nconsole.log(+invalidStr); // NaN\n```\n\n## Further reading\n\n- [MDN Web Docs: Number()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)\n- [MDN Web Docs: parseInt()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)\n- [MDN Web Docs: parseFloat()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat)\n- [MDN Web Docs: Unary plus (+)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)\n"
  },
  {
    "path": "questions/how-do-you-convert-a-string-to-a-number-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-convert-a-string-to-a-number-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Data Types & Variables\"\n}\n"
  },
  {
    "path": "questions/how-do-you-convert-a-string-to-a-number-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 如何在 JavaScript 中将字符串转换为数字？\n---\n\n## TL;DR\n\n在 JavaScript 中，您可以使用多种方法将字符串转换为数字。最常见的方法是 `Number()`、`parseInt()`、`parseFloat()` 和一元加运算符 (`+`)。例如，`Number(\"123\")` 将字符串 `\"123\"` 转换为数字 `123`，而 `parseInt(\"123.45\")` 将字符串 `\"123.45\"` 转换为整数 `123`。\n\n***\n\n## 如何在 JavaScript 中将字符串转换为数字？\n\n### 使用 `Number()` 函数\n\n`Number()` 函数将字符串转换为数字。它可以处理整数和浮点数。\n\n```js live\nlet str = '123';\nlet num = Number(str);\nconsole.log(num); // 123\n\nlet floatStr = '123.45';\nlet floatNum = Number(floatStr);\nconsole.log(floatNum); // 123.45\n```\n\n### 使用 `parseInt()` 函数\n\n`parseInt()` 函数解析一个字符串并返回一个整数。它还可以接受第二个参数，即要使用的数字系统的基数（底数）。\n\n```js live\nlet str = '123';\nlet num = parseInt(str);\nconsole.log(num); // 123\n\nlet floatStr = '120.45';\nlet floatNum = parseInt(floatStr);\nconsole.log(floatNum); // 120\n\nlet binaryStr = '1010';\nlet binaryNum = parseInt(binaryStr, 2);\nconsole.log(binaryNum); // 10\n```\n\n### 使用 `parseFloat()` 函数\n\n`parseFloat()` 函数解析一个字符串并返回一个浮点数。\n\n```js live\nlet floatStr = '123.45';\nlet floatNum = parseFloat(floatStr);\nconsole.log(floatNum); // 123.45\n```\n\n### 使用一元加运算符 (`+`)\n\n一元加运算符可用于将字符串转换为数字。这是一种简写方法，适用于整数和浮点数。\n\n```js live\nlet str = '123';\nlet num = +str;\nconsole.log(num); // 123\n\nlet floatStr = '123.45';\nlet floatNum = +floatStr;\nconsole.log(floatNum); // 123.45\n```\n\n### 处理非数字字符串\n\n如果字符串无法转换为数字，这些方法将返回 `NaN` (非数字)。\n\n```js live\nlet invalidStr = 'abc';\nconsole.log(Number(invalidStr)); // NaN\nconsole.log(parseInt(invalidStr)); // NaN\nconsole.log(parseFloat(invalidStr)); // NaN\nconsole.log(+invalidStr); // NaN\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Number()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number)\n* [MDN Web Docs: parseInt()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/parseInt)\n* [MDN Web Docs: parseFloat()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/parseFloat)\n* [MDN Web Docs: Unary plus (+)](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Unary_plus)\n"
  },
  {
    "path": "questions/how-do-you-create-a-constructor-function/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"2243699d\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"38d18dbb\",\n        \"8cfc2ad0\",\n        \"2a7816d0\",\n        \"528c2335\",\n        \"7f0e9485\",\n        \"a9b0c3e0\",\n        \"bb2cea8d\",\n        \"f25e75c4\",\n        \"80bca8a9\",\n        \"e3b5c44\",\n        \"b9bc035a\",\n        \"ce841525\",\n        \"97ba09c0\",\n        \"2339a0c6\",\n        \"948de165\",\n        \"55cf8bf6\",\n        \"aa1c88d2\",\n        \"ee363481\",\n        \"9af57c23\",\n        \"1f4770e5\",\n        \"e5d6bbb9\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"38d18dbb\",\n        \"8cfc2ad0\",\n        \"2a7816d0\",\n        \"528c2335\",\n        \"7f0e9485\",\n        \"a9b0c3e0\",\n        \"bb2cea8d\",\n        \"f25e75c4\",\n        \"80bca8a9\",\n        \"e3b5c44\",\n        \"b9bc035a\",\n        \"ce841525\",\n        \"97ba09c0\",\n        \"2339a0c6\",\n        \"948de165\",\n        \"55cf8bf6\",\n        \"aa1c88d2\",\n        \"ee363481\",\n        \"9af57c23\",\n        \"1f4770e5\",\n        \"e5d6bbb9\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-create-a-constructor-function/en-US.mdx",
    "content": "---\ntitle: How do you create a constructor function?\n---\n\n## TL;DR\n\nTo create a constructor function in JavaScript, define a regular function with a capitalized name to indicate it's a constructor. Use the `this` keyword to set properties and methods. When creating an instance, use the `new` keyword.\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\nconst john = new Person('John', 30);\nconsole.log(john.age); // 30\n```\n\n---\n\n## How do you create a constructor function?\n\n### Defining a constructor function\n\nA constructor function in JavaScript is a regular function that is used to create objects. By convention, the name of the constructor function starts with a capital letter to distinguish it from regular functions.\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n```\n\n### Using the `this` keyword\n\nWithin the constructor function, the `this` keyword is used to refer to the object that will be created. Properties and methods can be assigned to `this`.\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n  this.greet = function () {\n    console.log(\n      `Hello, my name is ${this.name} and I am ${this.age} years old.`,\n    );\n  };\n}\n```\n\n### Creating an instance\n\nTo create an instance of the object, use the `new` keyword followed by the constructor function.\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n  this.greet = function () {\n    console.log(\n      `Hello, my name is ${this.name} and I am ${this.age} years old.`,\n    );\n  };\n}\n\nconst john = new Person('John', 30);\njohn.greet(); // Output: Hello, my name is John and I am 30 years old.\n```\n\n### Adding methods to the prototype\n\nTo save memory, it's a good practice to add methods to the constructor's prototype instead of defining them inside the constructor function.\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\nPerson.prototype.greet = function () {\n  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);\n};\n\nconst jane = new Person('Jane', 25);\njane.greet(); // Output: Hello, my name is Jane and I am 25 years old.\n```\n\n### Checking the instance type\n\nYou can check if an object is an instance of a constructor function using the `instanceof` operator.\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\nconst jane = new Person('Jane', 25);\n\nconsole.log(jane instanceof Person); // Output: true\n```\n\n## Further reading\n\n- [MDN Web Docs: Working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects)\n- [MDN Web Docs: Object prototypes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes)\n- [JavaScript.info: Constructor, operator \"new\"](https://javascript.info/constructor-new)\n"
  },
  {
    "path": "questions/how-do-you-create-a-constructor-function/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-create-a-constructor-function\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Prototypes & Inheritance\"\n}\n"
  },
  {
    "path": "questions/how-do-you-create-a-constructor-function/zh-CN.mdx",
    "content": "---\ntitle: 如何创建构造函数？\n---\n\n## TL;DR\n\n要在 JavaScript 中创建构造函数，请定义一个名称大写的常规函数，以表明它是一个构造函数。使用 `this` 关键字设置属性和方法。创建实例时，使用 `new` 关键字。\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\nconst john = new Person('John', 30);\nconsole.log(john.age); // 30\n```\n\n***\n\n## 如何创建构造函数？\n\n### 定义构造函数\n\nJavaScript 中的构造函数是一个用于创建对象的常规函数。按照惯例，构造函数的名称以大写字母开头，以区别于常规函数。\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n```\n\n### 使用 `this` 关键字\n\n在构造函数中，`this` 关键字用于引用将要创建的对象。可以将属性和方法分配给 `this`。\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n  this.greet = function () {\n    console.log(\n      `Hello, my name is ${this.name} and I am ${this.age} years old.`,\n    );\n  };\n}\n```\n\n### 创建实例\n\n要创建对象的实例，请使用 `new` 关键字，后跟构造函数。\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n  this.greet = function () {\n    console.log(\n      `Hello, my name is ${this.name} and I am ${this.age} years old.`,\n    );\n  };\n}\n\nconst john = new Person('John', 30);\njohn.greet(); // Output: Hello, my name is John and I am 30 years old.\n```\n\n### 将方法添加到原型\n\n为了节省内存，最好将方法添加到构造函数的原型中，而不是在构造函数中定义它们。\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\nPerson.prototype.greet = function () {\n  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);\n};\n\nconst jane = new Person('Jane', 25);\njane.greet(); // Output: Hello, my name is Jane and I am 25 years old.\n```\n\n### 检查实例类型\n\n您可以使用 `instanceof` 运算符检查对象是否是构造函数的实例。\n\n```js live\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\nconst jane = new Person('Jane', 25);\n\nconsole.log(jane instanceof Person); // Output: true\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects)\n* [MDN Web Docs: Object prototypes](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes)\n* [JavaScript.info: Constructor, operator \"new\"](https://javascript.info/constructor-new)\n"
  },
  {
    "path": "questions/how-do-you-detect-if-javascript-is-disabled-on-a-page/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"8334a1c1\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"4774815\",\n        \"4102232f\",\n        \"2a7816d0\",\n        \"e85ad18d\",\n        \"f155fdc4\",\n        \"567312ea\",\n        \"19c254ba\",\n        \"ace1b291\",\n        \"836b473a\",\n        \"58d8485b\",\n        \"6e2c3b41\",\n        \"bcaeabdb\",\n        \"e81ff55f\",\n        \"e152fa7b\",\n        \"1f4770e5\",\n        \"f793b2e5\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4774815\",\n        \"4102232f\",\n        \"2a7816d0\",\n        \"e85ad18d\",\n        \"f155fdc4\",\n        \"567312ea\",\n        \"19c254ba\",\n        \"ace1b291\",\n        \"836b473a\",\n        \"58d8485b\",\n        \"6e2c3b41\",\n        \"bcaeabdb\",\n        \"e81ff55f\",\n        \"e152fa7b\",\n        \"1f4770e5\",\n        \"f793b2e5\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-detect-if-javascript-is-disabled-on-a-page/en-US.mdx",
    "content": "---\ntitle: How do you detect if JavaScript is disabled on a page?\n---\n\n## TL;DR\n\nTo detect if JavaScript is disabled on a page, you can use the `<noscript>` HTML tag. This tag allows you to display content or messages to users who have JavaScript disabled in their browsers. For example, you can include a message within the `<noscript>` tag to inform users that JavaScript is required for the full functionality of the page.\n\n```html\n<noscript>\n  <p>\n    JavaScript is disabled in your browser. Please enable JavaScript for the\n    best experience.\n  </p>\n</noscript>\n```\n\n---\n\n## Using the `<noscript>` tag\n\n### What is the `<noscript>` tag?\n\nThe `<noscript>` tag is an HTML element that provides an alternative content for users who have disabled JavaScript in their browsers. This tag is useful for informing users that certain features of the website may not work properly without JavaScript.\n\n### Example usage\n\nHere is an example of how to use the `<noscript>` tag to display a message to users with JavaScript disabled:\n\n```html\n<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>JavaScript Detection</title>\n  </head>\n  <body>\n    <h1>Welcome to our website</h1>\n    <noscript>\n      <p>\n        JavaScript is disabled in your browser. Please enable JavaScript for the\n        best experience.\n      </p>\n    </noscript>\n    <p>This content is visible to all users.</p>\n  </body>\n</html>\n```\n\nIn this example, the message inside the `<noscript>` tag will only be displayed if JavaScript is disabled. If JavaScript is enabled, the content inside the `<noscript>` tag will be ignored.\n\n### Styling the `<noscript>` content\n\nYou can also style the content inside the `<noscript>` tag using CSS to make it more noticeable. For example:\n\n```html\n<noscript>\n  <style>\n    .noscript-message {\n      color: red;\n      font-weight: bold;\n    }\n  </style>\n  <p class=\"noscript-message\">\n    JavaScript is disabled in your browser. Please enable JavaScript for the\n    best experience.\n  </p>\n</noscript>\n```\n\nIn this example, the message will be styled with red text and bold font to make it stand out.\n\n## Further reading\n\n- [MDN Web Docs: `<noscript>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/noscript)\n- [W3Schools: HTML `<noscript>` Tag](https://www.w3schools.com/tags/tag_noscript.asp)\n- [Can I use: `<noscript>`](https://caniuse.com/?search=noscript)\n"
  },
  {
    "path": "questions/how-do-you-detect-if-javascript-is-disabled-on-a-page/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-detect-if-javascript-is-disabled-on-a-page\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"browser\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/how-do-you-detect-if-javascript-is-disabled-on-a-page/zh-CN.mdx",
    "content": "---\ntitle: 如何检测页面是否禁用了 JavaScript？\n---\n\n## TL;DR\n\n要检测页面上是否禁用了 JavaScript，可以使用 `<noscript>` HTML 标签。此标签允许您向浏览器中禁用了 JavaScript 的用户显示内容或消息。例如，您可以在 `<noscript>` 标签中包含一条消息，告知用户需要 JavaScript 才能获得页面的全部功能。\n\n```html\n<noscript>\n  <p>\n    您的浏览器中禁用了 JavaScript。请启用 JavaScript 以获得\n    最佳体验。\n  </p>\n</noscript>\n```\n\n***\n\n## 使用 `<noscript>` 标签\n\n### 什么是 `<noscript>` 标签？\n\n`<noscript>` 标签是一个 HTML 元素，它为在浏览器中禁用了 JavaScript 的用户提供替代内容。此标签对于告知用户，如果没有 JavaScript，网站的某些功能可能无法正常工作很有用。\n\n### 示例用法\n\n以下是如何使用 `<noscript>` 标签向禁用了 JavaScript 的用户显示消息的示例：\n\n```html\n<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>JavaScript 检测</title>\n  </head>\n  <body>\n    <h1>欢迎来到我们的网站</h1>\n    <noscript>\n      <p>\n        您的浏览器中禁用了 JavaScript。请启用 JavaScript 以获得\n        最佳体验。\n      </p>\n    </noscript>\n    <p>此内容对所有用户可见。</p>\n  </body>\n</html>\n```\n\n在此示例中，只有在禁用 JavaScript 的情况下，才会显示 `<noscript>` 标签内的消息。如果启用了 JavaScript，则会忽略 `<noscript>` 标签内的内容。\n\n### 设置 `<noscript>` 内容的样式\n\n您还可以使用 CSS 设置 `<noscript>` 标签内内容的样式，使其更引人注目。例如：\n\n```html\n<noscript>\n  <style>\n    .noscript-message {\n      color: red;\n      font-weight: bold;\n    }\n  </style>\n  <p class=\"noscript-message\">\n    您的浏览器中禁用了 JavaScript。请启用 JavaScript 以获得\n    最佳体验。\n  </p>\n</noscript>\n```\n\n在此示例中，消息将使用红色文本和粗体字体设置样式，使其突出显示。\n\n## 延伸阅读\n\n* [MDN Web Docs: `<noscript>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/noscript)\n* [W3Schools: HTML `<noscript>` 标签](https://www.w3schools.com/tags/tag_noscript.asp)\n* [Can I use: `<noscript>`](https://caniuse.com/?search=noscript)\n"
  },
  {
    "path": "questions/how-do-you-get-the-query-string-values-of-the-current-page-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"42de1ecb\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"b0f74c9a\",\n        \"16926c3b\",\n        \"2a7816d0\",\n        \"6f6e729\",\n        \"7f9aab58\",\n        \"9ff0d9e6\",\n        \"700ae9a2\",\n        \"30d009a1\",\n        \"685b5a6d\",\n        \"9b5019f0\",\n        \"c820cf00\",\n        \"ff3ea8d8\",\n        \"792e7e39\",\n        \"9654aab9\",\n        \"82b1bf3e\",\n        \"88b9a950\",\n        \"d58ffb87\",\n        \"f74994a7\",\n        \"79e274c7\",\n        \"c8d558a3\",\n        \"4a421d53\",\n        \"1f4770e5\",\n        \"436c50d9\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"b0f74c9a\",\n        \"16926c3b\",\n        \"2a7816d0\",\n        \"6f6e729\",\n        \"7f9aab58\",\n        \"9ff0d9e6\",\n        \"700ae9a2\",\n        \"30d009a1\",\n        \"685b5a6d\",\n        \"9b5019f0\",\n        \"c820cf00\",\n        \"ff3ea8d8\",\n        \"792e7e39\",\n        \"9654aab9\",\n        \"82b1bf3e\",\n        \"88b9a950\",\n        \"d58ffb87\",\n        \"f74994a7\",\n        \"79e274c7\",\n        \"c8d558a3\",\n        \"4a421d53\",\n        \"1f4770e5\",\n        \"436c50d9\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-get-the-query-string-values-of-the-current-page-in-javascript/en-US.mdx",
    "content": "---\ntitle: How do you get the query string values of the current page in JavaScript?\n---\n\n## TL;DR\n\nTo get the query string values of the current page in JavaScript, you can use the `URLSearchParams` object. First, create a `URLSearchParams` instance with `window.location.search`, then use the `get` method to retrieve specific query parameters. For example:\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconst value = params.get('language');\nconsole.log(value);\n```\n\n---\n\n## How do you get the query string values of the current page in JavaScript?\n\n### Using URLSearchParams\n\nThe `URLSearchParams` interface provides an easy way to work with query strings. Here's how you can use it:\n\n1. **Create a `URLSearchParams` instance**: Use `window.location.search` to get the query string part of the URL.\n2. **Retrieve specific query parameters**: Use the `get` method to get the value of a specific query parameter.\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconst value = params.get('key'); // Replace 'key' with the actual query parameter name\nconsole.log(value);\n```\n\nIf the query parameter does not exist, the `get` method returns `null`.\n\n### Example\n\nConsider a URL like `https://example.com?page=2&sort=asc`. To get the values of `page` and `sort`:\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconst page = params.get('page'); // '2'\nconst sort = params.get('sort'); // 'asc'\n```\n\n### Handling multiple values\n\nIf a query parameter appears multiple times, you can use the `getAll` method to retrieve all values:\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconst values = params.getAll('key'); // Returns an array of values\n```\n\n### Checking for the existence of a parameter\n\nYou can use the `has` method to check if a query parameter exists.\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconsole.log(params.has('page'));\nconsole.log(params.has('language'));\nconsole.log(params.has('tab'));\n```\n\n### Iterating over all parameters\n\nYou can iterate over all query parameters using the `forEach` method:\n\n```js\nconst params = new URLSearchParams(window.location.search);\nparams.forEach((value, key) => {\n  console.log(`${key}: ${value}`);\n});\n```\n\n## Further reading\n\n- [MDN Web Docs: URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)\n- [MDN Web Docs: window.location](https://developer.mozilla.org/en-US/docs/Web/API/Window/location)\n- [Practice 190+ JavaScript interview questions on GitHub](https://github.com/greatfrontend/top-javascript-interview-questions)\n"
  },
  {
    "path": "questions/how-do-you-get-the-query-string-values-of-the-current-page-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-get-the-query-string-values-of-the-current-page-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/how-do-you-get-the-query-string-values-of-the-current-page-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 如何用 JavaScript 获取当前页面的查询字符串值？\n---\n\n## 总结\n\n要在 JavaScript 中获取当前页面的查询字符串值，可以使用 `URLSearchParams` 对象。首先，使用 `window.location.search` 创建一个 `URLSearchParams` 实例，然后使用 `get` 方法检索特定的查询参数。例如：\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconst value = params.get('language');\nconsole.log(value);\n```\n\n***\n\n## 如何用 JavaScript 获取当前页面的查询字符串值？\n\n### 使用 URLSearchParams\n\n`URLSearchParams` 接口提供了一种简单的方法来处理查询字符串。以下是如何使用它：\n\n1. **创建 `URLSearchParams` 实例**：使用 `window.location.search` 获取 URL 的查询字符串部分。\n2. **检索特定的查询参数**：使用 `get` 方法获取特定查询参数的值。\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconst value = params.get('key'); // 将 'key' 替换为实际的查询参数名称\nconsole.log(value);\n```\n\n如果查询参数不存在，`get` 方法将返回 `null`。\n\n### 示例\n\n考虑一个像 `https://example.com?page=2&sort=asc` 这样的 URL。要获取 `page` 和 `sort` 的值：\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconst page = params.get('page'); // '2'\nconst sort = params.get('sort'); // 'asc'\n```\n\n### 处理多个值\n\n如果一个查询参数出现多次，可以使用 `getAll` 方法检索所有值：\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconst values = params.getAll('key'); // 返回一个值数组\n```\n\n### 检查参数是否存在\n\n您可以使用 `has` 方法检查查询参数是否存在。\n\n```js\nconst params = new URLSearchParams(window.location.search);\nconsole.log(params.has('page'));\nconsole.log(params.has('language'));\nconsole.log(params.has('tab'));\n```\n\n### 遍历所有参数\n\n您可以使用 `forEach` 方法遍历所有查询参数：\n\n```js\nconst params = new URLSearchParams(window.location.search);\nparams.forEach((value, key) => {\n  console.log(`${key}: ${value}`);\n});\n```\n\n## 延伸阅读\n\n* [MDN Web 文档：URLSearchParams](https://developer.mozilla.org/zh-CN/docs/Web/API/URLSearchParams)\n* [MDN Web 文档：window.location](https://developer.mozilla.org/zh-CN/docs/Web/API/Window/location)\n* [在 GitHub 上练习 190 多个 JavaScript 面试问题](https://github.com/greatfrontend/top-javascript-interview-questions)\n"
  },
  {
    "path": "questions/how-do-you-handle-errors-in-asynchronous-operations/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"83836691\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"327bddff\",\n        \"6f1c138c\",\n        \"f73efded\",\n        \"1e8e293b\",\n        \"2a7816d0\",\n        \"499dfcd3\",\n        \"f3ba35be\",\n        \"5c0b117d\",\n        \"6f1c138c\",\n        \"772c3745\",\n        \"393b7aae\",\n        \"c238d5a7\",\n        \"a65a6657\",\n        \"f3ba35be\",\n        \"fda8e360\",\n        \"b240177e\",\n        \"58260fa0\",\n        \"9ae9590d\",\n        \"c7bcda64\",\n        \"1f4770e5\",\n        \"933046ae\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"327bddff\",\n        \"6f1c138c\",\n        \"f73efded\",\n        \"1e8e293b\",\n        \"2a7816d0\",\n        \"499dfcd3\",\n        \"f3ba35be\",\n        \"5c0b117d\",\n        \"6f1c138c\",\n        \"772c3745\",\n        \"393b7aae\",\n        \"c238d5a7\",\n        \"a65a6657\",\n        \"f3ba35be\",\n        \"fda8e360\",\n        \"b240177e\",\n        \"58260fa0\",\n        \"9ae9590d\",\n        \"c7bcda64\",\n        \"1f4770e5\",\n        \"933046ae\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-handle-errors-in-asynchronous-operations/en-US.mdx",
    "content": "---\ntitle: How do you handle errors in asynchronous operations?\n---\n\n## TL;DR\n\nTo handle errors in asynchronous operations, you can use `try...catch` blocks with `async/await` syntax or `.catch()` method with Promises. For example, with `async/await`, you can wrap your code in a `try...catch` block to catch any errors:\n\n```js live\nasync function fetchData() {\n  try {\n    // Invalid URl\n    const response = await fetch('https://api.example.com/data');\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\n\nfetchData(); // Error fetching data: ....\n```\n\nWith Promises, you can use the `.catch()` method:\n\n```js live\nfetch('https://api.example.com/data') // Invalid URl\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error fetching data:', error));\n```\n\n---\n\n## Using `try...catch` with `async/await`\n\n### Basic usage\n\nWhen using `async/await`, you can handle errors by wrapping your asynchronous code in a `try...catch` block. This allows you to catch any errors that occur during the execution of the `await` statement.\n\n```js live\nasync function fetchData() {\n  try {\n    // Invalid URl\n    const response = await fetch('https://api.example.com/data');\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\n\nfetchData(); // Error fetching data: ....\n```\n\n### Nested asynchronous operations\n\nIf you have multiple asynchronous operations, you can nest `try...catch` blocks to handle errors at different levels.\n\n```js live\nasync function fetchUser() {\n  // Simulate a successful async operation\n  return { id: 1, name: 'Alice' };\n}\n\nasync function fetchUserPosts() {\n  // Simulate a failed async operation\n  throw new Error('Failed to fetch posts');\n}\n\nasync function loadUserData() {\n  try {\n    const user = await fetchUser();\n    console.log('User:', user);\n\n    try {\n      const posts = await fetchUserPosts();\n      console.log('Posts:', posts);\n    } catch (postsError) {\n      console.error('Error fetching posts:', postsError.message);\n    }\n  } catch (userError) {\n    console.error('Error fetching user:', userError.message);\n  }\n}\n\nloadUserData();\n```\n\n## Using `.catch()` with Promises\n\n### Basic usage\n\nWhen working with Promises, you can handle errors using the `.catch()` method. This method is called if the Promise is rejected.\n\n```js live\nfetch('https://api.example.com/data')\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error fetching data:', error));\n```\n\n### Chaining multiple Promises\n\nIf you have multiple Promises chained together, you can use a single `.catch()` at the end to handle any errors that occur in any of the Promises.\n\n```js live\nfetch('https://api.example.com/data')\n  .then((response) => response.json())\n  .then((data) => {\n    // Process data\n    return processData(data);\n  })\n  .then((result) => {\n    // Further processing\n    console.log(result);\n  })\n  .catch((error) => console.error('Error in the chain:', error));\n```\n\n## Further reading\n\n- [MDN Web Docs: async/await](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await)\n- [MDN Web Docs: Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)\n- [JavaScript.info: Error handling with promises](https://javascript.info/promise-error-handling)\n"
  },
  {
    "path": "questions/how-do-you-handle-errors-in-asynchronous-operations/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-handle-errors-in-asynchronous-operations\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"async\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Asynchronous JavaScript\"\n}\n"
  },
  {
    "path": "questions/how-do-you-handle-errors-in-asynchronous-operations/zh-CN.mdx",
    "content": "---\ntitle: 如何处理异步操作中的错误？\n---\n\n## TL;DR\n\n要处理异步操作中的错误，可以使用带有 `async/await` 语法的 `try...catch` 块或带有 Promises 的 `.catch()` 方法。例如，使用 `async/await`，您可以将代码包装在 `try...catch` 块中以捕获任何错误：\n\n```js live\nasync function fetchData() {\n  try {\n    // Invalid URl\n    const response = await fetch('https://api.example.com/data');\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\n\nfetchData(); // Error fetching data: ....\n```\n\n使用 Promises，您可以使用 `.catch()` 方法：\n\n```js live\nfetch('https://api.example.com/data') // Invalid URl\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error fetching data:', error));\n```\n\n***\n\n## 使用 `try...catch` 和 `async/await`\n\n### 基本用法\n\n使用 `async/await` 时，您可以通过将异步代码包装在 `try...catch` 块中来处理错误。这允许您捕获在执行 `await` 语句期间发生的任何错误。\n\n```js live\nasync function fetchData() {\n  try {\n    // Invalid URl\n    const response = await fetch('https://api.example.com/data');\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\n\nfetchData(); // Error fetching data: ....\n```\n\n### 嵌套异步操作\n\n如果您有多个异步操作，则可以嵌套 `try...catch` 块以处理不同级别的错误。\n\n```js live\nasync function fetchUser() {\n  // Simulate a successful async operation\n  return { id: 1, name: 'Alice' };\n}\n\nasync function fetchUserPosts() {\n  // Simulate a failed async operation\n  throw new Error('Failed to fetch posts');\n}\n\nasync function loadUserData() {\n  try {\n    const user = await fetchUser();\n    console.log('User:', user);\n\n    try {\n      const posts = await fetchUserPosts();\n      console.log('Posts:', posts);\n    } catch (postsError) {\n      console.error('Error fetching posts:', postsError.message);\n    }\n  } catch (userError) {\n    console.error('Error fetching user:', userError.message);\n  }\n}\n\nloadUserData();\n```\n\n## 使用 `.catch()` 和 Promises\n\n### 基本用法\n\n使用 Promises 时，您可以使用 `.catch()` 方法处理错误。如果 Promise 被拒绝，则会调用此方法。\n\n```js live\nfetch('https://api.example.com/data')\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error fetching data:', error));\n```\n\n### 链接多个 Promises\n\n如果您将多个 Promises 链接在一起，您可以在末尾使用一个 `.catch()` 来处理任何 Promise 中发生的错误。\n\n```js live\nfetch('https://api.example.com/data')\n  .then((response) => response.json())\n  .then((data) => {\n    // Process data\n    return processData(data);\n  })\n  .then((result) => {\n    // Further processing\n    console.log(result);\n  })\n  .catch((error) => console.error('Error in the chain:', error));\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: async/await](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await)\n* [MDN Web Docs: Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)\n* [JavaScript.info: Error handling with promises](https://javascript.info/promise-error-handling)\n"
  },
  {
    "path": "questions/how-do-you-handle-errors-using-trycatch-blocks/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"d57c372a\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"faeba4a7\",\n        \"2cfce4b6\",\n        \"2a7816d0\",\n        \"afedc9ab\",\n        \"ae1ce134\",\n        \"caf4cf80\",\n        \"2cfce4b6\",\n        \"9b5019f0\",\n        \"8b5b84e\",\n        \"672dfff6\",\n        \"2deb5771\",\n        \"2d397a97\",\n        \"7cc4268\",\n        \"4a1b5c91\",\n        \"d665ea43\",\n        \"25bfaa72\",\n        \"9b22b868\",\n        \"490dfaaa\",\n        \"bb88727\",\n        \"93edb5d0\",\n        \"74764fec\",\n        \"1f4770e5\",\n        \"ee7790b7\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"faeba4a7\",\n        \"2cfce4b6\",\n        \"2a7816d0\",\n        \"afedc9ab\",\n        \"ae1ce134\",\n        \"caf4cf80\",\n        \"2cfce4b6\",\n        \"9b5019f0\",\n        \"8b5b84e\",\n        \"672dfff6\",\n        \"2deb5771\",\n        \"2d397a97\",\n        \"7cc4268\",\n        \"4a1b5c91\",\n        \"d665ea43\",\n        \"25bfaa72\",\n        \"9b22b868\",\n        \"490dfaaa\",\n        \"bb88727\",\n        \"93edb5d0\",\n        \"74764fec\",\n        \"1f4770e5\",\n        \"ee7790b7\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-handle-errors-using-trycatch-blocks/en-US.mdx",
    "content": "---\ntitle: How do you handle errors using `try...catch` blocks?\n---\n\n## TL;DR\n\nTo handle errors using `try...catch` blocks, you wrap the code that might throw an error inside a `try` block. If an error occurs, the control is transferred to the `catch` block where you can handle the error. Optionally, you can use a `finally` block to execute code regardless of whether an error occurred or not.\n\n```js\ntry {\n  // Code that may throw an error\n} catch (error) {\n  // Handle the error\n} finally {\n  // Code that will run regardless of an error\n}\n```\n\n---\n\n## How do you handle errors using `try...catch` blocks?\n\n### Basic structure\n\nThe `try...catch` statement consists of a `try` block, a `catch` block, and optionally a `finally` block.\n\n```js\ntry {\n  // Code that may throw an error\n} catch (error) {\n  // Handle the error\n} finally {\n  // Code that will run regardless of an error\n}\n```\n\n### Example\n\nHere is an example of using `try...catch` to handle errors:\n\n```js live\nfunction riskyOperation() {\n  const invalidJsonString = '{\"name\": \"John}'; // Try changing this to a valid JSON string\n  return JSON.parse(invalidJsonString);\n}\n\ntry {\n  let result = riskyOperation();\n  console.log(result);\n} catch (error) {\n  console.error('An error occurred:', error.message);\n} finally {\n  console.log('This will run regardless of an error');\n}\n```\n\n### Explanation\n\n- **`try` block**: Contains code that might throw an error. If an error occurs, the control is transferred to the `catch` block.\n- **`catch` block**: Contains code to handle the error. The `error` object contains information about the error.\n- **`finally` block**: Contains code that will run regardless of whether an error occurred or not. This is useful for cleanup tasks.\n\n### Nested `try...catch` blocks\n\nYou can nest `try...catch` blocks to handle different levels of errors:\n\n```js live\nfunction anotherRiskyOperation() {\n  const person = undefined;\n  console.log(person.name);\n}\n\ntry {\n  try {\n    anotherRiskyOperation();\n  } catch (innerError) {\n    // Error (if any) for anotherRiskyOperation caught here\n    console.error('Inner error:', innerError.message);\n  }\n} catch (outerError) {\n  // Inner error does not reach here\n  console.error('Outer error:', outerError.message);\n}\n```\n\n### Re-throwing errors\n\nYou can re-throw an error from the `catch` block if you want it to be handled by an outer `try...catch` block:\n\n```js live\nfunction yetAnotherRiskyOperation() {\n  const numerator = 10;\n  const denominator = 0;\n  if (denominator === 0) {\n    throw new Error('Cannot divide by zero');\n  }\n\n  return numerator / denominator;\n}\n\ntry {\n  try {\n    const result = yetAnotherRiskyOperation();\n    console.log('Divisinon result:', result);\n  } catch (innerError) {\n    console.error('Inner error:', innerError.message);\n    throw innerError; // Re-throw the error\n  }\n} catch (outerError) {\n  console.error('Outer error:', outerError.message);\n}\n```\n\n### Using `finally` for cleanup\n\nThe `finally` block is useful for cleanup tasks, such as closing a file or releasing resources:\n\n```js\n// openFile() and closeFile() are custom implementations\ntry {\n  let file = openFile('example.txt');\n  // Perform operations on the file\n} catch (error) {\n  console.error('An error occurred:', error.message);\n} finally {\n  closeFile(file); // Ensure the file is closed\n}\n```\n\n## Further reading\n\n- [MDN Web Docs: try...catch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch)\n- [JavaScript.info: Error handling, \"try...catch\"](https://javascript.info/try-catch)\n- [MDN Web Docs: Error object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)\n"
  },
  {
    "path": "questions/how-do-you-handle-errors-using-trycatch-blocks/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-handle-errors-using-trycatch-blocks\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Error Handling\"\n}\n"
  },
  {
    "path": "questions/how-do-you-handle-errors-using-trycatch-blocks/zh-CN.mdx",
    "content": "---\ntitle: 如何使用 `try...catch` 块处理错误？\n---\n\n## TL;DR\n\n要使用 `try...catch` 块处理错误，您需要将可能抛出错误的代码包装在 `try` 块中。如果发生错误，控制权将转移到 `catch` 块，您可以在其中处理错误。或者，您可以使用 `finally` 块来执行代码，无论是否发生错误。\n\n```js\ntry {\n  // Code that may throw an error\n} catch (error) {\n  // Handle the error\n} finally {\n  // Code that will run regardless of an error\n}\n```\n\n***\n\n## 如何使用 `try...catch` 块处理错误？\n\n### 基本结构\n\n`try...catch` 语句由 `try` 块、`catch` 块和可选的 `finally` 块组成。\n\n```js\ntry {\n  // Code that may throw an error\n} catch (error) {\n  // Handle the error\n} finally {\n  // Code that will run regardless of an error\n}\n```\n\n### 示例\n\n以下是使用 `try...catch` 处理错误的示例：\n\n```js live\nfunction riskyOperation() {\n  const invalidJsonString = '{\"name\": \"John}'; // Try changing this to a valid JSON string\n  return JSON.parse(invalidJsonString);\n}\n\ntry {\n  let result = riskyOperation();\n  console.log(result);\n} catch (error) {\n  console.error('An error occurred:', error.message);\n} finally {\n  console.log('This will run regardless of an error');\n}\n```\n\n### 解释\n\n* **`try` 块**：包含可能抛出错误的代码。如果发生错误，控制权将转移到 `catch` 块。\n* **`catch` 块**：包含处理错误的代码。`error` 对象包含有关错误的信息。\n* **`finally` 块**：包含无论是否发生错误都将运行的代码。这对于清理任务很有用。\n\n### 嵌套 `try...catch` 块\n\n您可以嵌套 `try...catch` 块来处理不同级别的错误：\n\n```js live\nfunction anotherRiskyOperation() {\n  const person = undefined;\n  console.log(person.name);\n}\n\ntry {\n  try {\n    anotherRiskyOperation();\n  } catch (innerError) {\n    // Error (if any) for anotherRiskyOperation caught here\n    console.error('Inner error:', innerError.message);\n  }\n} catch (outerError) {\n  // Inner error does not reach here\n  console.error('Outer error:', outerError.message);\n}\n```\n\n### 重新抛出错误\n\n如果希望由外部 `try...catch` 块处理错误，您可以从 `catch` 块重新抛出错误：\n\n```js live\nfunction yetAnotherRiskyOperation() {\n  const numerator = 10;\n  const denominator = 0;\n  if (denominator === 0) {\n    throw new Error('Cannot divide by zero');\n  }\n\n  return numerator / denominator;\n}\n\ntry {\n  try {\n    const result = yetAnotherRiskyOperation();\n    console.log('Divisinon result:', result);\n  } catch (innerError) {\n    console.error('Inner error:', innerError.message);\n    throw innerError; // Re-throw the error\n  }\n} catch (outerError) {\n  console.error('Outer error:', outerError.message);\n}\n```\n\n### 使用 `finally` 进行清理\n\n`finally` 块对于清理任务很有用，例如关闭文件或释放资源：\n\n```js\n// openFile() 和 closeFile() 是自定义实现\ntry {\n  let file = openFile('example.txt');\n  // 对文件执行操作\n} catch (error) {\n  console.error('发生错误:', error.message);\n} finally {\n  closeFile(file); // 确保文件已关闭\n}\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: try...catch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch)\n* [JavaScript.info: Error handling, \"try...catch\"](https://javascript.info/try-catch)\n* [MDN Web Docs: Error object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)\n"
  },
  {
    "path": "questions/how-do-you-import-and-export-modules-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"6e46ab1a\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"95c9c1ca\",\n        \"9866d11c\",\n        \"2a7816d0\",\n        \"1423f9a4\",\n        \"4a8b3697\",\n        \"99ce95b0\",\n        \"854e709c\",\n        \"5aecda15\",\n        \"271e35e0\",\n        \"9c62d4fc\",\n        \"39551d08\",\n        \"abce53ee\",\n        \"d0d58bde\",\n        \"baa3139f\",\n        \"5c326618\",\n        \"7064378c\",\n        \"5347184c\",\n        \"d3f865f7\",\n        \"93180888\",\n        \"6a75df33\",\n        \"1f4770e5\",\n        \"926066f7\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"95c9c1ca\",\n        \"9866d11c\",\n        \"2a7816d0\",\n        \"1423f9a4\",\n        \"4a8b3697\",\n        \"99ce95b0\",\n        \"854e709c\",\n        \"5aecda15\",\n        \"271e35e0\",\n        \"9c62d4fc\",\n        \"39551d08\",\n        \"abce53ee\",\n        \"d0d58bde\",\n        \"baa3139f\",\n        \"5c326618\",\n        \"7064378c\",\n        \"5347184c\",\n        \"d3f865f7\",\n        \"93180888\",\n        \"6a75df33\",\n        \"1f4770e5\",\n        \"926066f7\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-import-and-export-modules-in-javascript/en-US.mdx",
    "content": "---\ntitle: How do you import and export modules in JavaScript?\n---\n\n## TL;DR\n\nIn JavaScript, you can import and export modules using the `import` and `export` statements. To export a module, you can use `export` before a function, variable, or class, or use `export default` for a single default export. To import a module, you use the `import` statement followed by the name of the exported module and the path to the module file.\n\n```js\n// Exporting a module\nexport const myFunction = () => {\n  /* ... */\n};\nexport default myFunction;\n\n// Importing a module\nimport { myFunction } from './myModule';\nimport myFunction from './myModule';\n```\n\n---\n\n## Exporting modules\n\n### Named exports\n\nYou can export multiple named items from a module. Use the `export` keyword before the function, variable, or class you want to export.\n\n```js\n// myModule.js\nexport const myFunction = () => {\n  console.log('This is my function');\n};\n\nexport const myVariable = 42;\n```\n\n### Default exports\n\nA module can have one default export. Use the `export default` keyword to export a single item.\n\n```js\n// myModule.js\nconst myFunction = () => {\n  console.log('This is my function');\n};\n\nexport default myFunction;\n```\n\n## Importing modules\n\n### Importing named exports\n\nTo import named exports, use the `import` statement followed by curly braces containing the names of the exports.\n\n```js\n// main.js\nimport { myFunction, myVariable } from './myModule';\n\nmyFunction(); // This is my function\nconsole.log(myVariable); // 42\n```\n\n### Importing default exports\n\nTo import a default export, use the `import` statement followed by a name of your choice.\n\n```js\n// main.js\nimport myFunction from './myModule';\n\nmyFunction(); // This is my function\n```\n\n### Importing all exports\n\nYou can import all named exports from a module using the `*` syntax and an alias.\n\n```js\n// main.js\nimport * as myModule from './myModule';\n\nmyModule.myFunction(); // This is my function\nconsole.log(myModule.myVariable); // 42\n```\n\n## Further reading\n\n- [MDN Web Docs: import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\n- [MDN Web Docs: export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\n- [JavaScript Modules: A Beginner’s Guide](https://www.sitepoint.com/understanding-es6-modules/)\n"
  },
  {
    "path": "questions/how-do-you-import-and-export-modules-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-import-and-export-modules-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Modules\"\n}\n"
  },
  {
    "path": "questions/how-do-you-import-and-export-modules-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 如何在 JavaScript 中导入和导出模块？\n---\n\n## TL;DR\n\n在 JavaScript 中，您可以使用 `import` 和 `export` 语句导入和导出模块。要导出模块，您可以在函数、变量或类之前使用 `export`，或者对单个默认导出使用 `export default`。要导入模块，您可以使用 `import` 语句，后跟已导出模块的名称和模块文件的路径。\n\n```js\n// Exporting a module\nexport const myFunction = () => {\n  /* ... */\n};\nexport default myFunction;\n\n// Importing a module\nimport { myFunction } from './myModule';\nimport myFunction from './myModule';\n```\n\n***\n\n## 导出模块\n\n### 命名导出\n\n您可以从模块中导出多个已命名的项目。在要导出的函数、变量或类之前使用 `export` 关键字。\n\n```js\n// myModule.js\nexport const myFunction = () => {\n  console.log('This is my function');\n};\n\nexport const myVariable = 42;\n```\n\n### 默认导出\n\n一个模块可以有一个默认导出。使用 `export default` 关键字导出一个项目。\n\n```js\n// myModule.js\nconst myFunction = () => {\n  console.log('This is my function');\n};\n\nexport default myFunction;\n```\n\n## 导入模块\n\n### 导入命名导出\n\n要导入命名导出，请使用 `import` 语句，后跟包含导出名称的括号。\n\n```js\n// main.js\nimport { myFunction, myVariable } from './myModule';\n\nmyFunction(); // This is my function\nconsole.log(myVariable); // 42\n```\n\n### 导入默认导出\n\n要导入默认导出，请使用 `import` 语句，后跟您选择的名称。\n\n```js\n// main.js\nimport myFunction from './myModule';\n\nmyFunction(); // This is my function\n```\n\n### 导入所有导出\n\n您可以使用 `*` 语法和别名从模块导入所有已命名的导出。\n\n```js\n// main.js\nimport * as myModule from './myModule';\n\nmyModule.myFunction(); // This is my function\nconsole.log(myModule.myVariable); // 42\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\n* [MDN Web Docs: export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\n* [JavaScript Modules: A Beginner’s Guide](https://www.sitepoint.com/understanding-es6-modules/)\n"
  },
  {
    "path": "questions/how-do-you-make-an-http-request-using-the-fetch-api/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"1bc2711a\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"1dfb1cc3\",\n        \"b0f8e59f\",\n        \"5f93685\",\n        \"dde523a3\",\n        \"2a7816d0\",\n        \"b4813231\",\n        \"33b004b2\",\n        \"975b180e\",\n        \"3bab9183\",\n        \"f7de8e1c\",\n        \"b58c6263\",\n        \"deaf1b90\",\n        \"a6f86595\",\n        \"dcbf1f15\",\n        \"4f774dfb\",\n        \"709d86f1\",\n        \"691a51fb\",\n        \"fd336ae0\",\n        \"47fcde76\",\n        \"bbb7fc9a\",\n        \"ee855b6a\",\n        \"1f4770e5\",\n        \"18521edb\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"1dfb1cc3\",\n        \"b0f8e59f\",\n        \"5f93685\",\n        \"dde523a3\",\n        \"2a7816d0\",\n        \"b4813231\",\n        \"33b004b2\",\n        \"975b180e\",\n        \"3bab9183\",\n        \"f7de8e1c\",\n        \"b58c6263\",\n        \"deaf1b90\",\n        \"a6f86595\",\n        \"dcbf1f15\",\n        \"4f774dfb\",\n        \"709d86f1\",\n        \"691a51fb\",\n        \"fd336ae0\",\n        \"47fcde76\",\n        \"bbb7fc9a\",\n        \"ee855b6a\",\n        \"1f4770e5\",\n        \"18521edb\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-make-an-http-request-using-the-fetch-api/en-US.mdx",
    "content": "---\ntitle: How do you make an HTTP request using the Fetch API?\n---\n\n## TL;DR\n\nTo make an HTTP request using the Fetch API, you can use the `fetch` function, which returns a promise. You can handle the response using `.then()` and `.catch()` for error handling. Here's a basic example of a GET request:\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\nFor a POST request, you can pass an options object as the second argument to `fetch`:\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/posts', {\n  method: 'POST',\n  body: JSON.stringify({\n    title: 'foo',\n    body: 'bar',\n    userId: 1,\n  }),\n  headers: {\n    'Content-Type': 'application/json; charset=UTF-8',\n  },\n})\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\n---\n\n## Making an HTTP request using the Fetch API\n\n### Basic GET request\n\nTo make a basic GET request, you can use the `fetch` function with the URL of the resource you want to fetch. The `fetch` function returns a promise that resolves to the `Response` object representing the response to the request.\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\n### Handling different response types\n\nThe `Response` object has several methods to handle different types of responses, such as `.json()`, `.text()`, `.blob()`, and `.arrayBuffer()`.\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.text())\n  .then((text) => console.log(text))\n  .catch((error) => console.error('Error:', error));\n```\n\n### Making a POST request\n\nTo make a POST request, you need to pass an options object as the second argument to `fetch`. This object can include the HTTP method, headers, and body of the request.\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/posts', {\n  method: 'POST',\n  body: JSON.stringify({\n    title: 'foo',\n    body: 'bar',\n    userId: 1,\n  }),\n  headers: {\n    'Content-Type': 'application/json; charset=UTF-8',\n  },\n})\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\n### Handling errors\n\nError handling in the Fetch API can be done using the `.catch()` method. It's also a good practice to check the `response.ok` property to ensure the request was successful.\n\n```js live\nfetch('https://jsonplaceholder.tyicode.com/posts/1/comments') // Typo in the URL\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\n### Using async/await\n\nYou can also use the Fetch API with `async/await` for a more synchronous-looking code.\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/todos/1',\n    );\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error:', error);\n  }\n}\n\nfetchData();\n```\n\n## Further reading\n\n- [MDN Web Docs: Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)\n- [MDN Web Docs: Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)\n- [JavaScript.info: Fetch](https://javascript.info/fetch)\n"
  },
  {
    "path": "questions/how-do-you-make-an-http-request-using-the-fetch-api/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-make-an-http-request-using-the-fetch-api\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"networking\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/how-do-you-make-an-http-request-using-the-fetch-api/zh-CN.mdx",
    "content": "---\ntitle: 如何使用 Fetch API 发出 HTTP 请求？\n---\n\n## TL;DR\n\n要使用 Fetch API 发出 HTTP 请求，您可以使用 `fetch` 函数，该函数返回一个 promise。您可以使用 `.then()` 和 `.catch()` 来处理响应，以进行错误处理。 这是一个 GET 请求的基本示例：\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\n对于 POST 请求，您可以将一个选项对象作为第二个参数传递给 `fetch`：\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/posts', {\n  method: 'POST',\n  body: JSON.stringify({\n    title: 'foo',\n    body: 'bar',\n    userId: 1,\n  }),\n  headers: {\n    'Content-Type': 'application/json; charset=UTF-8',\n  },\n})\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\n***\n\n## 使用 Fetch API 发出 HTTP 请求\n\n### 基本的 GET 请求\n\n要发出基本的 GET 请求，您可以使用 `fetch` 函数，并使用您要获取的资源的 URL。`fetch` 函数返回一个 promise，该 promise 解析为表示对请求的响应的 `Response` 对象。\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\n### 处理不同的响应类型\n\n`Response` 对象有几种方法来处理不同类型的响应，例如 `.json()`、`.text()`、`.blob()` 和 `.arrayBuffer()`。\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.text())\n  .then((text) => console.log(text))\n  .catch((error) => console.error('Error:', error));\n```\n\n### 发出 POST 请求\n\n要发出 POST 请求，您需要将一个选项对象作为第二个参数传递给 `fetch`。此对象可以包括 HTTP 方法、标头和请求正文。\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/posts', {\n  method: 'POST',\n  body: JSON.stringify({\n    title: 'foo',\n    body: 'bar',\n    userId: 1,\n  }),\n  headers: {\n    'Content-Type': 'application/json; charset=UTF-8',\n  },\n})\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\n### 处理错误\n\n可以使用 `.catch()` 方法在 Fetch API 中进行错误处理。 检查 `response.ok` 属性以确保请求成功也是一个好习惯。\n\n```js live\nfetch('https://jsonplaceholder.tyicode.com/posts/1/comments') // Typo in the URL\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error:', error));\n```\n\n### 使用 async/await\n\n您还可以将 Fetch API 与 `async/await` 结合使用，以获得更具同步感知的代码。\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/todos/1',\n    );\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error:', error);\n  }\n}\n\nfetchData();\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)\n* [MDN Web Docs: Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)\n* [JavaScript.info: Fetch](https://javascript.info/fetch)\n"
  },
  {
    "path": "questions/how-do-you-manipulate-css-styles-using-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"e7c58a4f\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"9b63a7a1\",\n        \"850eb5e8\",\n        \"44b2c038\",\n        \"d1c317b8\",\n        \"2a7816d0\",\n        \"5da8a342\",\n        \"b55920c3\",\n        \"b6b3e806\",\n        \"530f42be\",\n        \"46897af4\",\n        \"1ae24a7c\",\n        \"35e22bc6\",\n        \"5955deb\",\n        \"5fdff3b9\",\n        \"a15546f1\",\n        \"beefb0f\",\n        \"d78dc868\",\n        \"af769ec7\",\n        \"1f4770e5\",\n        \"f6661148\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"9b63a7a1\",\n        \"850eb5e8\",\n        \"44b2c038\",\n        \"d1c317b8\",\n        \"2a7816d0\",\n        \"5da8a342\",\n        \"b55920c3\",\n        \"b6b3e806\",\n        \"530f42be\",\n        \"46897af4\",\n        \"1ae24a7c\",\n        \"35e22bc6\",\n        \"5955deb\",\n        \"5fdff3b9\",\n        \"a15546f1\",\n        \"beefb0f\",\n        \"d78dc868\",\n        \"af769ec7\",\n        \"1f4770e5\",\n        \"f6661148\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-manipulate-css-styles-using-javascript/en-US.mdx",
    "content": "---\ntitle: How do you manipulate CSS styles using JavaScript?\n---\n\n## TL;DR\n\nYou can manipulate CSS styles using JavaScript by accessing the `style` property of an HTML element. For example, to change the background color of a `div` element with the id `myDiv`, you can use:\n\n```js\ndocument.getElementById('myDiv').style.backgroundColor = 'blue';\n```\n\nYou can also add, remove, or toggle CSS classes using the `classList` property:\n\n```js\ndocument.getElementById('myDiv').classList.add('newClass');\ndocument.getElementById('myDiv').classList.remove('oldClass');\ndocument.getElementById('myDiv').classList.toggle('toggleClass');\n```\n\n---\n\n## Manipulating CSS styles using JavaScript\n\n### Accessing and modifying inline styles\n\nYou can directly manipulate the inline styles of an HTML element using the `style` property. This property allows you to set individual CSS properties.\n\n```js\n// Select the element\nconst myDiv = document.getElementById('myDiv');\n\n// Change the background color\nmyDiv.style.backgroundColor = 'blue';\n\n// Set multiple styles\nmyDiv.style.width = '100px';\nmyDiv.style.height = '100px';\nmyDiv.style.border = '1px solid black';\n```\n\n### Using the `classList` property\n\nThe `classList` property provides methods to add, remove, and toggle CSS classes on an element. This is useful for applying predefined styles from your CSS files.\n\n```js\n// Select the element\nconst myDiv = document.getElementById('myDiv');\n\n// Add a class\nmyDiv.classList.add('newClass');\n\n// Remove a class\nmyDiv.classList.remove('oldClass');\n\n// Toggle a class\nmyDiv.classList.toggle('toggleClass');\n```\n\n### Modifying styles using CSS variables\n\nCSS variables (custom properties) can be manipulated using JavaScript. This is particularly useful for theming and dynamic styling.\n\n```js\n// Set a CSS variable\ndocument.documentElement.style.setProperty('--main-color', 'blue');\n\n// Get the value of a CSS variable\nconst mainColor = getComputedStyle(document.documentElement).getPropertyValue(\n  '--main-color',\n);\nconsole.log(mainColor);\n```\n\n### Using external stylesheets\n\nYou can also manipulate styles by dynamically adding or removing stylesheets.\n\n```js\n// Create a new link element\nconst link = document.createElement('link');\nlink.rel = 'stylesheet';\nlink.href = 'styles.css';\n\n// Append the link element to the head\ndocument.head.appendChild(link);\n\n// Remove the link element\ndocument.head.removeChild(link);\n```\n\n## Further reading\n\n- [MDN Web Docs: Element.style](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style)\n- [MDN Web Docs: Element.classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)\n- [MDN Web Docs: Using CSS custom properties (variables)](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties)\n- [MDN Web Docs: Document.createElement()](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement)\n"
  },
  {
    "path": "questions/how-do-you-manipulate-css-styles-using-javascript/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-manipulate-css-styles-using-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"css\", \"web-api\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"DOM Manipulation & Events\"\n}\n"
  },
  {
    "path": "questions/how-do-you-manipulate-css-styles-using-javascript/zh-CN.mdx",
    "content": "---\ntitle: 如何使用 JavaScript 操作 CSS 样式？\n---\n\n## TL;DR\n\n您可以通过访问 HTML 元素的 `style` 属性来使用 JavaScript 操作 CSS 样式。例如，要更改 `id` 为 `myDiv` 的 `div` 元素的背景颜色，您可以使用：\n\n```js\ndocument.getElementById('myDiv').style.backgroundColor = 'blue';\n```\n\n您还可以使用 `classList` 属性添加、删除或切换 CSS 类：\n\n```js\ndocument.getElementById('myDiv').classList.add('newClass');\ndocument.getElementById('myDiv').classList.remove('oldClass');\ndocument.getElementById('myDiv').classList.toggle('toggleClass');\n```\n\n***\n\n## 使用 JavaScript 操作 CSS 样式\n\n### 访问和修改内联样式\n\n您可以使用 `style` 属性直接操作 HTML 元素的内联样式。此属性允许您设置单个 CSS 属性。\n\n```js\n// Select the element\nconst myDiv = document.getElementById('myDiv');\n\n// Change the background color\nmyDiv.style.backgroundColor = 'blue';\n\n// Set multiple styles\nmyDiv.style.width = '100px';\nmyDiv.style.height = '100px';\nmyDiv.style.border = '1px solid black';\n```\n\n### 使用 `classList` 属性\n\n`classList` 属性提供了在元素上添加、删除和切换 CSS 类的方法。这对于应用来自 CSS 文件的预定义样式很有用。\n\n```js\n// Select the element\nconst myDiv = document.getElementById('myDiv');\n\n// Add a class\nmyDiv.classList.add('newClass');\n\n// Remove a class\nmyDiv.classList.remove('oldClass');\n\n// Toggle a class\nmyDiv.classList.toggle('toggleClass');\n```\n\n### 使用 CSS 变量修改样式\n\n可以使用 JavaScript 操作 CSS 变量（自定义属性）。这对于主题和动态样式特别有用。\n\n```js\n// Set a CSS variable\ndocument.documentElement.style.setProperty('--main-color', 'blue');\n\n// Get the value of a CSS variable\nconst mainColor = getComputedStyle(document.documentElement).getPropertyValue(\n  '--main-color',\n);\nconsole.log(mainColor);\n```\n\n### 使用外部样式表\n\n您还可以通过动态添加或删除样式表来操作样式。\n\n```js\n// Create a new link element\nconst link = document.createElement('link');\nlink.rel = 'stylesheet';\nlink.href = 'styles.css';\n\n// Append the link element to the head\ndocument.head.appendChild(link);\n\n// Remove the link element\ndocument.head.removeChild(link);\n```\n\n## 延伸阅读\n\n* [MDN Web 文档：Element.style](https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLElement/style)\n* [MDN Web 文档：Element.classList](https://developer.mozilla.org/zh-CN/docs/Web/API/Element/classList)\n* [MDN Web 文档：使用 CSS 自定义属性（变量）](https://developer.mozilla.org/zh-CN/docs/Web/CSS/Using_CSS_custom_properties)\n* [MDN Web 文档：Document.createElement()](https://developer.mozilla.org/zh-CN/docs/Web/API/Document/createElement)\n"
  },
  {
    "path": "questions/how-do-you-organize-your-code-module-pattern-classical-inheritance/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"9eacf6bc\",\n        \"2a7816d0\",\n        \"bc12ba0f\",\n        \"82aa747e\",\n        \"6ba2ffe5\",\n        \"89c85b75\",\n        \"b4c6d9cc\",\n        \"72b944e8\",\n        \"6c3c3a52\",\n        \"1ed032fa\",\n        \"1f4bd4d3\",\n        \"84afc48b\",\n        \"cb6ad0cd\",\n        \"d198ab1b\",\n        \"76c60b9c\",\n        \"53c68fb2\",\n        \"67ddc1a6\",\n        \"bc8f5185\",\n        \"e22beaf8\",\n        \"750510df\",\n        \"1f4770e5\",\n        \"63685884\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"9eacf6bc\",\n        \"2a7816d0\",\n        \"bc12ba0f\",\n        \"82aa747e\",\n        \"6ba2ffe5\",\n        \"89c85b75\",\n        \"b4c6d9cc\",\n        \"72b944e8\",\n        \"6c3c3a52\",\n        \"1ed032fa\",\n        \"1f4bd4d3\",\n        \"84afc48b\",\n        \"cb6ad0cd\",\n        \"d198ab1b\",\n        \"76c60b9c\",\n        \"53c68fb2\",\n        \"67ddc1a6\",\n        \"bc8f5185\",\n        \"e22beaf8\",\n        \"750510df\",\n        \"1f4770e5\",\n        \"63685884\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"a4d94590\",\n    \"subtitle\": \"d8b55125\"\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-organize-your-code-module-pattern-classical-inheritance/en-US.mdx",
    "content": "---\ntitle: How do you organize your code?\nsubtitle: Do you use module pattern, classical inheritance, something else?\n---\n\n## TL;DR\n\nI organize my code by following a modular approach, using a clear folder structure, and adhering to coding standards and best practices. I separate concerns by dividing code into different layers such as components, services, and utilities. I also use naming conventions and documentation to ensure code readability and maintainability.\n\n---\n\n## How do you organize your code?\n\n### Modular approach\n\nI follow a modular approach to break down the application into smaller, reusable pieces. This helps in managing the codebase more efficiently and makes it easier to maintain and scale.\n\n### Folder structure\n\nI use a clear and consistent folder structure to organize my code. Here is a common structure for a React project:\n\n```\nsrc/\n|-- components/\n|   |-- Header/\n|   |   |-- Header.js\n|   |   |-- Header.css\n|   |-- Footer/\n|   |   |-- Footer.js\n|   |   |-- Footer.css\n|-- services/\n|   |-- apiService.js\n|-- utils/\n|   |-- helpers.js\n|-- App.js\n|-- index.js\n```\n\n### Separation of concerns\n\nI separate concerns by dividing the code into different layers:\n\n- **Components**: UI elements that are reusable and self-contained\n- **Services**: Functions that handle data fetching and business logic\n- **Utilities**: Helper functions and constants that can be used across the application\n\n### Naming conventions\n\nI use consistent naming conventions to improve code readability:\n\n- **Files and folders**: Use camelCase or kebab-case for file and folder names\n- **Components**: Use PascalCase for React component names\n- **Variables and functions**: Use camelCase for variable and function names\n\n### Documentation\n\nI document my code to make it easier for others (and myself) to understand:\n\n- **Comments**: Add comments to explain complex logic or important sections of the code\n- **README**: Include a README file with instructions on how to set up and run the project\n\n### Coding standards and best practices\n\nI adhere to coding standards and best practices to ensure code quality:\n\n- **Linting**: Use tools like ESLint to enforce coding standards\n- **Formatting**: Use tools like Prettier to maintain consistent code formatting\n- **Testing**: Write unit tests and integration tests to ensure code reliability\n\n## Further reading\n\n- [JavaScript Coding Standards](https://github.com/airbnb/javascript)\n- [How to Write Clean Code](https://www.freecodecamp.org/news/how-to-write-clean-code/)\n- [Effective JavaScript Documentation](https://jsdoc.app/)\n"
  },
  {
    "path": "questions/how-do-you-organize-your-code-module-pattern-classical-inheritance/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-organize-your-code-module-pattern-classical-inheritance\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": false,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/how-do-you-organize-your-code-module-pattern-classical-inheritance/pt-BR.mdx",
    "content": "---\ntitle: Como você organiza seu código?\nsubtitle: Você usa o pattern de modulo, herança clássica, algo mais?\n---\n\nNo passado, os desenvolvedores usavam o Backbone para os meus modelos, que incentivava uma abordagem mais OOP, criando modelos Backbone e anexando métodos a eles.\n\nO padrão de módulo ainda é ótimo, mas nos dias de hoje, os desenvolvedores preferem usar o React/Redux, que utiliza um fluxo de dados unidirecional baseado na arquitetura Flux. Agora é comum representar o modelo de dados de um aplicativo usando objetos simples e escrever funções puras de utilidade para manipular esses objetos. O State é manipulado usando ações e redutores como em qualquer outra aplicação Redux.\n\nEvite usar herança clássica sempre que possível. Quando e se tiver, mantenha [estas regras](https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4).\n"
  },
  {
    "path": "questions/how-do-you-organize-your-code-module-pattern-classical-inheritance/zh-CN.mdx",
    "content": "---\ntitle: 你如何组织你的代码？\nsubtitle: 你使用模块模式、经典继承还是其他方式？\n---\n\n## TL;DR\n\n我通过遵循模块化方法、使用清晰的文件夹结构以及遵守编码标准和最佳实践来组织我的代码。我通过将代码划分为不同的层（如组件、服务和实用程序）来分离关注点。我还使用命名约定和文档来确保代码的可读性和可维护性。\n\n***\n\n## 你如何组织你的代码？\n\n### 模块化方法\n\n我遵循模块化方法，将应用程序分解为更小、可重用的部分。这有助于更有效地管理代码库，并使其更易于维护和扩展。\n\n### 文件夹结构\n\n我使用清晰一致的文件夹结构来组织我的代码。以下是 React 项目的常见结构：\n\n```\nsrc/\n|-- components/\n|   |-- Header/\n|   |   |-- Header.js\n|   |   |-- Header.css\n|   |-- Footer/\n|   |   |-- Footer.js\n|   |   |-- Footer.css\n|-- services/\n|   |-- apiService.js\n|-- utils/\n|   |-- helpers.js\n|-- App.js\n|-- index.js\n```\n\n### 关注点分离\n\n我通过将代码划分为不同的层来分离关注点：\n\n* **组件**：可重用且自包含的 UI 元素\n* **服务**：处理数据获取和业务逻辑的函数\n* **实用程序**：可在整个应用程序中使用的辅助函数和常量\n\n### 命名约定\n\n我使用一致的命名约定来提高代码可读性：\n\n* **文件和文件夹**：对文件和文件夹名称使用 camelCase 或 kebab-case\n* **组件**：对 React 组件名称使用 PascalCase\n* **变量和函数**：对变量和函数名称使用 camelCase\n\n### 文档\n\n我记录我的代码，以便其他人（和我自己）更容易理解：\n\n* **注释**：添加注释以解释复杂的逻辑或代码的重要部分\n* **README**：包含一个 README 文件，其中包含有关如何设置和运行项目的说明\n\n### 编码标准和最佳实践\n\n我遵守编码标准和最佳实践，以确保代码质量：\n\n* **Linting**: 使用 ESLint 等工具来执行编码标准\n* **Formatting**: 使用 Prettier 等工具来保持一致的代码格式\n* **Testing**: 编写单元测试和集成测试以确保代码可靠性\n\n## 延伸阅读\n\n* [JavaScript 编码规范](https://github.com/airbnb/javascript)\n* [如何编写干净的代码](https://www.freecodecamp.org/news/how-to-write-clean-code/)\n* [有效的 JavaScript 文档](https://jsdoc.app/)\n"
  },
  {
    "path": "questions/how-do-you-prevent-the-default-behavior-of-an-event/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"87fe0485\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"bf104edd\",\n        \"cf44adc\",\n        \"7a1cb2be\",\n        \"2a7816d0\",\n        \"b03e75f4\",\n        \"3030837f\",\n        \"7498deed\",\n        \"cb221d89\",\n        \"e2d30460\",\n        \"575547b5\",\n        \"92b4d62f\",\n        \"4d6c4dda\",\n        \"dabdb934\",\n        \"fae963f1\",\n        \"7afed49\",\n        \"bb5aceeb\",\n        \"3da76af2\",\n        \"b967961d\",\n        \"1f4770e5\",\n        \"cb8ccacb\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"bf104edd\",\n        \"cf44adc\",\n        \"7a1cb2be\",\n        \"2a7816d0\",\n        \"b03e75f4\",\n        \"3030837f\",\n        \"7498deed\",\n        \"cb221d89\",\n        \"e2d30460\",\n        \"575547b5\",\n        \"92b4d62f\",\n        \"4d6c4dda\",\n        \"dabdb934\",\n        \"fae963f1\",\n        \"7afed49\",\n        \"bb5aceeb\",\n        \"3da76af2\",\n        \"b967961d\",\n        \"1f4770e5\",\n        \"cb8ccacb\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-prevent-the-default-behavior-of-an-event/en-US.mdx",
    "content": "---\ntitle: How do you prevent the default behavior of an event?\n---\n\n## TL;DR\n\nTo prevent the default behavior of an event in JavaScript, you can use the `preventDefault` method on the event object. For example, if you want to prevent a form from submitting, you can do the following:\n\n```js\ndocument.querySelector('form').addEventListener('submit', function (event) {\n  event.preventDefault();\n});\n```\n\nThis method stops the default action associated with the event from occurring.\n\n---\n\n## How do you prevent the default behavior of an event?\n\n### Using `preventDefault` method\n\nThe `preventDefault` method is used to stop the default action of an event from occurring. This is useful in scenarios where you want to override the default behavior of an element, such as preventing a link from navigating to a new page or stopping a form from submitting.\n\n### Example: Preventing form submission\n\nTo prevent a form from submitting, you can attach an event listener to the form's `submit` event and call `preventDefault` within the event handler:\n\n```js\ndocument.querySelector('form').addEventListener('submit', function (event) {\n  event.preventDefault();\n  // Additional code to handle form submission\n});\n```\n\n### Example: Preventing link navigation\n\nTo prevent a link from navigating to a new page, you can attach an event listener to the link's `click` event and call `preventDefault`:\n\n```js\ndocument.querySelector('a').addEventListener('click', function (event) {\n  event.preventDefault();\n  // Additional code to handle the click event\n});\n```\n\n### Example: Preventing default behavior in other events\n\nThe `preventDefault` method can be used with various other events, such as `keydown`, `contextmenu`, and more. Here is an example of preventing the default context menu from appearing on right-click:\n\n```js\ndocument.addEventListener('contextmenu', function (event) {\n  event.preventDefault();\n  // Additional code to handle the right-click event\n});\n```\n\n### Important considerations\n\n- The `preventDefault` method should be called within the event handler function.\n- Not all events have a default behavior that can be prevented. For example, custom events do not have default actions.\n\n## Further reading\n\n- [MDN Web Docs: Event.preventDefault()](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n- [JavaScript.info: Browser default actions](https://javascript.info/default-browser-action)\n- [W3Schools: JavaScript Event preventDefault()](https://www.w3schools.com/jsref/event_preventdefault.asp)\n"
  },
  {
    "path": "questions/how-do-you-prevent-the-default-behavior-of-an-event/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-prevent-the-default-behavior-of-an-event\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"DOM Manipulation & Events\"\n}\n"
  },
  {
    "path": "questions/how-do-you-prevent-the-default-behavior-of-an-event/zh-CN.mdx",
    "content": "---\ntitle: 如何阻止事件的默认行为？\n---\n\n## TL;DR\n\n要在 JavaScript 中阻止事件的默认行为，您可以在事件对象上使用 `preventDefault` 方法。例如，如果您想阻止表单提交，您可以执行以下操作：\n\n```js\ndocument.querySelector('form').addEventListener('submit', function (event) {\n  event.preventDefault();\n});\n```\n\n此方法会阻止与事件关联的默认操作发生。\n\n***\n\n## 如何阻止事件的默认行为？\n\n### 使用 `preventDefault` 方法\n\n`preventDefault` 方法用于阻止事件的默认操作发生。这在您想要覆盖元素的默认行为（例如，阻止链接导航到新页面或阻止表单提交）的情况下非常有用。\n\n### 示例：阻止表单提交\n\n要阻止表单提交，您可以将事件监听器附加到表单的 `submit` 事件，并在事件处理程序中调用 `preventDefault`：\n\n```js\ndocument.querySelector('form').addEventListener('submit', function (event) {\n  event.preventDefault();\n  // 额外的代码来处理表单提交\n});\n```\n\n### 示例：阻止链接导航\n\n要阻止链接导航到新页面，您可以将事件监听器附加到链接的 `click` 事件并调用 `preventDefault`：\n\n```js\ndocument.querySelector('a').addEventListener('click', function (event) {\n  event.preventDefault();\n  // 额外的代码来处理点击事件\n});\n```\n\n### 示例：阻止其他事件中的默认行为\n\n`preventDefault` 方法可以与各种其他事件一起使用，例如 `keydown`、`contextmenu` 等。 这是一个阻止右键单击时出现默认上下文菜单的示例：\n\n```js\ndocument.addEventListener('contextmenu', function (event) {\n  event.preventDefault();\n  // 额外的代码来处理右键单击事件\n});\n```\n\n### 重要注意事项\n\n* `preventDefault` 方法应在事件处理程序函数中调用。\n* 并非所有事件都具有可以阻止的默认行为。 例如，自定义事件没有默认操作。\n\n## 延伸阅读\n\n* [MDN Web Docs: Event.preventDefault()](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n* [JavaScript.info: Browser default actions](https://javascript.info/default-browser-action)\n* [W3Schools: JavaScript Event preventDefault()](https://www.w3schools.com/jsref/event_preventdefault.asp)\n"
  },
  {
    "path": "questions/how-do-you-redirect-to-a-new-page-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"6c0ed32d\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"a2d090b7\",\n        \"4ec99f70\",\n        \"2a7816d0\",\n        \"8ce9bef2\",\n        \"74a6daca\",\n        \"dc3f3967\",\n        \"f5729471\",\n        \"27dbb046\",\n        \"906695df\",\n        \"a71017d2\",\n        \"3ddeeef4\",\n        \"d574d5\",\n        \"af44266\",\n        \"fe16b779\",\n        \"ec1008d2\",\n        \"d4bec39f\",\n        \"a82b3d3c\",\n        \"895f229d\",\n        \"efb723d\",\n        \"1f4770e5\",\n        \"bb0a345a\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"a2d090b7\",\n        \"4ec99f70\",\n        \"2a7816d0\",\n        \"8ce9bef2\",\n        \"74a6daca\",\n        \"dc3f3967\",\n        \"f5729471\",\n        \"27dbb046\",\n        \"906695df\",\n        \"a71017d2\",\n        \"3ddeeef4\",\n        \"d574d5\",\n        \"af44266\",\n        \"fe16b779\",\n        \"ec1008d2\",\n        \"d4bec39f\",\n        \"a82b3d3c\",\n        \"895f229d\",\n        \"efb723d\",\n        \"1f4770e5\",\n        \"bb0a345a\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-redirect-to-a-new-page-in-javascript/en-US.mdx",
    "content": "---\ntitle: How do you redirect to a new page in JavaScript?\n---\n\n## TL;DR\n\nTo redirect to a new page in JavaScript, you can use the `window.location` object. The most common methods are `window.location.href` and `window.location.replace()`. For example:\n\n```js\n// Using window.location.href\nwindow.location.href = 'https://www.example.com';\n\n// Using window.location.replace()\nwindow.location.replace('https://www.example.com');\n```\n\n---\n\n## How do you redirect to a new page in JavaScript?\n\n### Using `window.location.href`\n\nThe `window.location.href` property is used to get or set the URL of the current page. When you set this property, the browser will navigate to the new URL, and it will create a new entry in the browser's history.\n\n```js\nwindow.location.href = 'https://www.example.com';\n```\n\n### Using `window.location.replace()`\n\nThe `window.location.replace()` method is similar to `window.location.href`, but it does not create a new entry in the browser's history. This means that the user cannot use the back button to return to the original page.\n\n```js\nwindow.location.replace('https://www.example.com');\n```\n\n### Using `window.location.assign()`\n\nThe `window.location.assign()` method works similarly to `window.location.href` and creates a new entry in the browser's history.\n\n```js\nwindow.location.assign('https://www.example.com');\n```\n\n### Using `window.location.reload()`\n\nIf you want to reload the current page, you can use the `window.location.reload()` method. This method can be useful if you want to refresh the page without changing the URL.\n\n```js\nwindow.location.reload();\n```\n\n### Using `window.history.pushState()`\n\nFor more advanced use cases, such as single-page applications (SPAs), you can use the `window.history.pushState()` method. This method allows you to change the URL without reloading the page.\n\n```js\nwindow.history.pushState({}, '', '/new-page');\n```\n\n## Further reading\n\n- [MDN Web Docs: Window.location](https://developer.mozilla.org/en-US/docs/Web/API/Window/location)\n- [MDN Web Docs: Window.location.href](https://developer.mozilla.org/en-US/docs/Web/API/Location/href)\n- [MDN Web Docs: Window.location.replace()](https://developer.mozilla.org/en-US/docs/Web/API/Location/replace)\n- [MDN Web Docs: Window.history.pushState()](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)\n"
  },
  {
    "path": "questions/how-do-you-redirect-to-a-new-page-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-redirect-to-a-new-page-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/how-do-you-redirect-to-a-new-page-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 如何在 JavaScript 中重定向到新页面？\n---\n\n## TL;DR\n\n要在 JavaScript 中重定向到新页面，可以使用 `window.location` 对象。最常用的方法是 `window.location.href` 和 `window.location.replace()`。例如：\n\n```js\n// Using window.location.href\nwindow.location.href = 'https://www.example.com';\n\n// Using window.location.replace()\nwindow.location.replace('https://www.example.com');\n```\n\n***\n\n## 如何在 JavaScript 中重定向到新页面？\n\n### 使用 `window.location.href`\n\n`window.location.href` 属性用于获取或设置当前页面的 URL。设置此属性后，浏览器将导航到新的 URL，并将在浏览器的历史记录中创建一个新条目。\n\n```js\nwindow.location.href = 'https://www.example.com';\n```\n\n### 使用 `window.location.replace()`\n\n`window.location.replace()` 方法类似于 `window.location.href`，但它不会在浏览器的历史记录中创建新条目。这意味着用户无法使用后退按钮返回到原始页面。\n\n```js\nwindow.location.replace('https://www.example.com');\n```\n\n### 使用 `window.location.assign()`\n\n`window.location.assign()` 方法与 `window.location.href` 类似，并在浏览器的历史记录中创建一个新条目。\n\n```js\nwindow.location.assign('https://www.example.com');\n```\n\n### 使用 `window.location.reload()`\n\n如果要重新加载当前页面，可以使用 `window.location.reload()` 方法。如果您想刷新页面而不更改 URL，此方法很有用。\n\n```js\nwindow.location.reload();\n```\n\n### 使用 `window.history.pushState()`\n\n对于更高级的用例，例如单页应用程序 (SPA)，您可以使用 `window.history.pushState()` 方法。此方法允许您更改 URL 而无需重新加载页面。\n\n```js\nwindow.history.pushState({}, '', '/new-page');\n```\n\n## 延伸阅读\n\n* [MDN Web 文档：Window.location](https://developer.mozilla.org/en-US/docs/Web/API/Window/location)\n* [MDN Web 文档：Window.location.href](https://developer.mozilla.org/en-US/docs/Web/API/Location/href)\n* [MDN Web 文档：Window.location.replace()](https://developer.mozilla.org/en-US/docs/Web/API/Location/replace)\n* [MDN Web 文档：Window.history.pushState()](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)\n"
  },
  {
    "path": "questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"bb4e7bf4\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"e40f8891\",\n        \"a04c812a\",\n        \"2a7816d0\",\n        \"95135f93\",\n        \"86130dde\",\n        \"f690abea\",\n        \"794b5e3a\",\n        \"ae932cd3\",\n        \"d3ff3995\",\n        \"d429a578\",\n        \"e41d192f\",\n        \"7406187\",\n        \"8bcb2a1f\",\n        \"26aeeb5a\",\n        \"8e3ac5c\",\n        \"8699a701\",\n        \"71a20fff\",\n        \"2fc4afe\",\n        \"1f4770e5\",\n        \"7f7019e3\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"e40f8891\",\n        \"a04c812a\",\n        \"2a7816d0\",\n        \"95135f93\",\n        \"86130dde\",\n        \"f690abea\",\n        \"794b5e3a\",\n        \"ae932cd3\",\n        \"d3ff3995\",\n        \"d429a578\",\n        \"e41d192f\",\n        \"7406187\",\n        \"8bcb2a1f\",\n        \"26aeeb5a\",\n        \"8e3ac5c\",\n        \"8699a701\",\n        \"71a20fff\",\n        \"2fc4afe\",\n        \"1f4770e5\",\n        \"7f7019e3\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-reliably-determine-whether-an-object-is-empty/en-US.mdx",
    "content": "---\ntitle: How do you reliably determine whether an object is empty?\n---\n\n## TL;DR\n\nTo reliably determine whether an object is empty, you can use `Object.keys()` to check if the object has any enumerable properties. If the length of the array returned by `Object.keys()` is zero, the object is empty.\n\n```js live\nconst isEmpty = (obj) => Object.keys(obj).length === 0;\n\nconst obj = {};\nconsole.log(isEmpty(obj)); // true\n```\n\n---\n\n## How do you reliably determine whether an object is empty?\n\n### Using `Object.keys()`\n\nThe most common and reliable way to check if an object is empty is by using `Object.keys()`. This method returns an array of the object's own enumerable property names. If the length of this array is zero, the object is empty.\n\n```js live\nconst isEmpty = (obj) => Object.keys(obj).length === 0;\n\nconst obj1 = {};\nconst obj2 = { key: 'value' };\n\nconsole.log(isEmpty(obj1)); // true\nconsole.log(isEmpty(obj2)); // false\n```\n\n### Using `Object.entries()`\n\nAnother method is to use `Object.entries()`, which returns an array of the object's own enumerable property `[key, value]` pairs. If the length of this array is zero, the object is empty.\n\n```js live\nconst isEmpty = (obj) => Object.entries(obj).length === 0;\n\nconst obj1 = {};\nconst obj2 = { key: 'value' };\n\nconsole.log(isEmpty(obj1)); // true\nconsole.log(isEmpty(obj2)); // false\n```\n\n### Using `Object.values()`\n\nSimilarly, you can use `Object.values()`, which returns an array of the object's own enumerable property values. If the length of this array is zero, the object is empty.\n\n```js live\nconst isEmpty = (obj) => Object.values(obj).length === 0;\n\nconst obj1 = {};\nconst obj2 = { key: 'value' };\n\nconsole.log(isEmpty(obj1)); // true\nconsole.log(isEmpty(obj2)); // false\n```\n\n### Using a `for...in` loop\n\nYou can also use a `for...in` loop to check if an object has any properties. If the loop doesn't iterate over any properties, the object is empty.\n\n```js live\nconst isEmpty = (obj) => {\n  for (let key in obj) {\n    if (obj.hasOwnProperty(key)) {\n      return false;\n    }\n  }\n  return true;\n};\n\nconst obj1 = {};\nconst obj2 = { key: 'value' };\nconst childObj = Object.create(obj2); // Inherit from obj2\n\nconsole.log(isEmpty(obj1)); // true\nconsole.log(isEmpty(obj2)); // false\nconsole.log(isEmpty(childObj)); // true (has no own properties)\nconsole.log(childObj.key); // Output: 'value' (still has the inherited property)\n```\n\n### Edge cases\n\n- **Prototype properties**: The methods above only check for the object's own properties, not properties inherited from its prototype.\n- **Non-enumerable properties**: These methods do not account for non-enumerable properties.\n\n## Further reading\n\n- [MDN Web Docs: Object.keys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)\n- [MDN Web Docs: Object.entries()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)\n- [MDN Web Docs: Object.values()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values)\n- [MDN Web Docs: for...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)\n"
  },
  {
    "path": "questions/how-do-you-reliably-determine-whether-an-object-is-empty/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-reliably-determine-whether-an-object-is-empty\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/how-do-you-reliably-determine-whether-an-object-is-empty/zh-CN.mdx",
    "content": "---\ntitle: 如何可靠地确定一个对象是否为空？\n---\n\n## TL;DR\n\n要可靠地确定一个对象是否为空，您可以使用 `Object.keys()` 来检查该对象是否具有任何可枚举的属性。如果 `Object.keys()` 返回的数组的长度为零，则该对象为空。\n\n```js live\nconst isEmpty = (obj) => Object.keys(obj).length === 0;\n\nconst obj = {};\nconsole.log(isEmpty(obj)); // true\n```\n\n***\n\n## 如何可靠地确定一个对象是否为空？\n\n### 使用 `Object.keys()`\n\n检查对象是否为空的最常见和可靠的方法是使用 `Object.keys()`。此方法返回一个包含对象自身可枚举属性名称的数组。如果此数组的长度为零，则该对象为空。\n\n```js live\nconst isEmpty = (obj) => Object.keys(obj).length === 0;\n\nconst obj1 = {};\nconst obj2 = { key: 'value' };\n\nconsole.log(isEmpty(obj1)); // true\nconsole.log(isEmpty(obj2)); // false\n```\n\n### 使用 `Object.entries()`\n\n另一种方法是使用 `Object.entries()`，它返回一个包含对象自身可枚举属性 `[key, value]` 对的数组。如果此数组的长度为零，则该对象为空。\n\n```js live\nconst isEmpty = (obj) => Object.entries(obj).length === 0;\n\nconst obj1 = {};\nconst obj2 = { key: 'value' };\n\nconsole.log(isEmpty(obj1)); // true\nconsole.log(isEmpty(obj2)); // false\n```\n\n### 使用 `Object.values()`\n\n同样，您可以使用 `Object.values()`，它返回一个包含对象自身可枚举属性值的数组。如果此数组的长度为零，则该对象为空。\n\n```js live\nconst isEmpty = (obj) => Object.values(obj).length === 0;\n\nconst obj1 = {};\nconst obj2 = { key: 'value' };\n\nconsole.log(isEmpty(obj1)); // true\nconsole.log(isEmpty(obj2)); // false\n```\n\n### 使用 `for...in` 循环\n\n您还可以使用 `for...in` 循环来检查对象是否具有任何属性。如果循环没有遍历任何属性，则该对象为空。\n\n```js live\nconst isEmpty = (obj) => {\n  for (let key in obj) {\n    if (obj.hasOwnProperty(key)) {\n      return false;\n    }\n  }\n  return true;\n};\n\nconst obj1 = {};\nconst obj2 = { key: 'value' };\nconst childObj = Object.create(obj2); // Inherit from obj2\n\nconsole.log(isEmpty(obj1)); // true\nconsole.log(isEmpty(obj2)); // false\nconsole.log(isEmpty(childObj)); // true (has no own properties)\nconsole.log(childObj.key); // Output: 'value' (still has the inherited property)\n```\n\n### 边缘情况\n\n* **原型属性**：上述方法仅检查对象自身的属性，而不是从其原型继承的属性。\n* **不可枚举属性**：这些方法不考虑不可枚举属性。\n\n## 延伸阅读\n\n* [MDN Web 文档：Object.keys()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)\n* [MDN Web 文档：Object.entries()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)\n* [MDN Web 文档：Object.values()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/values)\n* [MDN Web 文档：for...in](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...in)\n"
  },
  {
    "path": "questions/how-do-you-use-windowhistory-api/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"89e8be16\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3de58dbe\",\n        \"2a7816d0\",\n        \"e4a7c86e\",\n        \"b4ce6522\",\n        \"fb0a4c07\",\n        \"3f17f66a\",\n        \"762a5af5\",\n        \"dfe52398\",\n        \"15b43d11\",\n        \"a89ccc61\",\n        \"bdc0a8a8\",\n        \"9eb64cc4\",\n        \"6e4399ea\",\n        \"7f8c9480\",\n        \"25f535d4\",\n        \"4fc778c7\",\n        \"cbb4a303\",\n        \"3a662b33\",\n        \"afa05dad\",\n        \"c41f0511\",\n        \"66836483\",\n        \"34606c68\",\n        \"9b5019f0\",\n        \"c856260e\",\n        \"302cc985\",\n        \"1f4770e5\",\n        \"ddc4e63b\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3de58dbe\",\n        \"2a7816d0\",\n        \"e4a7c86e\",\n        \"b4ce6522\",\n        \"fb0a4c07\",\n        \"3f17f66a\",\n        \"762a5af5\",\n        \"dfe52398\",\n        \"15b43d11\",\n        \"a89ccc61\",\n        \"bdc0a8a8\",\n        \"9eb64cc4\",\n        \"6e4399ea\",\n        \"7f8c9480\",\n        \"25f535d4\",\n        \"4fc778c7\",\n        \"cbb4a303\",\n        \"3a662b33\",\n        \"afa05dad\",\n        \"c41f0511\",\n        \"66836483\",\n        \"34606c68\",\n        \"9b5019f0\",\n        \"c856260e\",\n        \"302cc985\",\n        \"1f4770e5\",\n        \"ddc4e63b\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-use-windowhistory-api/en-US.mdx",
    "content": "---\ntitle: How do you use `window.history` API?\n---\n\n## TL;DR\n\nThe `window.history` API allows you to manipulate the browser's session history. You can use `history.pushState()` to add a new entry to the history stack, `history.replaceState()` to modify the current entry, and `history.back()`, `history.forward()`, and `history.go()` to navigate through the history. For example, `history.pushState({page: 1}, \"title 1\", \"?page=1\")` adds a new entry to the history.\n\n---\n\n## Using the `window.history` API\n\nThe `window.history` API provides methods to interact with the browser's history stack. This can be useful for single-page applications (SPAs) where you want to manage the URL and browser history without causing a full page reload.\n\n### Methods\n\n#### `history.pushState()`\n\nThis method adds a new entry to the history stack.\n\n```js\nhistory.pushState({ page: 1 }, 'title 1', '?page=1');\n```\n\n- The first parameter is a state object associated with the new history entry.\n- The second parameter is the title of the new history entry (currently ignored by most browsers).\n- The third parameter is the URL to be displayed in the address bar.\n\n#### `history.replaceState()`\n\nThis method modifies the current history entry.\n\n```js\nhistory.replaceState({ page: 2 }, 'title 2', '?page=2');\n```\n\n- The parameters are the same as `pushState()`, but this method replaces the current entry instead of adding a new one.\n\n#### `history.back()`\n\nThis method moves the user back one entry in the history stack, similar to clicking the browser's back button.\n\n```js\nhistory.back();\n```\n\n#### `history.forward()`\n\nThis method moves the user forward one entry in the history stack, similar to clicking the browser's forward button.\n\n```js\nhistory.forward();\n```\n\n#### `history.go()`\n\nThis method moves the user a specified number of entries in the history stack.\n\n```js\n// Move back one entry\nhistory.go(-1);\n\n// Move forward one entry\nhistory.go(1);\n\n// Reload the current page\nhistory.go(0);\n```\n\n### Example\n\nHere's a simple example demonstrating the use of `pushState` and `replaceState`:\n\n```html\n<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <title>History API Example</title>\n  </head>\n  <body>\n    <button id=\"pushStateBtn\">Push State</button>\n    <button id=\"replaceStateBtn\">Replace State</button>\n    <button id=\"backBtn\">Back</button>\n    <button id=\"forwardBtn\">Forward</button>\n\n    <script>\n      document.getElementById('pushStateBtn').addEventListener('click', () => {\n        history.pushState({ page: 1 }, 'title 1', '?page=1');\n      });\n\n      document\n        .getElementById('replaceStateBtn')\n        .addEventListener('click', () => {\n          history.replaceState({ page: 2 }, 'title 2', '?page=2');\n        });\n\n      document.getElementById('backBtn').addEventListener('click', () => {\n        history.back();\n      });\n\n      document.getElementById('forwardBtn').addEventListener('click', () => {\n        history.forward();\n      });\n    </script>\n  </body>\n</html>\n```\n\n## Further reading\n\n- [MDN Web Docs: History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API)\n- [MDN Web Docs: `history.pushState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)\n- [MDN Web Docs: `history.replaceState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)\n- [MDN Web Docs: `history.back()`](https://developer.mozilla.org/en-US/docs/Web/API/History/back)\n- [MDN Web Docs: `history.forward()`](https://developer.mozilla.org/en-US/docs/Web/API/History/forward)\n- [MDN Web Docs: `history.go()`](https://developer.mozilla.org/en-US/docs/Web/API/History/go)\n"
  },
  {
    "path": "questions/how-do-you-use-windowhistory-api/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-use-windowhistory-api\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/how-do-you-use-windowhistory-api/zh-CN.mdx",
    "content": "---\ntitle: 如何使用 `window.history` API？\n---\n\n## TL;DR\n\n通过 `window.history` API，您可以操作浏览器的会话历史记录。您可以使用 `history.pushState()` 向历史堆栈添加新条目，使用 `history.replaceState()` 修改当前条目，以及使用 `history.back()`、`history.forward()` 和 `history.go()` 在历史记录中导航。例如，`history.pushState({page: 1}, \"title 1\", \"?page=1\")` 向历史记录添加一个新条目。\n\n***\n\n## 使用 `window.history` API\n\n`window.history` API 提供了与浏览器历史堆栈交互的方法。这对于单页应用程序 (SPA) 很有用，您希望管理 URL 和浏览器历史记录，而无需导致完全页面重新加载。\n\n### 方法\n\n#### `history.pushState()`\n\n此方法向历史堆栈添加一个新条目。\n\n```js\nhistory.pushState({ page: 1 }, 'title 1', '?page=1');\n```\n\n* 第一个参数是与新历史记录条目关联的状态对象。\n* 第二个参数是新历史记录条目的标题（目前大多数浏览器都忽略）。\n* 第三个参数是要显示在地址栏中的 URL。\n\n#### `history.replaceState()`\n\n此方法修改当前历史记录条目。\n\n```js\nhistory.replaceState({ page: 2 }, 'title 2', '?page=2');\n```\n\n* 参数与 `pushState()` 相同，但此方法替换当前条目，而不是添加新条目。\n\n#### `history.back()`\n\n此方法将用户在历史堆栈中后退一个条目，类似于单击浏览器的后退按钮。\n\n```js\nhistory.back();\n```\n\n#### `history.forward()`\n\n此方法使用户在历史堆栈中向前移动一个条目，类似于单击浏览器的前进按钮。\n\n```js\nhistory.forward();\n```\n\n#### `history.go()`\n\n此方法将用户在历史堆栈中移动指定的条目数。\n\n```js\n// Move back one entry\nhistory.go(-1);\n\n// Move forward one entry\nhistory.go(1);\n\n// Reload the current page\nhistory.go(0);\n```\n\n### 示例\n\n这是一个简单的示例，演示了 `pushState` 和 `replaceState` 的用法：\n\n```html\n<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <title>History API Example</title>\n  </head>\n  <body>\n    <button id=\"pushStateBtn\">Push State</button>\n    <button id=\"replaceStateBtn\">Replace State</button>\n    <button id=\"backBtn\">Back</button>\n    <button id=\"forwardBtn\">Forward</button>\n\n    <script>\n      document.getElementById('pushStateBtn').addEventListener('click', () => {\n        history.pushState({ page: 1 }, 'title 1', '?page=1');\n      });\n\n      document\n        .getElementById('replaceStateBtn')\n        .addEventListener('click', () => {\n          history.replaceState({ page: 2 }, 'title 2', '?page=2');\n        });\n\n      document.getElementById('backBtn').addEventListener('click', () => {\n        history.back();\n      });\n\n      document.getElementById('forwardBtn').addEventListener('click', () => {\n        history.forward();\n      });\n    </script>\n  </body>\n</html>\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API)\n* [MDN Web Docs: `history.pushState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState)\n* [MDN Web Docs: `history.replaceState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState)\n* [MDN Web Docs: `history.back()`](https://developer.mozilla.org/en-US/docs/Web/API/History/back)\n* [MDN Web Docs: `history.forward()`](https://developer.mozilla.org/en-US/docs/Web/API/History/forward)\n* [MDN Web Docs: `history.go()`](https://developer.mozilla.org/en-US/docs/Web/API/History/go)\n"
  },
  {
    "path": "questions/how-do-you-validate-form-elements-using-the-constraint-validation-api/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"90486b0f\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"fbe2f2d5\",\n        \"2f04741c\",\n        \"2a7816d0\",\n        \"46083c74\",\n        \"83283a80\",\n        \"4a30a441\",\n        \"2c608d7b\",\n        \"6e5ba15f\",\n        \"a829ec7e\",\n        \"ff214208\",\n        \"6fd0665e\",\n        \"c0fbbc9a\",\n        \"ad893d15\",\n        \"a6c3196d\",\n        \"f24f07f8\",\n        \"ee0689eb\",\n        \"628b458c\",\n        \"d34b4358\",\n        \"cfce609c\",\n        \"2748d196\",\n        \"34237970\",\n        \"4f338cf9\",\n        \"9b5019f0\",\n        \"19646f73\",\n        \"fb469bef\",\n        \"1bf2c887\",\n        \"1f4770e5\",\n        \"2de0d5ff\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"fbe2f2d5\",\n        \"2f04741c\",\n        \"2a7816d0\",\n        \"46083c74\",\n        \"83283a80\",\n        \"4a30a441\",\n        \"2c608d7b\",\n        \"6e5ba15f\",\n        \"a829ec7e\",\n        \"ff214208\",\n        \"6fd0665e\",\n        \"c0fbbc9a\",\n        \"ad893d15\",\n        \"a6c3196d\",\n        \"f24f07f8\",\n        \"ee0689eb\",\n        \"628b458c\",\n        \"d34b4358\",\n        \"cfce609c\",\n        \"2748d196\",\n        \"34237970\",\n        \"4f338cf9\",\n        \"9b5019f0\",\n        \"19646f73\",\n        \"fb469bef\",\n        \"1bf2c887\",\n        \"1f4770e5\",\n        \"2de0d5ff\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-validate-form-elements-using-the-constraint-validation-api/en-US.mdx",
    "content": "---\ntitle: How do you validate form elements using the Constraint Validation API?\n---\n\n## TL;DR\n\nThe Constraint Validation API provides a way to validate form elements in HTML. You can use properties like `validity`, `validationMessage`, and methods like `checkValidity()` and `setCustomValidity()`. For example, to check if an input is valid, you can use:\n\n```js\nconst input = document.querySelector('input');\nif (input.checkValidity()) {\n  console.log('Input is valid');\n} else {\n  console.log(input.validationMessage);\n}\n```\n\n---\n\n## How do you validate form elements using the Constraint Validation API?\n\n### Introduction\n\nThe Constraint Validation API is a set of methods and properties available on form elements that allow you to perform validation checks and provide feedback to users. This API is built into HTML5 and provides a way to validate form inputs without needing to write custom JavaScript validation logic.\n\n### Key properties and methods\n\n#### `checkValidity()`\n\nThe `checkValidity()` method checks if an element meets all its validation constraints. It returns `true` if the element is valid and `false` otherwise.\n\n```js\nconst input = document.querySelector('input');\nif (input.checkValidity()) {\n  console.log('Input is valid');\n} else {\n  console.log('Input is invalid');\n}\n```\n\n#### `reportValidity()`\n\nThe `reportValidity()` method works like `checkValidity()` but also displays the browser's default validation message if the element is invalid.\n\n```js\nconst input = document.querySelector('input');\nif (!input.reportValidity()) {\n  console.log('Input is invalid');\n}\n```\n\n#### `setCustomValidity()`\n\nThe `setCustomValidity()` method allows you to set a custom validation message. If a custom message is set, the element will be considered invalid.\n\n```js\nconst input = document.querySelector('input');\ninput.setCustomValidity('This field is required');\nif (!input.checkValidity()) {\n  console.log(input.validationMessage); // Outputs: This field is required\n}\n```\n\n#### `validity`\n\nThe `validity` property is an object that contains several boolean properties indicating the validity state of the element, such as `valid`, `valueMissing`, `typeMismatch`, etc.\n\n```js\nconst input = document.querySelector('input');\nif (input.validity.valueMissing) {\n  console.log('Value is missing');\n}\n```\n\n#### `validationMessage`\n\nThe `validationMessage` property returns the message that will be shown to the user if the element is invalid.\n\n```js\nconst input = document.querySelector('input');\nif (!input.checkValidity()) {\n  console.log(input.validationMessage);\n}\n```\n\n### Example\n\nHere is a complete example that demonstrates how to use the Constraint Validation API to validate a form:\n\n```html\n<form id=\"myForm\">\n  <input type=\"text\" id=\"username\" required />\n  <input type=\"submit\" value=\"Submit\" />\n</form>\n\n<script>\n  const form = document.getElementById('myForm');\n  const username = document.getElementById('username');\n\n  form.addEventListener('submit', function (event) {\n    if (!username.checkValidity()) {\n      username.setCustomValidity('Username is required');\n      username.reportValidity();\n      event.preventDefault();\n    } else {\n      username.setCustomValidity(''); // Clear custom message\n    }\n  });\n</script>\n```\n\nIn this example, the form will not submit if the `username` input is empty, and a custom validation message will be displayed.\n\n## Further reading\n\n- [MDN Web Docs: Constraint Validation](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Constraint_validation)\n- [MDN Web Docs: HTMLFormElement.checkValidity()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/checkValidity)\n- [MDN Web Docs: HTMLObjectElement.setCustomValidity()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLObjectElement/setCustomValidity)\n"
  },
  {
    "path": "questions/how-do-you-validate-form-elements-using-the-constraint-validation-api/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-validate-form-elements-using-the-constraint-validation-api\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"advanced\",\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/how-do-you-validate-form-elements-using-the-constraint-validation-api/zh-CN.mdx",
    "content": "---\ntitle: 如何使用约束验证 API 验证表单元素？\n---\n\n## TL;DR\n\n约束验证 API 提供了一种验证 HTML 表单元素的方法。您可以使用 `validity`、`validationMessage` 等属性以及 `checkValidity()` 和 `setCustomValidity()` 等方法。例如，要检查输入是否有效，您可以使用：\n\n```js\nconst input = document.querySelector('input');\nif (input.checkValidity()) {\n  console.log('Input is valid');\n} else {\n  console.log(input.validationMessage);\n}\n```\n\n***\n\n## 如何使用约束验证 API 验证表单元素？\n\n### 简介\n\n约束验证 API 是一组在表单元素上可用的方法和属性，允许您执行验证检查并向用户提供反馈。此 API 内置于 HTML5 中，提供了一种验证表单输入的方法，而无需编写自定义 JavaScript 验证逻辑。\n\n### 关键属性和方法\n\n#### `checkValidity()`\n\n`checkValidity()` 方法检查元素是否满足其所有验证约束。如果元素有效，则返回 `true`，否则返回 `false`。\n\n```js\nconst input = document.querySelector('input');\nif (input.checkValidity()) {\n  console.log('Input is valid');\n} else {\n  console.log('Input is invalid');\n}\n```\n\n#### `reportValidity()`\n\n`reportValidity()` 方法的工作方式与 `checkValidity()` 类似，但如果元素无效，它还会显示浏览器的默认验证消息。\n\n```js\nconst input = document.querySelector('input');\nif (!input.reportValidity()) {\n  console.log('Input is invalid');\n}\n```\n\n#### `setCustomValidity()`\n\n`setCustomValidity()` 方法允许您设置自定义验证消息。如果设置了自定义消息，则该元素将被视为无效。\n\n```js\nconst input = document.querySelector('input');\ninput.setCustomValidity('This field is required');\nif (!input.checkValidity()) {\n  console.log(input.validationMessage); // Outputs: This field is required\n}\n```\n\n#### `validity`\n\n`validity` 属性是一个对象，包含几个布尔属性，指示元素的有效性状态，例如 `valid`、`valueMissing`、`typeMismatch` 等。\n\n```js\nconst input = document.querySelector('input');\nif (input.validity.valueMissing) {\n  console.log('Value is missing');\n}\n```\n\n#### `validationMessage`\n\n如果元素无效，`validationMessage` 属性将返回将向用户显示的消息。\n\n```js\nconst input = document.querySelector('input');\nif (!input.checkValidity()) {\n  console.log(input.validationMessage);\n}\n```\n\n### 示例\n\n这是一个完整的示例，演示了如何使用约束验证 API 来验证表单：\n\n```html\n<form id=\"myForm\">\n  <input type=\"text\" id=\"username\" required />\n  <input type=\"submit\" value=\"Submit\" />\n</form>\n\n<script>\n  const form = document.getElementById('myForm');\n  const username = document.getElementById('username');\n\n  form.addEventListener('submit', function (event) {\n    if (!username.checkValidity()) {\n      username.setCustomValidity('Username is required');\n      username.reportValidity();\n      event.preventDefault();\n    } else {\n      username.setCustomValidity(''); // Clear custom message\n    }\n  });\n</script>\n```\n\n在此示例中，如果 `username` 输入为空，则表单将不会提交，并且将显示自定义验证消息。\n\n## 延伸阅读\n\n* [MDN Web Docs: Constraint Validation](https://developer.mozilla.org/zh-CN/docs/Web/Guide/HTML/Constraint_validation)\n* [MDN Web Docs: HTMLFormElement.checkValidity()](https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLFormElement/checkValidity)\n* [MDN Web Docs: HTMLObjectElement.setCustomValidity()](https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLObjectElement/setCustomValidity)\n"
  },
  {
    "path": "questions/how-do-you-write-unit-tests-for-javascript-code/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"94296de\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"5e12438a\",\n        \"8e4dcc86\",\n        \"8657052e\",\n        \"2a7816d0\",\n        \"f5a328f2\",\n        \"b2393455\",\n        \"56954944\",\n        \"2127f802\",\n        \"68c024d8\",\n        \"cd660751\",\n        \"a20311c6\",\n        \"63e91f35\",\n        \"ae1ce134\",\n        \"3f8f7a1d\",\n        \"e76b9a8\",\n        \"4036dd21\",\n        \"5bdb4be7\",\n        \"276d81b8\",\n        \"e76b9a8\",\n        \"ca741ea3\",\n        \"80dfc734\",\n        \"12cec0e7\",\n        \"e76b9a8\",\n        \"ebc5f58a\",\n        \"bd14ebd5\",\n        \"cbbe1b76\",\n        \"55afeaa7\",\n        \"1f4770e5\",\n        \"1b7e90d8\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"5e12438a\",\n        \"8e4dcc86\",\n        \"8657052e\",\n        \"2a7816d0\",\n        \"f5a328f2\",\n        \"b2393455\",\n        \"56954944\",\n        \"2127f802\",\n        \"68c024d8\",\n        \"cd660751\",\n        \"a20311c6\",\n        \"63e91f35\",\n        \"ae1ce134\",\n        \"3f8f7a1d\",\n        \"e76b9a8\",\n        \"4036dd21\",\n        \"5bdb4be7\",\n        \"276d81b8\",\n        \"e76b9a8\",\n        \"ca741ea3\",\n        \"80dfc734\",\n        \"12cec0e7\",\n        \"e76b9a8\",\n        \"ebc5f58a\",\n        \"bd14ebd5\",\n        \"cbbe1b76\",\n        \"55afeaa7\",\n        \"1f4770e5\",\n        \"1b7e90d8\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-do-you-write-unit-tests-for-javascript-code/en-US.mdx",
    "content": "---\ntitle: How do you write unit tests for JavaScript code?\n---\n\n## TL;DR\n\nTo write unit tests for JavaScript code, you typically use a testing framework like Jest or Mocha. First, you set up your testing environment by installing the necessary libraries. Then, you write test cases using functions like `describe`, `it`, or `test` to define your tests. Each test case should focus on a small, isolated piece of functionality. You use assertions to check if the output of your code matches the expected result.\n\nExample using Jest:\n\n```js\n// sum.js\nfunction sum(a, b) {\n  return a + b;\n}\nmodule.exports = sum;\n\n// sum.test.js\nconst sum = require('./sum');\n\ntest('adds 1 + 2 to equal 3', () => {\n  expect(sum(1, 2)).toBe(3);\n});\n```\n\n---\n\n## Setting up the testing environment\n\n### Installing Jest\n\nTo get started with Jest, you need to install it via npm:\n\n```bash\nnpm install --save-dev jest\n```\n\n### Configuring Jest\n\nAdd a script to your `package.json` to run Jest:\n\n```json\n{\n  \"scripts\": {\n    \"test\": \"jest\"\n  }\n}\n```\n\n## Writing test cases\n\n### Basic structure\n\nA test file typically contains one or more `describe` blocks, which group related tests, and `it` or `test` blocks, which define individual test cases.\n\nExample:\n\n```js\n// sum.js\nfunction sum(a, b) {\n  return a + b;\n}\nmodule.exports = sum;\n\n// sum.test.js\nconst sum = require('./sum');\n\ndescribe('sum function', () => {\n  test('adds 1 + 2 to equal 3', () => {\n    expect(sum(1, 2)).toBe(3);\n  });\n\n  test('adds -1 + 1 to equal 0', () => {\n    expect(sum(-1, 1)).toBe(0);\n  });\n});\n```\n\n### Using assertions\n\nAssertions are used to check if the output of your code matches the expected result. Jest provides various assertion methods like `toBe`, `toEqual`, `toBeNull`, etc.\n\nExample:\n\n```js\ntest('object assignment', () => {\n  const data = { one: 1 };\n  data['two'] = 2;\n  expect(data).toEqual({ one: 1, two: 2 });\n});\n```\n\n## Mocking dependencies\n\nSometimes, you need to mock dependencies to isolate the unit of code you are testing. Jest provides functions like `jest.fn()` and `jest.mock()` for this purpose.\n\nExample:\n\n```js\n// fetchData.js\nconst fetch = require('node-fetch');\n\nasync function fetchData(url) {\n  const response = await fetch(url);\n  return response.json();\n}\nmodule.exports = fetchData;\n\n// fetchData.test.js\nconst fetchData = require('./fetchData');\nconst fetch = require('node-fetch');\n\njest.mock('node-fetch');\n\ntest('fetches data from API', async () => {\n  const mockResponse = { data: '12345' };\n  fetch.mockResolvedValueOnce({\n    json: async () => mockResponse,\n  });\n\n  const data = await fetchData('https://api.example.com/data');\n  expect(data).toEqual(mockResponse);\n});\n```\n\n## Running the tests\n\nTo run your tests, use the following command:\n\n```bash\nnpm test\n```\n\n## Further reading\n\n- [Jest documentation](https://jestjs.io/docs/getting-started)\n- [Mocha documentation](https://mochajs.org/)\n- [Chai documentation](https://www.chaijs.com/)\n- [Sinon documentation](https://sinonjs.org/)\n"
  },
  {
    "path": "questions/how-do-you-write-unit-tests-for-javascript-code/metadata.json",
    "content": "{\n  \"slug\": \"how-do-you-write-unit-tests-for-javascript-code\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"testing\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Testing\"\n}\n"
  },
  {
    "path": "questions/how-do-you-write-unit-tests-for-javascript-code/zh-CN.mdx",
    "content": "---\ntitle: 如何为 JavaScript 代码编写单元测试？\n---\n\n## 总结\n\n要为 JavaScript 代码编写单元测试，您通常使用 Jest 或 Mocha 等测试框架。首先，您通过安装必要的库来设置测试环境。然后，您使用 `describe`、`it` 或 `test` 等函数编写测试用例来定义您的测试。每个测试用例都应侧重于一小段孤立的功能。您使用断言来检查代码的输出是否与预期结果匹配。\n\n使用 Jest 的示例：\n\n```js\n// sum.js\nfunction sum(a, b) {\n  return a + b;\n}\nmodule.exports = sum;\n\n// sum.test.js\nconst sum = require('./sum');\n\ntest('adds 1 + 2 to equal 3', () => {\n  expect(sum(1, 2)).toBe(3);\n});\n```\n\n***\n\n## 设置测试环境\n\n### 安装 Jest\n\n要开始使用 Jest，您需要通过 npm 安装它：\n\n```bash\nnpm install --save-dev jest\n```\n\n### 配置 Jest\n\n将脚本添加到您的 `package.json` 以运行 Jest：\n\n```json\n{\n  \"scripts\": {\n    \"test\": \"jest\"\n  }\n}\n```\n\n## 编写测试用例\n\n### 基本结构\n\n测试文件通常包含一个或多个 `describe` 块（用于分组相关测试）和 `it` 或 `test` 块（用于定义单个测试用例）。\n\n示例：\n\n```js\n// sum.js\nfunction sum(a, b) {\n  return a + b;\n}\nmodule.exports = sum;\n\n// sum.test.js\nconst sum = require('./sum');\n\ndescribe('sum function', () => {\n  test('adds 1 + 2 to equal 3', () => {\n    expect(sum(1, 2)).toBe(3);\n  });\n\n  test('adds -1 + 1 to equal 0', () => {\n    expect(sum(-1, 1)).toBe(0);\n  });\n});\n```\n\n### 使用断言\n\n断言用于检查代码的输出是否与预期结果匹配。Jest 提供了各种断言方法，如 `toBe`、`toEqual`、`toBeNull` 等。\n\n示例：\n\n```js\ntest('object assignment', () => {\n  const data = { one: 1 };\n  data['two'] = 2;\n  expect(data).toEqual({ one: 1, two: 2 });\n});\n```\n\n## 模拟依赖项\n\n有时，您需要模拟依赖项以隔离您正在测试的代码单元。 Jest 提供了 `jest.fn()` 和 `jest.mock()` 等功能来实现此目的。\n\n示例：\n\n```js\n// fetchData.js\nconst fetch = require('node-fetch');\n\nasync function fetchData(url) {\n  const response = await fetch(url);\n  return response.json();\n}\nmodule.exports = fetchData;\n\n// fetchData.test.js\nconst fetchData = require('./fetchData');\nconst fetch = require('node-fetch');\n\njest.mock('node-fetch');\n\ntest('fetches data from API', async () => {\n  const mockResponse = { data: '12345' };\n  fetch.mockResolvedValueOnce({\n    json: async () => mockResponse,\n  });\n\n  const data = await fetchData('https://api.example.com/data');\n  expect(data).toEqual(mockResponse);\n});\n```\n\n## 运行测试\n\n要运行测试，请使用以下命令：\n\n```bash\nnpm test\n```\n\n## 延伸阅读\n\n* [Jest 文档](https://jestjs.io/docs/getting-started)\n* [Mocha 文档](https://mochajs.org/)\n* [Chai 文档](https://www.chaijs.com/)\n* [Sinon 文档](https://sinonjs.org/)\n"
  },
  {
    "path": "questions/how-does-hoisting-affect-function-declarations-and-expressions/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"1854114a\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"4b74c10c\",\n        \"98329d24\",\n        \"2a7816d0\",\n        \"544e6254\",\n        \"85382bd2\",\n        \"35cda8a0\",\n        \"701273a8\",\n        \"474bac8d\",\n        \"7dbb6573\",\n        \"c071fe6a\",\n        \"418e386e\",\n        \"4ed83929\",\n        \"97dedb35\",\n        \"1bc385b3\",\n        \"d1c335e0\",\n        \"20bdd608\",\n        \"1f4770e5\",\n        \"e5beba1e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4b74c10c\",\n        \"98329d24\",\n        \"2a7816d0\",\n        \"544e6254\",\n        \"85382bd2\",\n        \"35cda8a0\",\n        \"701273a8\",\n        \"474bac8d\",\n        \"7dbb6573\",\n        \"c071fe6a\",\n        \"418e386e\",\n        \"4ed83929\",\n        \"97dedb35\",\n        \"1bc385b3\",\n        \"d1c335e0\",\n        \"20bdd608\",\n        \"1f4770e5\",\n        \"e5beba1e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-does-hoisting-affect-function-declarations-and-expressions/en-US.mdx",
    "content": "---\ntitle: How does hoisting affect function declarations and expressions?\n---\n\n## TL;DR\n\nHoisting in JavaScript means that function declarations are moved to the top of their containing scope during the compile phase, making them available throughout the entire scope. This allows you to call a function before it is defined in the code. However, function expressions are not hoisted in the same way. If you try to call a function expression before it is defined, you will get an error because the variable holding the function is hoisted but not its assignment.\n\n```js live\n// Function declaration\nconsole.log(foo()); // Works fine\nfunction foo() {\n  return 'Hello';\n}\n\n// Function expression\nconsole.log(bar()); // Throws TypeError: bar is not a function\nvar bar = function () {\n  return 'Hello';\n};\n```\n\n---\n\n## Hoisting in JavaScript\n\n### Function declarations\n\nFunction declarations are hoisted to the top of their containing scope. This means you can call the function before it is defined in the code.\n\n```js live\nconsole.log(foo()); // Works fine\nfunction foo() {\n  return 'Hello';\n}\n```\n\nIn the example above, the function `foo` is hoisted to the top of its scope, so calling `foo()` before its definition works without any issues.\n\n### Function expressions\n\nFunction expressions, on the other hand, are not hoisted in the same way. The variable that holds the function is hoisted, but its assignment is not. This means that if you try to call a function expression before it is defined, you will get an error.\n\n```js live\nconsole.log(bar()); // Throws TypeError: bar is not a function\nvar bar = function () {\n  return 'Hello';\n};\n```\n\nIn this example, the variable `bar` is hoisted to the top of its scope, but the assignment `function() { return 'Hello'; }` is not. Therefore, calling `bar()` before the assignment results in a `TypeError`.\n\n### Differences between `var`, `let`, and `const`\n\nIt's also important to note the differences in hoisting behavior between `var`, `let`, and `const` when used with function expressions.\n\n- `var`: The variable is hoisted and initialized with `undefined`.\n- `let` and `const`: The variables are hoisted but not initialized, leading to a `ReferenceError` if accessed before initialization.\n\n```js live\nconsole.log(baz); // undefined\nvar baz = function () {\n  return 'Hello';\n};\n\nconsole.log(qux); // ReferenceError: Cannot access 'qux' before initialization\nlet qux = function () {\n  return 'Hello';\n};\n\nconsole.log(quux); // ReferenceError: Cannot access 'quux' before initialization\nconst quux = function () {\n  return 'Hello';\n};\n```\n\n## Further reading\n\n- [MDN Web Docs on Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)\n- [JavaScript.info on Hoisting](https://javascript.info/var#var-hoisting)\n- [MDN Web Docs on Function Declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)\n- [MDN Web Docs on Function Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)\n"
  },
  {
    "path": "questions/how-does-hoisting-affect-function-declarations-and-expressions/metadata.json",
    "content": "{\n  \"slug\": \"how-does-hoisting-affect-function-declarations-and-expressions\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"advanced\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Hoisting\"\n}\n"
  },
  {
    "path": "questions/how-does-hoisting-affect-function-declarations-and-expressions/zh-CN.mdx",
    "content": "---\ntitle: Hoisting 如何影响函数声明和表达式？\n---\n\n## TL;DR\n\nJavaScript 中的 Hoisting 意味着函数声明在编译阶段被移动到其包含作用域的顶部，使其在整个作用域中可用。这允许您在代码中定义函数之前调用它。但是，函数表达式不会以相同的方式被 Hoisting。如果您尝试在定义函数表达式之前调用它，您将收到一个错误，因为保存函数的变量被 Hoisting，但其赋值没有被 Hoisting。\n\n```js live\n// Function declaration\nconsole.log(foo()); // Works fine\nfunction foo() {\n  return 'Hello';\n}\n\n// Function expression\nconsole.log(bar()); // Throws TypeError: bar is not a function\nvar bar = function () {\n  return 'Hello';\n};\n```\n\n***\n\n## JavaScript 中的 Hoisting\n\n### 函数声明\n\n函数声明被 Hoisting 到其包含作用域的顶部。这意味着您可以在代码中定义函数之前调用该函数。\n\n```js live\nconsole.log(foo()); // Works fine\nfunction foo() {\n  return 'Hello';\n}\n```\n\n在上面的例子中，函数 `foo` 被 Hoisting 到其作用域的顶部，因此在定义之前调用 `foo()` 可以正常工作，没有任何问题。\n\n### 函数表达式\n\n另一方面，函数表达式不会以相同的方式被 Hoisting。保存函数的变量被 Hoisting，但其赋值没有被 Hoisting。这意味着如果您尝试在定义函数表达式之前调用它，您将收到一个错误。\n\n```js live\nconsole.log(bar()); // Throws TypeError: bar is not a function\nvar bar = function () {\n  return 'Hello';\n};\n```\n\n在这个例子中，变量 `bar` 被 Hoisting 到其作用域的顶部，但赋值 `function() { return 'Hello'; }` 没有被 Hoisting。因此，在赋值之前调用 `bar()` 会导致 `TypeError`。\n\n### `var`、`let` 和 `const` 之间的区别\n\n在使用函数表达式时，注意 `var`、`let` 和 `const` 之间的 Hoisting 行为差异也很重要。\n\n* `var`：变量被 Hoisting 并使用 `undefined` 初始化。\n* `let` 和 `const`：变量被 Hoisting 但未初始化，如果在初始化之前访问，则会导致 `ReferenceError`。\n\n```js live\nconsole.log(baz); // undefined\nvar baz = function () {\n  return 'Hello';\n};\n\nconsole.log(qux); // ReferenceError: Cannot access 'qux' before initialization\nlet qux = function () {\n  return 'Hello';\n};\n\nconsole.log(quux); // ReferenceError: Cannot access 'quux' before initialization\nconst quux = function () {\n  return 'Hello';\n};\n```\n\n## 延伸阅读\n\n* [MDN Web Docs on Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)\n* [JavaScript.info on Hoisting](https://javascript.info/var#var-hoisting)\n* [MDN Web Docs on Function Declarations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)\n* [MDN Web Docs on Function Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function)\n"
  },
  {
    "path": "questions/how-does-javascript-garbage-collection-work/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"735e9fc7\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"8d1749ee\",\n        \"44dd65df\",\n        \"e78c464\",\n        \"c2a87a44\",\n        \"6647873d\",\n        \"9480ed6\",\n        \"5229a444\",\n        \"eed5a7cb\",\n        \"2a7816d0\",\n        \"f2a2fae9\",\n        \"9cfccc60\",\n        \"18ec17a7\",\n        \"f0a51af9\",\n        \"bc54dce1\",\n        \"e1b5cb38\",\n        \"b7994e6b\",\n        \"9d15fa8d\",\n        \"e7b1f46b\",\n        \"6b187e30\",\n        \"bb85613f\",\n        \"b1fe1532\",\n        \"658d51a2\",\n        \"ad0dfb4f\",\n        \"ff9b461\",\n        \"1053d7b1\",\n        \"46560b3d\",\n        \"323764f2\",\n        \"6a446a16\",\n        \"1f4770e5\",\n        \"f992ea36\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"8d1749ee\",\n        \"44dd65df\",\n        \"e78c464\",\n        \"c2a87a44\",\n        \"6647873d\",\n        \"9480ed6\",\n        \"5229a444\",\n        \"eed5a7cb\",\n        \"2a7816d0\",\n        \"f2a2fae9\",\n        \"9cfccc60\",\n        \"18ec17a7\",\n        \"f0a51af9\",\n        \"bc54dce1\",\n        \"e1b5cb38\",\n        \"b7994e6b\",\n        \"9d15fa8d\",\n        \"e7b1f46b\",\n        \"6b187e30\",\n        \"bb85613f\",\n        \"b1fe1532\",\n        \"658d51a2\",\n        \"ad0dfb4f\",\n        \"ff9b461\",\n        \"1053d7b1\",\n        \"46560b3d\",\n        \"323764f2\",\n        \"6a446a16\",\n        \"1f4770e5\",\n        \"f992ea36\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-does-javascript-garbage-collection-work/en-US.mdx",
    "content": "---\ntitle: How does JavaScript garbage collection work?\n---\n\n## TL;DR\n\nGarbage collection in JavaScript is an automatic memory management mechanism that reclaims memory occupied by objects and variables that are no longer in use by the program. The two most common algorithms are mark-and-sweep and generational garbage collection.\n\n**Mark-and-sweep**\n\nThe most common garbage collection algorithm used in JavaScript is the Mark-and-sweep algorithm. It operates in two phases:\n\n- **Marking phase**: The garbage collector traverses the object graph, starting from the root objects (global variables, currently executing functions, etc.), and marks all reachable objects as \"in-use\".\n- **Sweeping phase**: The garbage collector sweeps through memory, removing all unmarked objects, as they are considered unreachable and no longer needed.\n\nThis algorithm effectively identifies and removes objects that have become unreachable, freeing up memory for new allocations.\n\n**Generational garbage collection**\n\nLeveraged by modern JavaScript engines, objects are divided into different generations based on their age and usage patterns. Frequently accessed objects are moved to younger generations, while less frequently used objects are promoted to older generations. This optimization reduces the overhead of garbage collection by focusing on the younger generations, where most objects are short-lived.\n\nDifferent JavaScript engines (differs according to browsers) implement different garbage collection algorithms and there's no standard way of doing garbage collection.\n\n---\n\n## Garbage collection in JavaScript\n\nGarbage collection in JavaScript is an automatic process managed by the JavaScript engine, designed to reclaim memory occupied by objects that are no longer needed. This helps prevent memory leaks and optimizes the use of available memory. Here's an overview of how garbage collection works in JavaScript:\n\n### Memory management basics\n\nJavaScript allocates memory for objects, arrays, and other variables as they are created. Over time, some of these objects become unreachable because there are no references to them. Garbage collection is the process of identifying these unreachable objects and reclaiming their memory.\n\n### Reachability\n\nThe primary concept in JavaScript garbage collection is reachability. An object is considered reachable if it can be accessed or reached in some way:\n\n- **Global variables**: Objects referenced by global variables are always reachable.\n- **Local variables and function parameters**: These objects are reachable as long as the function is executing.\n- **Closure variables**: Objects referenced by closures are reachable if the closure is reachable.\n- **DOM and other system roots**: Objects referenced by the DOM or other host objects.\n\nIf there is a chain of references from a root to an object, that object is considered reachable.\n\n### Garbage collection algorithms\n\n1. **Mark-and-sweep**:\n   - **Mark Phase**: The garbage collector starts from the root objects and marks all reachable objects.\n   - **Sweep Phase**: It then scans memory for objects that were not marked and reclaims their memory.\n2. **Reference counting**:\n   - This algorithm keeps a count of references to each object. When an object's reference count drops to zero, it is considered unreachable and can be collected.\n   - A drawback of reference counting is that it cannot handle circular references well (e.g., two objects referencing each other but not referenced by any other object).\n3. **Generational garbage collection**:\n   - Memory is divided into generations: young and old.\n   - Objects are initially allocated in the young generation.\n   - Objects that survive multiple collections are promoted to the old generation.\n   - Young generation collections are more frequent and faster, while old generation collections are less frequent but cover more objects.\n\n### JavaScript engine implementations\n\nDifferent JavaScript engines use variations of these algorithms:\n\n- **V8 (Google Chrome, Node.js)**: Uses a combination of generational, mark-and-sweep, and other optimizations for efficient garbage collection.\n- **SpiderMonkey (Mozilla Firefox)**: Uses incremental and generational garbage collection.\n- **JavaScriptCore (Safari)**: Uses a mark-and-sweep algorithm with generational collection.\n\n### Memory leaks\n\nMemory leaks in JavaScript occur when a program fails to release memory that it no longer needs, causing the program to consume more and more memory over time.\n\nMemory leaks in JavaScript can occur due to various reasons, including:\n\n- **Accidental global variables**: Unintentionally creating global variables that remain in memory even after they are no longer needed.\n- **Closures**: Improper use of closures, where an inner function retains references to variables from an outer function's scope, preventing the outer function's scope from being garbage collected.\n- **Event listeners**: Failing to remove event listeners or callbacks when they are no longer needed, causing the associated objects to remain in memory.\n- **Caching**: Implementing caches without proper eviction logic, leading to unbounded memory growth over time.\n- **Detached DOM node references**: Keeping references to detached DOM nodes, preventing them from being garbage collected.\n- **Forgotten timers or callbacks**: Failing to clear timers or callbacks when they are no longer needed, causing their associated data to remain in memory.\n\nTo avoid leaking memory:\n\n- **Remove event listeners**: Always remove event listeners when they are no longer needed.\n- **Clear references in closures**: Avoid holding unnecessary references in closures.\n- **Manage DOM references**: Explicitly remove DOM nodes and their references when they are no longer needed.\n- **Avoid global variables**: Minimize the use of global variables to reduce the risk of inadvertently keeping references alive.\n\n## Further reading\n\n- [Garbage collection - MDN](https://developer.mozilla.org/en-US/docs/Glossary/Garbage_collection)\n- [Memory management](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_management)\n- [Understanding memory management and garbage collection in JavaScript](https://www.linkedin.com/pulse/understanding-memory-management-garbage-collection-aayush-patniya)\n- [JavaScript memory management: A comprehensive guide to garbage collection in JavaScript](https://www.calibraint.com/blog/garbage-collection-in-javascript)\n- [Garbage collection - javascript.info](https://javascript.info/garbage-collection)\n"
  },
  {
    "path": "questions/how-does-javascript-garbage-collection-work/metadata.json",
    "content": "{\n  \"slug\": \"how-does-javascript-garbage-collection-work\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 500,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/how-does-javascript-garbage-collection-work/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 垃圾回收机制是如何工作的？\n---\n\n## TL;DR\n\nJavaScript 中的垃圾回收是一种自动内存管理机制，用于回收程序不再使用的对象和变量所占用的内存。两种最常见的算法是标记-清除和分代垃圾回收。\n\n**标记-清除**\n\nJavaScript 中使用最常见的垃圾回收算法是标记-清除算法。它分两个阶段运行：\n\n* **标记阶段**：垃圾回收器遍历对象图，从根对象（全局变量、当前执行的函数等）开始，将所有可访问的对象标记为“在使用中”。\n* **清除阶段**：垃圾回收器扫描内存，删除所有未标记的对象，因为它们被认为不可访问且不再需要。\n\n该算法有效地识别并删除已变得不可访问的对象，从而为新的分配释放内存。\n\n**分代垃圾回收**\n\n现代 JavaScript 引擎利用了这一点，对象根据其年龄和使用模式被划分为不同的代。经常访问的对象被移动到年轻代，而较少使用的对象被提升到老年代。这种优化通过专注于年轻代（大多数对象寿命短）来减少垃圾回收的开销。\n\n不同的 JavaScript 引擎（根据浏览器而异）实现不同的垃圾回收算法，并且没有标准的垃圾回收方式。\n\n***\n\n## JavaScript 中的垃圾回收\n\nJavaScript 中的垃圾回收是由 JavaScript 引擎管理的自动过程，旨在回收不再需要的对象所占用的内存。这有助于防止内存泄漏并优化可用内存的使用。以下是 JavaScript 中垃圾回收工作原理的概述：\n\n### 内存管理基础\n\nJavaScript 在创建对象、数组和其他变量时为其分配内存。随着时间的推移，其中一些对象变得不可访问，因为没有对它们的引用。垃圾回收是识别这些不可访问的对象并回收其内存的过程。\n\n### 可达性\n\nJavaScript 垃圾回收中的主要概念是可达性。如果一个对象可以通过某种方式访问或到达，则认为它是可达的：\n\n* **全局变量**：全局变量引用的对象始终是可达的。\n* **局部变量和函数参数**：只要函数正在执行，这些对象就是可达的。\n* **闭包变量**：如果闭包是可达的，则闭包引用的对象是可达的。\n* **DOM 和其他系统根**：DOM 或其他宿主对象引用的对象。\n\n如果从根到对象存在引用链，则该对象被认为是可达的。\n\n### 垃圾回收算法\n\n1. **标记和清除**：\n   * **标记阶段**：垃圾收集器从根对象开始，标记所有可访问的对象。\n   * **清除阶段**：然后扫描内存，查找未被标记的对象，并回收它们的内存。\n2. **引用计数**：\n   * 此算法保留对每个对象的引用计数。当对象的引用计数降为零时，它被认为不可访问，可以被收集。\n   * 引用计数的缺点是它不能很好地处理循环引用（例如，两个对象相互引用，但没有被任何其他对象引用）。\n3. **分代垃圾回收**：\n   * 内存被划分为几代：年轻代和老年代。\n   * 对象最初分配在年轻代中。\n   * 存活了多次收集的对象被提升到老年代。\n   * 年轻代收集更频繁且更快，而老年代收集不太频繁，但涵盖更多对象。\n\n### JavaScript 引擎实现\n\n不同的 JavaScript 引擎使用这些算法的变体：\n\n* **V8 (Google Chrome, Node.js)**：使用分代、标记和清除以及其他优化来高效地进行垃圾回收。\n* **SpiderMonkey (Mozilla Firefox)**：使用增量和分代垃圾回收。\n* **JavaScriptCore (Safari)**：使用带有分代收集的标记和清除算法。\n\n### 内存泄漏\n\n当程序未能释放它不再需要的内存时，JavaScript 中就会发生内存泄漏，导致程序随着时间的推移消耗越来越多的内存。\n\nJavaScript 中的内存泄漏可能由于各种原因而发生，包括：\n\n* **意外的全局变量**：无意中创建全局变量，即使不再需要它们，这些变量仍然保留在内存中。\n* **闭包**：不正确地使用闭包，其中内部函数保留对来自外部函数作用域的变量的引用，阻止外部函数的作用域被垃圾回收。\n* **事件监听器**：当不再需要事件监听器或回调时，未能删除它们，导致相关对象保留在内存中。\n* **缓存**：实现缓存时没有适当的逐出逻辑，导致随着时间的推移内存无界增长。\n* **分离的 DOM 节点引用**：保留对分离的 DOM 节点的引用，阻止它们被垃圾回收。\n* **被遗忘的计时器或回调**：未能清除计时器或回调，导致它们的相关数据保留在内存中。\n\n为了避免内存泄漏：\n\n* **删除事件监听器**：当不再需要事件监听器时，始终删除它们。\n* **清除闭包中的引用**：避免在闭包中保留不必要的引用。\n* **管理 DOM 引用**：当不再需要 DOM 节点及其引用时，显式删除它们。\n* **避免全局变量**：尽量减少全局变量的使用，以降低无意中保持引用存活的风险。\n\n## 延伸阅读\n\n* [垃圾回收 - MDN](https://developer.mozilla.org/en-US/docs/Glossary/Garbage_collection)\n* [内存管理](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_management)\n* [了解 JavaScript 中的内存管理和垃圾回收](https://www.linkedin.com/pulse/understanding-memory-management-garbage-collection-aayush-patniya)\n* [JavaScript 内存管理：JavaScript 中垃圾回收的综合指南](https://www.calibraint.com/blog/garbage-collection-in-javascript)\n* [垃圾回收 - javascript.info](https://javascript.info/garbage-collection)\n"
  },
  {
    "path": "questions/how-is-promiseall-different-from-promiseallsettled/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"319260d3\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"5ba8509b\",\n        \"2a7816d0\",\n        \"4127c26d\",\n        \"af87d03a\",\n        \"d87546bb\",\n        \"748ffe75\",\n        \"81572b5b\",\n        \"9ba2ed32\",\n        \"b994d932\",\n        \"a5a4bb9f\",\n        \"e09c448\",\n        \"d11e620b\",\n        \"39160a6e\",\n        \"748ffe75\",\n        \"3fa9f5c4\",\n        \"695d3549\",\n        \"b994d932\",\n        \"31150e98\",\n        \"da9329f\",\n        \"1f4770e5\",\n        \"76963f99\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"5ba8509b\",\n        \"2a7816d0\",\n        \"4127c26d\",\n        \"af87d03a\",\n        \"d87546bb\",\n        \"748ffe75\",\n        \"81572b5b\",\n        \"9ba2ed32\",\n        \"b994d932\",\n        \"a5a4bb9f\",\n        \"e09c448\",\n        \"d11e620b\",\n        \"39160a6e\",\n        \"748ffe75\",\n        \"3fa9f5c4\",\n        \"695d3549\",\n        \"b994d932\",\n        \"31150e98\",\n        \"da9329f\",\n        \"1f4770e5\",\n        \"76963f99\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/how-is-promiseall-different-from-promiseallsettled/en-US.mdx",
    "content": "---\ntitle: How is `Promise.all()` different from `Promise.allSettled()`?\n---\n\n## TL;DR\n\n`Promise.all()` and `Promise.allSettled()` are both methods for handling multiple promises in JavaScript, but they behave differently. `Promise.all()` waits for all promises to resolve and fails fast if any promise rejects, returning a single rejected promise. `Promise.allSettled()`, on the other hand, waits for all promises to settle (either resolve or reject) and returns an array of objects describing the outcome of each promise.\n\n---\n\n## How is `Promise.all()` different from `Promise.allSettled()`?\n\n### `Promise.all()`\n\n`Promise.all()` takes an iterable of promises and returns a single promise that resolves when all of the input promises have resolved. If any of the input promises reject, the returned promise immediately rejects with the reason of the first promise that rejected.\n\n#### Example\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = 42;\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.all([promise1, promise2, promise3])\n  .then((values) => {\n    console.log(values); // [3, 42, 'foo']\n  })\n  .catch((error) => {\n    console.error(error);\n  });\n```\n\nIn this example, `Promise.all()` resolves with an array of results `[3, 42, 'foo']` because all promises resolve successfully.\n\n#### Failure case\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = Promise.reject('error');\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.all([promise1, promise2, promise3])\n  .then((values) => {\n    console.log(values);\n  })\n  .catch((error) => {\n    console.error(error); // 'error'\n  });\n```\n\nIn this example, `Promise.all()` rejects immediately with the reason `'error'` because `promise2` rejects.\n\n### `Promise.allSettled()`\n\n`Promise.allSettled()` takes an iterable of promises and returns a single promise that resolves when all of the input promises have settled (either resolved or rejected). The returned promise resolves with an array of objects that each describe the outcome of each promise.\n\n#### Example\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = 42;\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.allSettled([promise1, promise2, promise3]).then((results) => {\n  results.forEach((result) => console.log(result));\n  // { status: 'fulfilled', value: 3 }\n  // { status: 'fulfilled', value: 42 }\n  // { status: 'fulfilled', value: 'foo' }\n});\n```\n\nIn this example, `Promise.allSettled()` resolves with an array of result objects, each indicating the status and value of the promises.\n\n#### Failure case\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = Promise.reject('error');\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.allSettled([promise1, promise2, promise3]).then((results) => {\n  results.forEach((result) => console.log(result));\n  // { status: 'fulfilled', value: 3 }\n  // { status: 'rejected', reason: 'error' }\n  // { status: 'fulfilled', value: 'foo' }\n});\n```\n\nIn this example, `Promise.allSettled()` resolves with an array of result objects, including the rejected promise with its reason.\n\n## Further reading\n\n- [MDN Web Docs: Promise.all()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)\n- [MDN Web Docs: Promise.allSettled()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled)\n- [JavaScript.info: Promise API](https://javascript.info/promise-api)\n"
  },
  {
    "path": "questions/how-is-promiseall-different-from-promiseallsettled/metadata.json",
    "content": "{\n  \"slug\": \"how-is-promiseall-different-from-promiseallsettled\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"async\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Asynchronous JavaScript\"\n}\n"
  },
  {
    "path": "questions/how-is-promiseall-different-from-promiseallsettled/zh-CN.mdx",
    "content": "---\ntitle: Promise.all() 与 Promise.allSettled() 有什么区别？\n---\n\n## TL;DR\n\nPromise.all() 和 Promise.allSettled() 都是用于处理 JavaScript 中多个 Promise 的方法，但它们的行为有所不同。Promise.all() 等待所有 Promise 都被解决，如果任何一个 Promise 被拒绝，它会快速失败，返回一个被拒绝的 Promise。另一方面，Promise.allSettled() 等待所有 Promise 都被确定（解决或拒绝），并返回一个描述每个 Promise 结果的对象数组。\n\n***\n\n## Promise.all() 与 Promise.allSettled() 有什么区别？\n\n### Promise.all()\n\nPromise.all() 接受一个可迭代的 Promise，并返回一个 Promise，当所有输入的 Promise 都已解决时，该 Promise 将被解决。如果任何一个输入的 Promise 被拒绝，则返回的 Promise 会立即被拒绝，并带有第一个被拒绝的 Promise 的原因。\n\n#### 示例\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = 42;\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.all([promise1, promise2, promise3])\n  .then((values) => {\n    console.log(values); // [3, 42, 'foo']\n  })\n  .catch((error) => {\n    console.error(error);\n  });\n```\n\n在此示例中，Promise.all() 使用结果数组 `[3, 42, 'foo']` 进行解析，因为所有 Promise 都成功解析。\n\n#### 失败情况\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = Promise.reject('error');\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.all([promise1, promise2, promise3])\n  .then((values) => {\n    console.log(values);\n  })\n  .catch((error) => {\n    console.error(error); // 'error'\n  });\n```\n\n在此示例中，Promise.all() 立即拒绝，原因是 `'error'`，因为 `promise2` 被拒绝。\n\n### Promise.allSettled()\n\nPromise.allSettled() 接受一个可迭代的 Promise，并返回一个 Promise，当所有输入的 Promise 都已确定（已解决或已拒绝）时，该 Promise 将被解决。返回的 Promise 使用一个对象数组进行解析，每个对象描述每个 Promise 的结果。\n\n#### 示例\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = 42;\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.allSettled([promise1, promise2, promise3]).then((results) => {\n  results.forEach((result) => console.log(result));\n  // { status: 'fulfilled', value: 3 }\n  // { status: 'fulfilled', value: 42 }\n  // { status: 'fulfilled', value: 'foo' }\n});\n```\n\n在此示例中，Promise.allSettled() 使用结果对象数组进行解析，每个对象指示 Promise 的状态和值。\n\n#### 失败情况\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = Promise.reject('error');\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.allSettled([promise1, promise2, promise3]).then((results) => {\n  results.forEach((result) => console.log(result));\n  // { status: 'fulfilled', value: 3 }\n  // { status: 'rejected', reason: 'error' }\n  // { status: 'fulfilled', value: 'foo' }\n});\n```\n\n在此示例中，Promise.allSettled() 使用结果对象数组进行解析，包括被拒绝的 Promise 及其原因。\n\n## 延伸阅读\n\n* [MDN Web 文档：Promise.all()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)\n* [MDN Web 文档：Promise.allSettled()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled)\n* [JavaScript.info：Promise API](https://zh.javascript.info/promise-api)\n"
  },
  {
    "path": "questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"d4e3c085\",\n        \"ce69f685\",\n        \"db49f614\",\n        \"6e03c893\",\n        \"43645c83\",\n        \"2a7816d0\",\n        \"aba50af\",\n        \"1743fc64\",\n        \"dd75fb51\",\n        \"748ffe75\",\n        \"51a33446\",\n        \"5fd903ca\",\n        \"7caa40d3\",\n        \"748ffe75\",\n        \"cdda9b48\",\n        \"1f4770e5\",\n        \"f1e51291\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d4e3c085\",\n        \"ce69f685\",\n        \"db49f614\",\n        \"6e03c893\",\n        \"43645c83\",\n        \"2a7816d0\",\n        \"aba50af\",\n        \"1743fc64\",\n        \"dd75fb51\",\n        \"748ffe75\",\n        \"51a33446\",\n        \"5fd903ca\",\n        \"7caa40d3\",\n        \"748ffe75\",\n        \"cdda9b48\",\n        \"1f4770e5\",\n        \"f1e51291\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"47d101a3\"\n  }\n}\n"
  },
  {
    "path": "questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used/en-US.mdx",
    "content": "---\ntitle: Provide some examples of how currying and partial application can be used\n---\n\n## TL;DR\n\nCurrying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. Partial application fixes a few arguments of a function, producing another function with a smaller number of arguments. For example, currying a function `add(a, b)` would look like `add(a)(b)`, while partial application of `add(2, b)` would fix the first argument to 2, resulting in a function that only needs the second argument.\n\nCurrying example:\n\n```js live\nconst add = (a) => (b) => a + b;\nconst addTwo = add(2);\nconsole.log(addTwo(3)); // 5\n```\n\nPartial application example:\n\n```js live\nconst add = (a, b) => a + b;\nconst addTwo = add.bind(null, 2);\nconsole.log(addTwo(3)); // 5\n```\n\n---\n\n## Currying and partial application\n\n### Currying\n\nCurrying is a technique where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument. This allows for more flexible function composition and reuse.\n\n#### Example\n\n```js live\n// Consider a simple function that adds two numbers:\nfunction add(a, b) {\n  return a + b;\n}\n\n// To curry this function, we transform it into a series of functions,\n// each taking one argument:\nconst curriedAdd = (a) => (b) => a + b;\n\n// Now, you can use the curried function like this:\nconst addTwo = curriedAdd(2);\nconsole.log(addTwo(3)); // 5\n```\n\n### Partial application\n\nPartial application is a technique where you fix a few arguments of a function, producing another function with a smaller number of arguments. This is useful for creating specialized functions from more general ones.\n\n#### Example\n\n```js live\n// Consider the same add function:\nfunction add(a, b) {\n  return a + b;\n}\n\n// To partially apply this function\n// you can use the `bind` method to fix the first argument:\nconst addTwo = add.bind(null, 2);\nconsole.log(addTwo(3)); // 5\n\n// Alternatively, you can create a custom partial application function:\nfunction partial(fn, ...fixedArgs) {\n  return function (...remainingArgs) {\n    return fn(...fixedArgs, ...remainingArgs);\n  };\n}\n\nconst addTwoCustom = partial(add, 2);\nconsole.log(addTwoCustom(3)); // 5\n```\n\n## Further reading\n\n- [Javascript.info: Currying](https://javascript.info/currying-partials)\n- [Functional programming in JavaScript](https://eloquentjavascript.net/1st_edition/chapter6.html)\n"
  },
  {
    "path": "questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used/metadata.json",
    "content": "{\n  \"slug\": \"provide-some-examples-of-how-currying-and-partial-application-can-be-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"closure\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Currying & Partial Application\"\n}\n"
  },
  {
    "path": "questions/provide-some-examples-of-how-currying-and-partial-application-can-be-used/zh-CN.mdx",
    "content": "---\ntitle: 提供一些关于如何使用柯里化和部分应用的例子\n---\n\n## TL;DR\n\n柯里化将具有多个参数的函数转换为一系列函数，每个函数只接受一个参数。部分应用会固定函数的一些参数，生成另一个参数较少的函数。例如，柯里化函数 `add(a, b)` 看起来像 `add(a)(b)`，而部分应用 `add(2, b)` 会将第一个参数固定为 2，从而产生一个只需要第二个参数的函数。\n\n柯里化示例：\n\n```js live\nconst add = (a) => (b) => a + b;\nconst addTwo = add(2);\nconsole.log(addTwo(3)); // 5\n```\n\n部分应用示例：\n\n```js live\nconst add = (a, b) => a + b;\nconst addTwo = add.bind(null, 2);\nconsole.log(addTwo(3)); // 5\n```\n\n***\n\n## 柯里化和部分应用\n\n### 柯里化\n\n柯里化是一种将具有多个参数的函数转换为一系列函数的技术，每个函数只接受一个参数。这允许更灵活的函数组合和重用。\n\n#### 示例\n\n```js live\n// 考虑一个简单的加法函数：\nfunction add(a, b) {\n  return a + b;\n}\n\n// 要柯里化这个函数，我们将其转换为一系列函数，\n// 每个函数接受一个参数：\nconst curriedAdd = (a) => (b) => a + b;\n\n// 现在，你可以这样使用柯里化函数：\nconst addTwo = curriedAdd(2);\nconsole.log(addTwo(3)); // 5\n```\n\n### 部分应用\n\n部分应用是一种技术，你可以在其中固定函数的一些参数，从而生成另一个参数较少的函数。这对于从更通用的函数创建专门的函数很有用。\n\n#### 示例\n\n```js live\n// 考虑相同的 add 函数：\nfunction add(a, b) {\n  return a + b;\n}\n\n// 要部分应用此函数\n// 你可以使用 `bind` 方法来固定第一个参数：\nconst addTwo = add.bind(null, 2);\nconsole.log(addTwo(3)); // 5\n\n// 或者，你可以创建一个自定义的部分应用函数：\nfunction partial(fn, ...fixedArgs) {\n  return function (...remainingArgs) {\n    return fn(...fixedArgs, ...remainingArgs);\n  };\n}\n\nconst addTwoCustom = partial(add, 2);\nconsole.log(addTwoCustom(3)); // 5\n```\n\n## 延伸阅读\n\n* [Javascript.info: Currying](https://javascript.info/currying-partials)\n* [Functional programming in JavaScript](https://eloquentjavascript.net/1st_edition/chapter6.html)\n"
  },
  {
    "path": "questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"5864e0e9\",\n        \"bca760b0\",\n        \"ca098495\",\n        \"49ed6e0d\",\n        \"2a7816d0\",\n        \"fb9680c5\",\n        \"24ad4448\",\n        \"eea083fa\",\n        \"a3fdeea5\",\n        \"157fa572\",\n        \"fcdd0db7\",\n        \"a9b3b659\",\n        \"70e92007\",\n        \"29881730\",\n        \"852195c\",\n        \"e120ec\",\n        \"5fedbc8e\",\n        \"76335194\",\n        \"647094ae\",\n        \"96179f4f\",\n        \"3f88c3b\",\n        \"bff90e2\",\n        \"e8e1d7c5\",\n        \"d5d43694\",\n        \"65526585\",\n        \"66224a2\",\n        \"ca098495\",\n        \"49991086\",\n        \"9684ec1b\",\n        \"60c84d23\",\n        \"1f4770e5\",\n        \"260bdb8f\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"5864e0e9\",\n        \"bca760b0\",\n        \"ca098495\",\n        \"49ed6e0d\",\n        \"2a7816d0\",\n        \"fb9680c5\",\n        \"24ad4448\",\n        \"eea083fa\",\n        \"a3fdeea5\",\n        \"157fa572\",\n        \"fcdd0db7\",\n        \"a9b3b659\",\n        \"70e92007\",\n        \"29881730\",\n        \"852195c\",\n        \"e120ec\",\n        \"5fedbc8e\",\n        \"76335194\",\n        \"647094ae\",\n        \"96179f4f\",\n        \"3f88c3b\",\n        \"bff90e2\",\n        \"e8e1d7c5\",\n        \"d5d43694\",\n        \"65526585\",\n        \"66224a2\",\n        \"ca098495\",\n        \"49991086\",\n        \"9684ec1b\",\n        \"60c84d23\",\n        \"1f4770e5\",\n        \"260bdb8f\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"963f6d50\"\n  }\n}\n"
  },
  {
    "path": "questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/en-US.mdx",
    "content": "---\ntitle: What advantage is there for using the JavaScript arrow syntax for a method in a constructor?\n---\n\n## TL;DR\n\nThe main advantage of using an arrow function as a method inside a constructor is that the value of `this` gets set at the time of the function creation and can't change after that. When the constructor is used to create a new object, `this` will always refer to that object.\n\nFor example, let's say we have a `Person` constructor that takes a first name as an argument has two methods to `console.log()` that name, one as a regular function and one as an arrow function:\n\n```js live\nconst Person = function (name) {\n  this.firstName = name;\n  this.sayName1 = function () {\n    console.log(this.firstName);\n  };\n  this.sayName2 = () => {\n    console.log(this.firstName);\n  };\n};\n\nconst john = new Person('John');\nconst dave = new Person('Dave');\n\njohn.sayName1(); // John\njohn.sayName2(); // John\n\n// The regular function can have its `this` value changed, but the arrow function cannot\njohn.sayName1.call(dave); // Dave (because `this` is now the dave object)\njohn.sayName2.call(dave); // John\n\njohn.sayName1.apply(dave); // Dave (because `this` is now the dave object)\njohn.sayName2.apply(dave); // John\n\njohn.sayName1.bind(dave)(); // Dave (because `this` is now the dave object)\njohn.sayName2.bind(dave)(); // John\n\nconst sayNameFromWindow1 = john.sayName1;\nsayNameFromWindow1(); // undefined (because `this` is now the window object)\n\nconst sayNameFromWindow2 = john.sayName2;\nsayNameFromWindow2(); // John\n```\n\nThe main takeaway here is that `this` can be changed for a normal function, but `this` always stays the same for an arrow function. So even if you are passing around your arrow function to different parts of your application, you wouldn't have to worry about the value of `this` changing.\n\n---\n\n## Arrow functions\n\nArrow functions are introduced in ES2015 and it provides a concise way to write functions in Javascript. One of the key features of arrow function is that it lexically bind the `this` value, which means that it takes the `this` value from enclosing scope.\n\n### Syntax\n\nArrow functions use the `=>` syntax instead of the function keyword. The basic syntax is:\n\n```js\nconst myFunction = (arg1, arg2, ...argN) => {\n  // function body\n};\n```\n\nIf the function body has only one expression, you can omit the curly braces and the return keyword:\n\n```js\nconst myFunction = (arg1, arg2, ...argN) => expression;\n```\n\n### Examples\n\n```js live\n// Arrow function with parameters\nconst multiply = (x, y) => x * y;\nconsole.log(multiply(2, 3)); // Output: 6\n\n// Arrow function with no parameters\nconst sayHello = () => 'Hello, World!';\nconsole.log(sayHello()); // Output: 'Hello, World!'\n```\n\n### Advantages\n\n- **Concise**: Arrow functions provide a more concise syntax, especially for short functions.\n- **Implicit return**: They have an implicit return for single-line functions.\n- **Value of `this` is predictable**: Arrow functions lexically bind the `this` value, inheriting it from the enclosing scope.\n\n### Limitations\n\nArrow functions cannot be used as constructors and will throw an error when used with the `new` keyword.\n\n```js live\nconst Foo = () => {};\nconst foo = new Foo(); // TypeError: Foo is not a constructor\n```\n\nThey also do not have `arguments` keyword; the arguments have to be obtained from using the rest operator (`...`) in the arguments.\n\n```js live\nconst arrowFunction = (...args) => {\n  console.log(arguments); // Throws a ReferenceError\n  console.log(args); // [1, 2, 3]\n};\n\narrowFunction(1, 2, 3);\n```\n\nSince arrow functions do not have their own `this`, they are not suitable for defining methods in an object. Traditional function expressions or function declarations should be used instead.\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: () => this.value, // `this` does not refer to `obj`\n};\n\nconsole.log(obj.getValue()); // undefined\n```\n\n## Why arrow functions are useful\n\nOne of the most notable features of arrow functions is their behavior with `this`. Unlike regular functions, arrow functions do not have their own `this`. Instead, they inherit `this` from the parent scope at the time they are defined. This makes arrow functions particularly useful for scenarios like event handlers, callbacks, and methods in classes.\n\n### Arrow functions inside function constructors\n\n```js live\nconst Person = function (name) {\n  this.firstName = name;\n  this.sayName1 = function () {\n    console.log(this.firstName);\n  };\n  this.sayName2 = () => {\n    console.log(this.firstName);\n  };\n};\n\nconst john = new Person('John');\nconst dave = new Person('Dave');\n\njohn.sayName1(); // John\njohn.sayName2(); // John\n\n// The regular function can have its `this` value changed, but the arrow function cannot\njohn.sayName1.call(dave); // Dave (because `this` is now the dave object)\njohn.sayName2.call(dave); // John\n\njohn.sayName1.apply(dave); // Dave (because `this` is now the dave object)\njohn.sayName2.apply(dave); // John\n\njohn.sayName1.bind(dave)(); // Dave (because `this` is now the dave object)\njohn.sayName2.bind(dave)(); // John\n\nconst sayNameFromWindow1 = john.sayName1;\nsayNameFromWindow1(); // undefined (because `this` is now the window object)\n\nconst sayNameFromWindow2 = john.sayName2;\nsayNameFromWindow2(); // John\n```\n\n### Arrow functions in event handlers\n\n```js\nconst button = document.getElementById('myButton');\n\nbutton.addEventListener('click', function () {\n  console.log(this); // Output: Button\n  console.log(this === button); // Output: true\n});\n\nbutton.addEventListener('click', () => {\n  console.log(this); // Output: Window\n  console.log(this === window); // Output: true\n});\n```\n\nThis can be particularly helpful in React class components. If you define a class method for something such as a click handler using a normal function, and then you pass that click handler down into a child component as a prop, you will need to also bind `this` in the constructor of the parent component. If you instead use an arrow function, there is no need to bind `this`, as the method will automatically get its `this` value from its enclosing lexical context. See this [article](https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-ede88184bbb) for an excellent demonstration and sample code.\n\n## Further reading\n\n- [Arrow function expressions - MDN ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\n- [How to Use JavaScript Arrow Functions – Explained in Detail](https://www.freecodecamp.org/news/javascript-arrow-functions-in-depth/)\n"
  },
  {
    "path": "questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/metadata.json",
    "content": "{\n  \"slug\": \"what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 120,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/pt-BR.mdx",
    "content": "---\ntitle: Qual é a vantagem de usar a sintaxe de seta para um método em um constructor?\n---\n\nA principal vantagem de usar uma arrow function como um método dentro de um construtor é que o valor de `this` é definido no momento da criação da função e não pode mudar depois disso. Então, quando o construtor é usado para criar um novo objeto, `this` sempre irá referir-se ao objeto. Por exemplo, digamos que temos um construtor `Person` que toma o primeiro nome como um argumento tem dois métodos para dar um `console.log` nesse nome, um como uma função normal e um como uma função de seta:\n\n```js\nconst Person = function (firstName) {\n  this.firstName = firstName;\n  this.sayName1 = function () {\n    console.log(this.firstName);\n  };\n  this.sayName2 = () => {\n    console.log(this.firstName);\n  };\n};\n\nconst john = new Person('John');\nconst dave = new Person('Dave');\n\njohn.sayName1(); // John\njohn.sayName2(); // John\n\n// A função regular pode ter seu valor 'this' alterado, mas a arrow function não pode\njohn.sayName1.call(dave); // Dave (porque \"this\" é agora o objeto dave)\njohn.sayName2.call(dave); // John\n\njohn.sayName1.apply(dave); // Dave (porque 'this' é agora o objeto dave)\njohn.sayName2.apply(dave); // João\n\njohn.sayName1.bind(dave)(); // Dave (porque 'this' é agora o dave object)\njohn.sayName2.bind(dave)(); // João\n\nvar sayNameFromWindow1 = john.sayName1;\nsayNameFromWindow1(); // undefined (porque 'this' agora é o objeto da window)\n\nvar sayNameFromWindow2 = john.sayName2;\nsayNameFromWindow2(); // John\n```\n\nO principal tirada aqui é que `this` pode ser alterado para uma função normal, mas o contexto sempre permanece o mesmo para uma arrow function. Então, mesmo que você esteja passando pela arrow function para diferentes partes do seu aplicativo, você não precisaria se preocupar com a mudança de contexto.\n\nIsso pode ser particularmente útil em componentes de classe React. Se você definir um método de classe para algo como um manipulador de cliques usando uma função normal, e, em seguida, você passa que clica manipulando em um componente filho como uma propriedade, você também precisará vincular o `this` no construtor do componente pai. Se você ao invés disso usar uma arrow function, não há necessidade de vincular também \"this\", como o método irá automaticamente obter seu valor \"this\" no contexto léxico que está encapsulado. (Veja esse artigo para uma excelente demonstração e código de amostra: https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-ede88184bbb)\n"
  },
  {
    "path": "questions/what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor/zh-CN.mdx",
    "content": "---\ntitle: 在构造函数中使用 JavaScript 箭头语法作为方法有什么优势？\n---\n\n## TL;DR\n\n在构造函数中使用箭头函数作为方法的主要优点是 `this` 的值在函数创建时设置，之后无法更改。当构造函数用于创建新对象时，`this` 将始终引用该对象。\n\n例如，假设我们有一个 `Person` 构造函数，它接受一个名字作为参数，并有两个方法来 `console.log()` 该名称，一个作为常规函数，一个作为箭头函数：\n\n```js live\nconst Person = function (name) {\n  this.firstName = name;\n  this.sayName1 = function () {\n    console.log(this.firstName);\n  };\n  this.sayName2 = () => {\n    console.log(this.firstName);\n  };\n};\n\nconst john = new Person('John');\nconst dave = new Person('Dave');\n\njohn.sayName1(); // John\njohn.sayName2(); // John\n\n// 常规函数可以更改其 `this` 值，但箭头函数不能\njohn.sayName1.call(dave); // Dave (因为 `this` 现在是 dave 对象)\njohn.sayName2.call(dave); // John\n\njohn.sayName1.apply(dave); // Dave (因为 `this` 现在是 dave 对象)\njohn.sayName2.apply(dave); // John\n\njohn.sayName1.bind(dave)(); // Dave (因为 `this` 现在是 dave 对象)\njohn.sayName2.bind(dave)(); // John\n\nconst sayNameFromWindow1 = john.sayName1;\nsayNameFromWindow1(); // undefined (因为 `this` 现在是 window 对象)\n\nconst sayNameFromWindow2 = john.sayName2;\nsayNameFromWindow2(); // John\n```\n\n这里的主要结论是，`this` 可以为普通函数更改，但 `this` 对于箭头函数始终保持不变。因此，即使您将箭头函数传递到应用程序的不同部分，您也不必担心 `this` 的值发生变化。\n\n***\n\n## 箭头函数\n\n箭头函数是在 ES2015 中引入的，它提供了一种用 Javascript 编写函数的简洁方式。箭头函数的一个关键特性是它在词法上绑定了 `this` 值，这意味着它从封闭范围获取 `this` 值。\n\n### 语法\n\n箭头函数使用 `=>` 语法代替 function 关键字。基本语法是：\n\n```js\nconst myFunction = (arg1, arg2, ...argN) => {\n  // function body\n};\n```\n\n如果函数体只有一个表达式，则可以省略大括号和 return 关键字：\n\n```js\nconst myFunction = (arg1, arg2, ...argN) => expression;\n```\n\n### 例子\n\n```js live\n// 带有参数的箭头函数\nconst multiply = (x, y) => x * y;\nconsole.log(multiply(2, 3)); // 输出：6\n\n// 没有参数的箭头函数\nconst sayHello = () => 'Hello, World!';\nconsole.log(sayHello()); // 输出：'Hello, World!'\n```\n\n### 优点\n\n* **简洁**: 箭头函数提供更简洁的语法，尤其适用于短函数。\n* **隐式返回**: 它们对单行函数具有隐式返回。\n* **`this` 的值是可预测的**: 箭头函数在词法上绑定 `this` 值，从封闭范围继承它。\n\n### 局限性\n\n箭头函数不能用作构造函数，并且与 `new` 关键字一起使用时会抛出错误。\n\n```js live\nconst Foo = () => {};\nconst foo = new Foo(); // TypeError: Foo is not a constructor\n```\n\n它们也没有 `arguments` 关键字；参数必须通过在参数中使用 rest 运算符 (`...`) 来获取。\n\n```js live\nconst arrowFunction = (...args) => {\n  console.log(arguments); // Throws a ReferenceError\n  console.log(args); // [1, 2, 3]\n};\n\narrowFunction(1, 2, 3);\n```\n\n由于箭头函数没有自己的 `this`，因此它们不适合在对象中定义方法。 应该使用传统的函数表达式或函数声明。\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: () => this.value, // `this` does not refer to `obj`\n};\n\nconsole.log(obj.getValue()); // undefined\n```\n\n## 为什么箭头函数有用\n\n箭头函数最显著的特征之一是它们与 `this` 的行为。与常规函数不同，箭头函数没有自己的 `this`。相反，它们在定义时从父作用域继承 `this`。这使得箭头函数特别适用于事件处理程序、回调和类中的方法等场景。\n\n### 函数构造函数中的箭头函数\n\n```js live\nconst Person = function (name) {\n  this.firstName = name;\n  this.sayName1 = function () {\n    console.log(this.firstName);\n  };\n  this.sayName2 = () => {\n    console.log(this.firstName);\n  };\n};\n\nconst john = new Person('John');\nconst dave = new Person('Dave');\n\njohn.sayName1(); // John\njohn.sayName2(); // John\n\n// 常规函数可以更改其 `this` 值，但箭头函数不能\njohn.sayName1.call(dave); // Dave (因为 `this` 现在是 dave 对象)\njohn.sayName2.call(dave); // John\n\njohn.sayName1.apply(dave); // Dave (因为 `this` 现在是 dave 对象)\njohn.sayName2.apply(dave); // John\n\njohn.sayName1.bind(dave)(); // Dave (因为 `this` 现在是 dave 对象)\njohn.sayName2.bind(dave)(); // John\n\nconst sayNameFromWindow1 = john.sayName1;\nsayNameFromWindow1(); // undefined (因为 `this` 现在是 window 对象)\n\nconst sayNameFromWindow2 = john.sayName2;\nsayNameFromWindow2(); // John\n```\n\n### 箭头函数在事件处理程序中\n\n```js\nconst button = document.getElementById('myButton');\n\nbutton.addEventListener('click', function () {\n  console.log(this); // Output: Button\n  console.log(this === button); // Output: true\n});\n\nbutton.addEventListener('click', () => {\n  console.log(this); // Output: Window\n  console.log(this === window); // Output: true\n});\n```\n\n这在 React 类组件中特别有用。 如果您使用普通函数定义一个类方法，例如单击处理程序，然后将该单击处理程序作为 prop 传递到子组件中，则还需要在父组件的构造函数中绑定 `this`。 如果您改为使用箭头函数，则无需绑定 `this`，因为该方法将自动从其封闭的词法上下文中获取其 `this` 值。 请参阅此 [文章](https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-ede88184bbb) 以获得出色的演示和示例代码。\n\n## 延伸阅读\n\n* [箭头函数表达式 - MDN ](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions)\n* [如何详细使用 JavaScript 箭头函数](https://www.freecodecamp.org/news/javascript-arrow-functions-in-depth/)\n"
  },
  {
    "path": "questions/what-are-callback-functions-and-how-are-they-used/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"d46d6047\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"78eadda8\",\n        \"8653c591\",\n        \"2a7816d0\",\n        \"f83af0df\",\n        \"25841bc3\",\n        \"72f4814c\",\n        \"63d1c073\",\n        \"b189f427\",\n        \"fc625159\",\n        \"316805a1\",\n        \"efc618b4\",\n        \"6d0fe492\",\n        \"9912c3a1\",\n        \"714a1b2d\",\n        \"4d9f1ec5\",\n        \"2d911d61\",\n        \"81e8fbc\",\n        \"fd95ec65\",\n        \"73a218d6\",\n        \"2b67e4ce\",\n        \"d72c4cfb\",\n        \"bc60df2b\",\n        \"1f4770e5\",\n        \"c2097a39\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"78eadda8\",\n        \"8653c591\",\n        \"2a7816d0\",\n        \"f83af0df\",\n        \"25841bc3\",\n        \"72f4814c\",\n        \"63d1c073\",\n        \"b189f427\",\n        \"fc625159\",\n        \"316805a1\",\n        \"efc618b4\",\n        \"6d0fe492\",\n        \"9912c3a1\",\n        \"714a1b2d\",\n        \"4d9f1ec5\",\n        \"2d911d61\",\n        \"81e8fbc\",\n        \"fd95ec65\",\n        \"73a218d6\",\n        \"2b67e4ce\",\n        \"d72c4cfb\",\n        \"bc60df2b\",\n        \"1f4770e5\",\n        \"c2097a39\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-callback-functions-and-how-are-they-used/en-US.mdx",
    "content": "---\ntitle: What are callback functions and how are they used?\n---\n\n## TL;DR\n\nA callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. They are commonly used for asynchronous operations like handling events, making API calls, or reading files. For example:\n\n```js live\nfunction fetchData(callback) {\n  // assume an asynchronous operation to fetch data\n  const data = { name: 'John Doe' };\n  callback(data);\n}\n\nfunction handleData(data) {\n  console.log(data);\n}\n\nfetchData(handleData);\n```\n\n---\n\n## What are callback functions and how are they used?\n\n### Definition\n\nA callback function is a function that is passed as an argument to another function and is executed after some operation has been completed. This allows other code to run in the meantime and prevents blocking.\n\n### Synchronous callbacks\n\nSynchronous callbacks are executed immediately within the function they are passed to. They are often used for tasks that need to be completed before moving on to the next line of code.\n\n```js live\nfunction greet(name, callback) {\n  console.log('Hello ' + name);\n  callback();\n}\n\nfunction sayGoodbye() {\n  console.log('Goodbye!');\n}\n\ngreet('Alice', sayGoodbye);\n// Output:\n// Hello Alice\n// Goodbye!\n```\n\n### Asynchronous callbacks\n\nAsynchronous callbacks are used for operations that take some time to complete, such as reading files, making HTTP requests, or handling events. These callbacks are executed after the asynchronous operation has finished.\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John Doe' };\n    callback(data);\n  }, 1000);\n}\n\nfunction handleData(data) {\n  console.log(data);\n}\n\nfetchData(handleData);\n// Output: { name: 'John Doe' } after 1 second\n```\n\n### Common use cases\n\n#### Event handling\n\nCallbacks are often used in event handling. For example, in JavaScript, you can pass a callback function to an event listener.\n\n```js live\nconst button = document.createElement('button');\n\nbutton.addEventListener('click', () => {\n  setTimeout(() => {\n    console.log('Button clicked after 1s');\n  }, 1000);\n});\n\nbutton.click();\n```\n\n#### API calls\n\nCallbacks are frequently used in making API calls to handle the response data.\n\n```js live\nfunction getUserData(userId, callback) {\n  fetch(`https://jsonplaceholder.typicode.com/todos/2`)\n    .then((response) => response.json())\n    .then((data) => callback(data))\n    .catch((error) => console.error('Error:', error));\n}\n\nfunction displayUserData(data) {\n  console.log(data);\n}\n\ngetUserData(1, displayUserData);\n```\n\n#### Timers\n\nCallbacks are also used with timers like `setTimeout` and `setInterval`.\n\n```js live\nfunction sayHello() {\n  console.log('Hello, world!');\n}\n\nsetTimeout(sayHello, 2000); // After 2 seconds elapse, sayHello callback is called\n```\n\n## Further reading\n\n- [MDN Web Docs: Callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function)\n- [JavaScript.info: Callbacks](https://javascript.info/callbacks)\n- [Eloquent JavaScript: Asynchronous Programming](https://eloquentjavascript.net/11_async.html)\n"
  },
  {
    "path": "questions/what-are-callback-functions-and-how-are-they-used/metadata.json",
    "content": "{\n  \"slug\": \"what-are-callback-functions-and-how-are-they-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"async\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Functions\"\n}\n"
  },
  {
    "path": "questions/what-are-callback-functions-and-how-are-they-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是回调函数以及如何使用它们？\n---\n\n## TL;DR\n\n回调函数是作为参数传递给另一个函数的函数，然后在外部函数中调用该函数以完成某种例程或操作。它们通常用于异步操作，例如处理事件、进行 API 调用或读取文件。例如：\n\n```js live\nfunction fetchData(callback) {\n  // assume an asynchronous operation to fetch data\n  const data = { name: 'John Doe' };\n  callback(data);\n}\n\nfunction handleData(data) {\n  console.log(data);\n}\n\nfetchData(handleData);\n```\n\n***\n\n## 什么是回调函数以及如何使用它们？\n\n### 定义\n\n回调函数是作为参数传递给另一个函数并在完成某些操作后执行的函数。这允许其他代码同时运行并防止阻塞。\n\n### 同步回调\n\n同步回调在传递给它们的函数中立即执行。它们通常用于需要在进入下一行代码之前完成的任务。\n\n```js live\nfunction greet(name, callback) {\n  console.log('Hello ' + name);\n  callback();\n}\n\nfunction sayGoodbye() {\n  console.log('Goodbye!');\n}\n\ngreet('Alice', sayGoodbye);\n// Output:\n// Hello Alice\n// Goodbye!\n```\n\n### 异步回调\n\n异步回调用于需要一些时间才能完成的操作，例如读取文件、发出 HTTP 请求或处理事件。这些回调在异步操作完成后执行。\n\n```js live\nfunction fetchData(callback) {\n  setTimeout(() => {\n    const data = { name: 'John Doe' };\n    callback(data);\n  }, 1000);\n}\n\nfunction handleData(data) {\n  console.log(data);\n}\n\nfetchData(handleData);\n// Output: { name: 'John Doe' } after 1 second\n```\n\n### 常见用例\n\n#### 事件处理\n\n回调通常用于事件处理。例如，在 JavaScript 中，您可以将回调函数传递给事件侦听器。\n\n```js live\nconst button = document.createElement('button');\n\nbutton.addEventListener('click', () => {\n  setTimeout(() => {\n    console.log('Button clicked after 1s');\n  }, 1000);\n});\n\nbutton.click();\n```\n\n#### API 调用\n\n回调经常用于进行 API 调用以处理响应数据。\n\n```js live\nfunction getUserData(userId, callback) {\n  fetch(`https://jsonplaceholder.typicode.com/todos/2`)\n    .then((response) => response.json())\n    .then((data) => callback(data))\n    .catch((error) => console.error('Error:', error));\n}\n\nfunction displayUserData(data) {\n  console.log(data);\n}\n\ngetUserData(1, displayUserData);\n```\n\n#### 定时器\n\n回调函数也用于计时器，如 `setTimeout` 和 `setInterval`。\n\n```js live\nfunction sayHello() {\n  console.log('Hello, world!');\n}\n\nsetTimeout(sayHello, 2000); // 2 秒后，sayHello 回调函数被调用\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function)\n* [JavaScript.info: Callbacks](https://javascript.info/callbacks)\n* [Eloquent JavaScript: Asynchronous Programming](https://eloquentjavascript.net/11_async.html)\n"
  },
  {
    "path": "questions/what-are-default-parameters-and-how-are-they-used/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"1addacf8\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"4b08f03b\",\n        \"6a552481\",\n        \"2a7816d0\",\n        \"8a464295\",\n        \"d7e64b68\",\n        \"eea083fa\",\n        \"1b6ecd61\",\n        \"9155cd6e\",\n        \"9b5019f0\",\n        \"ae7fa957\",\n        \"6a552481\",\n        \"d1d1fb12\",\n        \"9fb6eb8e\",\n        \"9a047168\",\n        \"f8c3b35e\",\n        \"916ba07f\",\n        \"87538ac8\",\n        \"1e9b6372\",\n        \"442a74d3\",\n        \"15fc8dff\",\n        \"1f4770e5\",\n        \"3ea4c540\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4b08f03b\",\n        \"6a552481\",\n        \"2a7816d0\",\n        \"8a464295\",\n        \"d7e64b68\",\n        \"eea083fa\",\n        \"1b6ecd61\",\n        \"9155cd6e\",\n        \"9b5019f0\",\n        \"ae7fa957\",\n        \"6a552481\",\n        \"d1d1fb12\",\n        \"9fb6eb8e\",\n        \"9a047168\",\n        \"f8c3b35e\",\n        \"916ba07f\",\n        \"87538ac8\",\n        \"1e9b6372\",\n        \"442a74d3\",\n        \"15fc8dff\",\n        \"1f4770e5\",\n        \"3ea4c540\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-default-parameters-and-how-are-they-used/en-US.mdx",
    "content": "---\ntitle: What are default parameters and how are they used?\n---\n\n## TL;DR\n\nDefault parameters in JavaScript allow you to set default values for function parameters if no value or `undefined` is passed. This helps avoid `undefined` values and makes your code more robust. You can define default parameters by assigning a value to the parameter in the function definition.\n\n```js live\nfunction greet(name = 'Guest') {\n  console.log(`Hello, ${name}!`);\n}\n\ngreet(); // Output: Hello, Guest!\ngreet('Alice'); // Output: Hello, Alice!\n```\n\n---\n\n## Default parameters\n\nDefault parameters in JavaScript provide a way to set default values for function parameters. This feature was introduced in ECMAScript 2015 (ES6) and helps to make functions more robust and easier to work with by avoiding `undefined` values when no arguments are passed.\n\n### Syntax\n\nYou can define default parameters by assigning a value to the parameter in the function definition. If no value or `undefined` is passed for that parameter, the default value will be used.\n\n```js\nfunction functionName(parameter1 = defaultValue1, parameter2 = defaultValue2) {\n  // function body\n}\n```\n\n### Example\n\nHere is a simple example to illustrate how default parameters work:\n\n```js live\nfunction greet(name = 'Guest') {\n  console.log(`Hello, ${name}!`);\n}\n\ngreet(); // Output: Hello, Guest!\ngreet('Alice'); // Output: Hello, Alice!\n```\n\nIn this example, the `greet` function has a default parameter `name` with a default value of `'Guest'`. When the function is called without any arguments, it uses the default value. When an argument is provided, it overrides the default value.\n\n### Multiple default parameters\n\nYou can also define multiple default parameters in a function:\n\n```js live\nfunction createUser(username = 'Anonymous', age = 18) {\n  console.log(`Username: ${username}, Age: ${age}`);\n}\n\ncreateUser(); // Output: Username: Anonymous, Age: 18\ncreateUser('John'); // Output: Username: John, Age: 18\ncreateUser('John', 25); // Output: Username: John, Age: 25\n```\n\nIn this example, the `createUser` function has two default parameters: `username` and `age`. If no arguments are passed, both default values are used. If only one argument is passed, the second parameter uses its default value.\n\n### Using expressions as default values\n\nYou can also use expressions as default values for parameters:\n\n```js live\nfunction add(a = 0, b = a + 1) {\n  return a + b;\n}\n\nconsole.log(add()); // Output: 1\nconsole.log(add(5)); // Output: 11\nconsole.log(add(5, 10)); // Output: 15\n```\n\nIn this example, the default value for `b` is an expression that depends on the value of `a`. If no arguments are passed, `a` is `0` and `b` is `1`. If only `a` is passed, `b` is `a + 1`. If both `a` and `b` are passed, the provided values are used.\n\n## Further reading\n\n- [MDN Web Docs: Default parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters)\n- [JavaScript.info: Default parameters](https://javascript.info/function-basics#default-values)\n- [ECMAScript 2015 (ES6) specification](https://www.ecma-international.org/ecma-262/6.0/#sec-function-definitions)\n"
  },
  {
    "path": "questions/what-are-default-parameters-and-how-are-they-used/metadata.json",
    "content": "{\n  \"slug\": \"what-are-default-parameters-and-how-are-they-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Functions\"\n}\n"
  },
  {
    "path": "questions/what-are-default-parameters-and-how-are-they-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是默认参数以及如何使用它们？\n---\n\n## TL;DR\n\nJavaScript 中的默认参数允许您为函数参数设置默认值，如果没有传递任何值或 `undefined`。这有助于避免 `undefined` 值，并使您的代码更健壮。您可以通过在函数定义中为参数赋值来定义默认参数。\n\n```js live\nfunction greet(name = 'Guest') {\n  console.log(`Hello, ${name}!`);\n}\n\ngreet(); // Output: Hello, Guest!\ngreet('Alice'); // Output: Hello, Alice!\n```\n\n***\n\n## 默认参数\n\nJavaScript 中的默认参数提供了一种为函数参数设置默认值的方法。此功能是在 ECMAScript 2015 (ES6) 中引入的，通过避免未传递任何参数时出现 `undefined` 值，有助于使函数更健壮且更易于使用。\n\n### 语法\n\n您可以通过在函数定义中为参数赋值来定义默认参数。如果未传递该参数的值或 `undefined`，则将使用默认值。\n\n```js\nfunction functionName(parameter1 = defaultValue1, parameter2 = defaultValue2) {\n  // function body\n}\n```\n\n### 示例\n\n这是一个简单的示例，说明默认参数的工作原理：\n\n```js live\nfunction greet(name = 'Guest') {\n  console.log(`Hello, ${name}!`);\n}\n\ngreet(); // Output: Hello, Guest!\ngreet('Alice'); // Output: Hello, Alice!\n```\n\n在此示例中，`greet` 函数有一个默认参数 `name`，其默认值为 `'Guest'`。当不带任何参数调用该函数时，它使用默认值。当提供参数时，它会覆盖默认值。\n\n### 多个默认参数\n\n您还可以在一个函数中定义多个默认参数：\n\n```js live\nfunction createUser(username = 'Anonymous', age = 18) {\n  console.log(`Username: ${username}, Age: ${age}`);\n}\n\ncreateUser(); // Output: Username: Anonymous, Age: 18\ncreateUser('John'); // Output: Username: John, Age: 18\ncreateUser('John', 25); // Output: Username: John, Age: 25\n```\n\n在此示例中，`createUser` 函数有两个默认参数：`username` 和 `age`。如果未传递任何参数，则使用两个默认值。如果仅传递一个参数，则第二个参数使用其默认值。\n\n### 使用表达式作为默认值\n\n您还可以使用表达式作为参数的默认值：\n\n```js live\nfunction add(a = 0, b = a + 1) {\n  return a + b;\n}\n\nconsole.log(add()); // Output: 1\nconsole.log(add(5)); // Output: 11\nconsole.log(add(5, 10)); // Output: 15\n```\n\n在这个例子中，`b` 的默认值是一个依赖于 `a` 值的表达式。如果没有传递参数，`a` 是 `0`，`b` 是 `1`。如果只传递了 `a`，`b` 是 `a + 1`。如果同时传递了 `a` 和 `b`，则使用提供的值。\n\n## 延伸阅读\n\n* [MDN Web 文档：默认参数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Default_parameters)\n* [JavaScript.info：默认参数](https://javascript.info/function-basics#default-values)\n* [ECMAScript 2015 (ES6) 规范](https://www.ecma-international.org/ecma-262/6.0/#sec-function-definitions)\n"
  },
  {
    "path": "questions/what-are-design-patterns-and-why-are-they-useful/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"29e1b7af\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"697cd09c\",\n        \"2a7816d0\",\n        \"a73b745d\",\n        \"a2d12ef9\",\n        \"27dcd70f\",\n        \"dfaabb48\",\n        \"3b039eaa\",\n        \"6191c545\",\n        \"b53dca6e\",\n        \"eaea05fa\",\n        \"88ad0e17\",\n        \"bb47c1cb\",\n        \"24936fbf\",\n        \"2928f66d\",\n        \"1f4770e5\",\n        \"44a9ce4b\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"697cd09c\",\n        \"2a7816d0\",\n        \"a73b745d\",\n        \"a2d12ef9\",\n        \"27dcd70f\",\n        \"dfaabb48\",\n        \"3b039eaa\",\n        \"6191c545\",\n        \"b53dca6e\",\n        \"eaea05fa\",\n        \"88ad0e17\",\n        \"bb47c1cb\",\n        \"24936fbf\",\n        \"2928f66d\",\n        \"1f4770e5\",\n        \"44a9ce4b\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-design-patterns-and-why-are-they-useful/en-US.mdx",
    "content": "---\ntitle: What are design patterns and why are they useful?\n---\n\n## TL;DR\n\nDesign patterns are reusable solutions to common problems in software design. They provide a template for how to solve a problem that can be used in many different situations. They are useful because they help developers avoid common pitfalls, improve code readability, and make it easier to maintain and scale applications.\n\n---\n\n## What are design patterns and why are they useful?\n\n### Definition of design patterns\n\nDesign patterns are general, reusable solutions to common problems that occur in software design. They are not finished designs that can be directly transformed into code but rather templates that describe how to solve a problem in various contexts. The concept was popularized by the book \"Design Patterns: Elements of Reusable Object-Oriented Software\" by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, also known as the \"Gang of Four\" (GoF).\n\n### Types of design patterns\n\nDesign patterns are typically categorized into three main types:\n\n1. **Creational patterns**: Deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. Examples include Singleton, Factory Method, and Abstract Factory.\n2. **Structural patterns**: Deal with object composition or the structure of classes and objects. Examples include Adapter, Composite, and Decorator.\n3. **Behavioral patterns**: Deal with object interaction and responsibility. Examples include Observer, Strategy, and Command.\n\n### Why design patterns are useful\n\n1. **Reusability**: Design patterns provide a proven solution to common problems, which can be reused across different projects.\n2. **Maintainability**: They help in writing code that is easier to understand, maintain, and extend.\n3. **Scalability**: Design patterns can help in designing systems that are scalable and can handle growth in complexity.\n4. **Communication**: They provide a common vocabulary for developers, making it easier to discuss and share design ideas.\n5. **Best practices**: They encapsulate best practices and industry standards, helping developers avoid common pitfalls.\n\n### Example: Singleton pattern\n\nThe Singleton pattern ensures that a class has only one instance and provides a global point of access to it. Here is a simple implementation in JavaScript:\n\n```js live\nclass Singleton {\n  constructor() {\n    if (Singleton.instance) {\n      return Singleton.instance;\n    }\n    Singleton.instance = this;\n  }\n\n  someMethod() {\n    console.log('Singleton method');\n  }\n}\n\nconst instance1 = new Singleton();\nconst instance2 = new Singleton();\n\nconsole.log(instance1 === instance2); // true\n```\n\nIn this example, the `Singleton` class ensures that only one instance of the class is created. Any subsequent calls to create a new instance will return the existing instance.\n\n## Further reading\n\n- [Design Patterns: Elements of Reusable Object-Oriented Software](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four\n- [Refactoring Guru: Design Patterns](https://refactoring.guru/design-patterns)\n- [JavaScript Design Patterns](https://addyosmani.com/resources/essentialjsdesignpatterns/book/) by Addy Osmani\n"
  },
  {
    "path": "questions/what-are-design-patterns-and-why-are-they-useful/metadata.json",
    "content": "{\n  \"slug\": \"what-are-design-patterns-and-why-are-they-useful\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Design Patterns\"\n}\n"
  },
  {
    "path": "questions/what-are-design-patterns-and-why-are-they-useful/zh-CN.mdx",
    "content": "---\ntitle: 什么是设计模式？它们为什么有用？\n---\n\n## TL;DR\n\n设计模式是软件设计中常见问题的可重用解决方案。它们为如何解决可以在许多不同情况下使用的问题提供了一个模板。它们之所以有用，是因为它们可以帮助开发人员避免常见的陷阱，提高代码可读性，并使维护和扩展应用程序更容易。\n\n***\n\n## 什么是设计模式？它们为什么有用？\n\n### 设计模式的定义\n\n设计模式是针对软件设计中出现的常见问题的一般性、可重用的解决方案。它们不是可以直接转化为代码的已完成设计，而是描述如何在各种上下文中解决问题的模板。这个概念由 Erich Gamma、Richard Helm、Ralph Johnson 和 John Vlissides（也称为“四人帮”（GoF））合著的《设计模式：可复用面向对象软件要素》一书推广。\n\n### 设计模式的类型\n\n设计模式通常分为三种主要类型：\n\n1. **创建型模式**：处理对象创建机制，试图以适合情况的方式创建对象。示例包括单例模式、工厂方法和抽象工厂。\n2. **结构型模式**：处理对象组合或类和对象的结构。示例包括适配器模式、组合模式和装饰器模式。\n3. **行为型模式**：处理对象交互和责任。示例包括观察者模式、策略模式和命令模式。\n\n### 为什么设计模式有用\n\n1. **可重用性**：设计模式为常见问题提供了经过验证的解决方案，可以在不同的项目中重复使用。\n2. **可维护性**：它们有助于编写更易于理解、维护和扩展的代码。\n3. **可扩展性**：设计模式可以帮助设计可扩展的系统，并可以处理复杂性的增长。\n4. **沟通**：它们为开发人员提供了通用词汇，使讨论和分享设计理念更容易。\n5. **最佳实践**：它们封装了最佳实践和行业标准，帮助开发人员避免常见的陷阱。\n\n### 示例：单例模式\n\n单例模式确保一个类只有一个实例，并提供对它的全局访问点。以下是 JavaScript 中的一个简单实现：\n\n```js live\nclass Singleton {\n  constructor() {\n    if (Singleton.instance) {\n      return Singleton.instance;\n    }\n    Singleton.instance = this;\n  }\n\n  someMethod() {\n    console.log('Singleton method');\n  }\n}\n\nconst instance1 = new Singleton();\nconst instance2 = new Singleton();\n\nconsole.log(instance1 === instance2); // true\n```\n\n在此示例中，`Singleton` 类确保只创建一个类的实例。任何后续创建新实例的调用都将返回现有实例。\n\n## 延伸阅读\n\n* [设计模式：可复用面向对象软件的要素](https://en.wikipedia.org/wiki/Design_Patterns) by the Gang of Four\n* [Refactoring Guru: 设计模式](https://refactoring.guru/design-patterns)\n* [JavaScript 设计模式](https://addyosmani.com/resources/essentialjsdesignpatterns/book/) by Addy Osmani\n"
  },
  {
    "path": "questions/what-are-event-listeners-and-how-are-they-used/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"9f373e88\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"965047e7\",\n        \"7b0f39ef\",\n        \"2a7816d0\",\n        \"848476af\",\n        \"f006b370\",\n        \"bb257db9\",\n        \"4b18b236\",\n        \"d5d3a621\",\n        \"a929b399\",\n        \"282d85b5\",\n        \"f4b49386\",\n        \"48d0a82a\",\n        \"febabc20\",\n        \"b7029f4\",\n        \"49ab7913\",\n        \"c8b14e3f\",\n        \"671f2159\",\n        \"ef6c45eb\",\n        \"ee639337\",\n        \"3357370b\",\n        \"2551ecd\",\n        \"1f4770e5\",\n        \"7101ec23\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"965047e7\",\n        \"7b0f39ef\",\n        \"2a7816d0\",\n        \"848476af\",\n        \"f006b370\",\n        \"bb257db9\",\n        \"4b18b236\",\n        \"d5d3a621\",\n        \"a929b399\",\n        \"282d85b5\",\n        \"f4b49386\",\n        \"48d0a82a\",\n        \"febabc20\",\n        \"b7029f4\",\n        \"49ab7913\",\n        \"c8b14e3f\",\n        \"671f2159\",\n        \"ef6c45eb\",\n        \"ee639337\",\n        \"3357370b\",\n        \"2551ecd\",\n        \"1f4770e5\",\n        \"7101ec23\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-event-listeners-and-how-are-they-used/en-US.mdx",
    "content": "---\ntitle: What are event listeners and how are they used?\n---\n\n## TL;DR\n\nEvent listeners are functions that wait for specific events to occur on elements, such as clicks or key presses. They are used to execute code in response to these events. You can add an event listener to an element using the `addEventListener` method. For example:\n\n```js\ndocument.getElementById('myButton').addEventListener('click', function () {\n  alert('Button was clicked!');\n});\n```\n\n---\n\n## What are event listeners and how are they used?\n\nEvent listeners are a fundamental part of web development, allowing developers to make web pages interactive by responding to user actions. They are functions that wait for specific events to occur on elements, such as clicks, key presses, or mouse movements, and then execute a specified function when those events occur.\n\n### Adding an event listener\n\nTo add an event listener to an element, you use the `addEventListener` method. This method takes two main arguments: the type of event to listen for and the function to execute when the event occurs.\n\n```js\nconst button = document.getElementById('myButton');\n\nbutton.addEventListener('click', function () {\n  alert('Button was clicked!');\n});\n```\n\nIn this example, an event listener is added to a button element with the ID `myButton`. When the button is clicked, an alert box will appear with the message \"Button was clicked!\".\n\n### Removing an event listener\n\nYou can also remove an event listener using the `removeEventListener` method. This method requires the same arguments as `addEventListener`: the event type and the function to remove.\n\n```js\nfunction handleClick() {\n  alert('Button was clicked!');\n}\n\nbutton.addEventListener('click', handleClick);\n\n// Later, you can remove the event listener\nbutton.removeEventListener('click', handleClick);\n```\n\n### Event object\n\nWhen an event listener is triggered, an event object is passed to the event handler function. This object contains useful information about the event, such as the target element, the type of event, and more.\n\n```js\nbutton.addEventListener('click', function (event) {\n  console.log('Event type:', event.type);\n  console.log('Target element:', event.target);\n});\n```\n\n### Common event types\n\n- `click`: Triggered when an element is clicked\n- `mouseover`: Triggered when the mouse pointer is moved over an element\n- `mouseout`: Triggered when the mouse pointer is moved out of an element\n- `keydown`: Triggered when a key is pressed down\n- `keyup`: Triggered when a key is released\n\n### Event delegation\n\nEvent delegation is a technique where a single event listener is added to a parent element to manage events for multiple child elements. This is useful for improving performance and managing dynamic content.\n\n```js\nconst list = document.getElementById('myList');\n\nlist.addEventListener('click', function (event) {\n  if (event.target && event.target.nodeName === 'LI') {\n    console.log('List item clicked:', event.target.textContent);\n  }\n});\n```\n\nIn this example, a single event listener is added to a list element. When any list item (`LI`) is clicked, the event listener will handle the event.\n\n## Further reading\n\n- [MDN Web Docs: EventTarget.addEventListener()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)\n- [JavaScript.info: Introduction to browser events](https://javascript.info/introduction-browser-events)\n- [W3Schools: JavaScript Event Listeners](https://www.w3schools.com/js/js_htmldom_eventlistener.asp)\n"
  },
  {
    "path": "questions/what-are-event-listeners-and-how-are-they-used/metadata.json",
    "content": "{\n  \"slug\": \"what-are-event-listeners-and-how-are-they-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"DOM Manipulation & Events\"\n}\n"
  },
  {
    "path": "questions/what-are-event-listeners-and-how-are-they-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是事件监听器以及如何使用它们？\n---\n\n## TL;DR\n\n事件监听器是等待元素上发生特定事件（例如单击或按键）的函数。它们用于响应这些事件执行代码。您可以使用 `addEventListener` 方法将事件监听器添加到元素。例如：\n\n```js\ndocument.getElementById('myButton').addEventListener('click', function () {\n  alert('Button was clicked!');\n});\n```\n\n***\n\n## 什么是事件监听器以及如何使用它们？\n\n事件监听器是 Web 开发的基本组成部分，允许开发人员通过响应用户操作来使网页具有交互性。它们是等待元素上发生特定事件（例如单击、按键或鼠标移动）的函数，然后在这些事件发生时执行指定的函数。\n\n### 添加事件监听器\n\n要将事件监听器添加到元素，您可以使用 `addEventListener` 方法。此方法接受两个主要参数：要侦听的事件类型和事件发生时要执行的函数。\n\n```js\nconst button = document.getElementById('myButton');\n\nbutton.addEventListener('click', function () {\n  alert('Button was clicked!');\n});\n```\n\n在此示例中，将事件监听器添加到 ID 为 `myButton` 的按钮元素。单击该按钮时，将弹出一个警报框，其中显示消息“Button was clicked!”。\n\n### 移除事件监听器\n\n您还可以使用 `removeEventListener` 方法移除事件监听器。此方法需要与 `addEventListener` 相同的参数：事件类型和要移除的函数。\n\n```js\nfunction handleClick() {\n  alert('Button was clicked!');\n}\n\nbutton.addEventListener('click', handleClick);\n\n// Later, you can remove the event listener\nbutton.removeEventListener('click', handleClick);\n```\n\n### 事件对象\n\n触发事件监听器时，会将一个事件对象传递给事件处理程序函数。此对象包含有关事件的有用信息，例如目标元素、事件类型等。\n\n```js\nbutton.addEventListener('click', function (event) {\n  console.log('Event type:', event.type);\n  console.log('Target element:', event.target);\n});\n```\n\n### 常见事件类型\n\n* `click`: 单击元素时触发\n* `mouseover`: 鼠标指针移动到元素上时触发\n* `mouseout`: 鼠标指针移出元素时触发\n* `keydown`: 按下某个键时触发\n* `keyup`: 释放某个键时触发\n\n### 事件委托\n\n事件委托是一种技术，其中将单个事件侦听器添加到父元素以管理多个子元素的事件。这对于提高性能和管理动态内容很有用。\n\n```js\nconst list = document.getElementById('myList');\n\nlist.addEventListener('click', function (event) {\n  if (event.target && event.target.nodeName === 'LI') {\n    console.log('List item clicked:', event.target.textContent);\n  }\n});\n```\n\n在此示例中，将单个事件侦听器添加到列表元素。当单击任何列表项 (`LI`) 时，事件侦听器将处理该事件。\n\n## 延伸阅读\n\n* [MDN Web Docs: EventTarget.addEventListener()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)\n* [JavaScript.info: Introduction to browser events](https://javascript.info/introduction-browser-events)\n* [W3Schools: JavaScript Event Listeners](https://www.w3schools.com/js/js_htmldom_eventlistener.asp)\n"
  },
  {
    "path": "questions/what-are-iterators-and-generators-and-what-are-they-used-for/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"2d9a1101\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"1fbc1653\",\n        \"3ade285a\",\n        \"c89f20c8\",\n        \"a544b1ca\",\n        \"f9b750be\",\n        \"9b462d6c\",\n        \"c49d63cd\",\n        \"9b1ec55b\",\n        \"b03f6710\",\n        \"2a7816d0\",\n        \"498e3e0c\",\n        \"95767bd4\",\n        \"2b3876be\",\n        \"25fc3008\",\n        \"6d92d3ca\",\n        \"7399fd6f\",\n        \"120ea48b\",\n        \"1694de85\",\n        \"7c3979b6\",\n        \"a66dddf1\",\n        \"c873062e\",\n        \"8ee35790\",\n        \"35453aab\",\n        \"e8a375ac\",\n        \"85abbd38\",\n        \"dec95974\",\n        \"cd488623\",\n        \"d6e49419\",\n        \"e7c3bd26\",\n        \"db059272\",\n        \"38954020\",\n        \"4c8a5ec5\",\n        \"f5d2f3b4\",\n        \"51c7926e\",\n        \"c927706b\",\n        \"88f6a16\",\n        \"b1239f8f\",\n        \"67a1d4f3\",\n        \"3f58a222\",\n        \"1f4770e5\",\n        \"d5505063\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"1fbc1653\",\n        \"3ade285a\",\n        \"c89f20c8\",\n        \"a544b1ca\",\n        \"f9b750be\",\n        \"9b462d6c\",\n        \"c49d63cd\",\n        \"9b1ec55b\",\n        \"b03f6710\",\n        \"2a7816d0\",\n        \"498e3e0c\",\n        \"95767bd4\",\n        \"2b3876be\",\n        \"25fc3008\",\n        \"6d92d3ca\",\n        \"7399fd6f\",\n        \"120ea48b\",\n        \"1694de85\",\n        \"7c3979b6\",\n        \"a66dddf1\",\n        \"c873062e\",\n        \"8ee35790\",\n        \"35453aab\",\n        \"e8a375ac\",\n        \"85abbd38\",\n        \"dec95974\",\n        \"cd488623\",\n        \"d6e49419\",\n        \"e7c3bd26\",\n        \"db059272\",\n        \"38954020\",\n        \"4c8a5ec5\",\n        \"f5d2f3b4\",\n        \"51c7926e\",\n        \"c927706b\",\n        \"88f6a16\",\n        \"b1239f8f\",\n        \"67a1d4f3\",\n        \"3f58a222\",\n        \"1f4770e5\",\n        \"d5505063\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-iterators-and-generators-and-what-are-they-used-for/en-US.mdx",
    "content": "---\ntitle: What are iterators and generators in JavaScript and what are they used for?\n---\n\n## TL;DR\n\nIn JavaScript, iterators and generators are powerful tools for managing sequences of data and controlling the flow of execution in a more flexible way.\n\n**Iterators** are objects that define a sequence and potentially a return value upon its termination. It adheres to a specific interface:\n\n- An iterator object must implement a `next()` method.\n- The `next()` method returns an object with two properties:\n  - `value`: The next value in the sequence.\n  - `done`: A boolean that is `true` if the iterator has finished its sequence, otherwise `false`.\n\nHere's an example of an object implementing the iterator interface.\n\n```js live\nconst iterator = {\n  current: 0,\n  last: 5,\n  next() {\n    if (this.current <= this.last) {\n      return { value: this.current++, done: false };\n    } else {\n      return { value: undefined, done: true };\n    }\n  },\n};\n\nlet result = iterator.next();\nwhile (!result.done) {\n  console.log(result.value); // Logs 0, 1, 2, 3, 4, 5\n  result = iterator.next();\n}\n```\n\n**Generators** are a special functions that **can pause execution and resume at a later point**. It uses the `function*` syntax and the `yield` keyword to control the flow of execution. When you call a generator function, it doesn't execute completely like a regular function. Instead, it returns an iterator object. Calling the `next()` method on the returned iterator advances the generator to the next `yield` statement, and the value after `yield` becomes the return value of `next()`.\n\n```js live\nfunction* numberGenerator() {\n  let num = 0;\n  while (num <= 5) {\n    yield num++;\n  }\n}\n\nconst gen = numberGenerator();\nconsole.log(gen.next()); // { value: 0, done: false }\nconsole.log(gen.next()); // { value: 1, done: false }\nconsole.log(gen.next()); // { value: 2, done: false }\nconsole.log(gen.next()); // { value: 3, done: false }\nconsole.log(gen.next()); // { value: 4, done: false }\nconsole.log(gen.next()); // { value: 5, done: false }\nconsole.log(gen.next()); // { value: undefined, done: true }\n```\n\nGenerators are powerful for creating iterators on-demand, especially for infinite sequences or complex iteration logic. They can be used for:\n\n- Lazy evaluation – processing elements only when needed, improving memory efficiency for large datasets.\n- Implementing iterators for custom data structures.\n- Creating asynchronous iterators for handling data streams.\n\n---\n\n## Iterators\n\nIterators are objects that define a sequence and provide a `next()` method to access the next value in the sequence. They are used to iterate over data structures like `arrays`, `strings`, and custom `objects`. The key use case of iterators include:\n\n- Implementing the iterator protocol to make custom objects iterable, allowing them to be used with `for...of` loops and other language constructs that expect iterables.\n- Providing a standard way to iterate over different data structures, making code more reusable and maintainable.\n\n### Creating a custom iterator for a range of numbers\n\nIn JavaScript, we can provide a default implementation for iterator by implementing `[Symbol.iterator]()` in any custom object.\n\n```js live\n// Define a class named Range\nclass Range {\n  // The constructor takes two parameters: start and end\n  constructor(start, end) {\n    // Assign the start and end values to the instance\n    this.start = start;\n    this.end = end;\n  }\n\n  // Define the default iterator for the object\n  [Symbol.iterator]() {\n    // Initialize the current value to the start value\n    let current = this.start;\n    const end = this.end;\n\n    // Return an object with a next method\n    return {\n      // The next method returns the next value in the iteration\n      next() {\n        // If the current value is less than or equal to the end value...\n        if (current <= end) {\n          // ...return an object with the current value and done set to false\n          return { value: current++, done: false };\n        }\n\n        // ...otherwise, return an object with value set to undefined and done set to true\n        return { value: undefined, done: true };\n      },\n    };\n  }\n}\n\n// Create a new Range object with start = 1 and end = 3\nconst range = new Range(1, 3);\n// Iterate over the range object\nfor (const number of range) {\n  // Log each number to the console\n  console.log(number); // 1, 2, 3\n}\n```\n\n### Built-in objects using the iterator protocol\n\nIn JavaScript, several built-in objects implement the iterator protocol, meaning they have a default `@@iterator` method. This allows them to be used in constructs like `for...of` loops and with the spread operator. Here are some of the key built-in objects that implement iterators:\n\n1. **Arrays**: Arrays have a built-in iterator that allows you to iterate over their elements.\n\n   ```js live\n   const array = [1, 2, 3];\n   const iterator = array[Symbol.iterator]();\n\n   console.log(iterator.next()); // { value: 1, done: false }\n   console.log(iterator.next()); // { value: 2, done: false }\n   console.log(iterator.next()); // { value: 3, done: false }\n   console.log(iterator.next()); // { value: undefined, done: true }\n\n   for (const value of array) {\n     console.log(value); // Logs 1, 2, 3\n   }\n   ```\n\n2. **Strings**: Strings have a built-in iterator that allows you to iterate over their characters.\n\n   ```js live\n   const string = 'hello';\n   const iterator = string[Symbol.iterator]();\n\n   console.log(iterator.next()); // { value: \"h\", done: false }\n   console.log(iterator.next()); // { value: \"e\", done: false }\n   console.log(iterator.next()); // { value: \"l\", done: false }\n   console.log(iterator.next()); // { value: \"l\", done: false }\n   console.log(iterator.next()); // { value: \"o\", done: false }\n   console.log(iterator.next()); // { value: undefined, done: true }\n\n   for (const char of string) {\n     console.log(char); // Logs h, e, l, l, o\n   }\n   ```\n\n3. **DOM NodeLists**\n\n   ```js live\n   // Create a new div and append it to the DOM\n   const newDiv = document.createElement('div');\n   newDiv.id = 'div1';\n   document.body.appendChild(newDiv);\n\n   const nodeList = document.querySelectorAll('div');\n   const iterator = nodeList[Symbol.iterator]();\n\n   console.log(iterator.next()); // { value: HTMLDivElement, done: false }\n   console.log(iterator.next()); // { value: undefined, done: true }\n\n   for (const node of nodeList) {\n     console.log(node); // Logs each <div> element, in this case only div1\n   }\n   ```\n\n`Map`s and `Set`s also have built-in iterators.\n\n## Generators\n\nGenerators are a special kind of function that can pause and resume their execution, allowing them to generate a sequence of values on-the-fly. They are commonly used to create iterators but have other applications as well. The key use cases of generators include:\n\n- Creating iterators in a more concise and readable way compared to manually implementing the iterator protocol.\n- Implementing lazy evaluation, where values are generated only when needed, saving memory and computation time.\n- Simplifying asynchronous programming by allowing code to be written in a synchronous-looking style using `yield` and `await`.\n\nGenerators provide several benefits:\n\n- **Lazy evaluation**: They generate values on the fly and only when required, which is memory efficient.\n- **Pause and resume**: Generators can pause execution (via `yield`) and can also receive new data upon resuming.\n- **Asynchronous iteration**: With the advent of `async/await`, generators can be used to manage asynchronous data flows.\n\n### Creating an iterator using a generator function\n\nWe can rewrite our `Range` example to use a generator function:\n\n```js live\n// Define a class named Range\nclass Range {\n  // The constructor takes two parameters: start and end\n  constructor(start, end) {\n    // Assign the start and end values to the instance\n    this.start = start;\n    this.end = end;\n  }\n\n  // Define the default iterator for the object using a generator\n  *[Symbol.iterator]() {\n    // Initialize the current value to the start value\n    let current = this.start;\n\n    // While the current value is less than or equal to the end value...\n    while (current <= this.end) {\n      // ...yield the current value\n      yield current++;\n    }\n  }\n}\n\n// Create a new Range object with start = 1 and end = 3\nconst range = new Range(1, 3);\n// Iterate over the range object\nfor (const number of range) {\n  // Log each number to the console\n  console.log(number); // 1, 2, 3\n}\n```\n\n### Iterating over data streams\n\nGenerators are well-suited for iterating over data streams, such as fetching data from an API or reading files. This example demonstrates using a generator to fetch data from an API in batches:\n\n```js live\nasync function* fetchDataInBatches(url, numBatches = 5, batchSize = 10) {\n  let startIndex = 0;\n  let currBatch = 0;\n\n  while (currBatch < numBatches) {\n    const response = await fetch(\n      `${url}?_start=${startIndex}&_limit=${batchSize}`,\n    );\n    const data = await response.json();\n    if (data.length === 0) break;\n    yield data;\n    startIndex += batchSize;\n    currBatch += 1;\n  }\n}\n\nasync function fetchAndLogData() {\n  const dataGenerator = fetchDataInBatches(\n    'https://jsonplaceholder.typicode.com/todos',\n  );\n\n  for await (const batch of dataGenerator) {\n    console.log(batch);\n  }\n}\nfetchAndLogData();\n```\n\nThis generator function `fetchDataInBatches` fetches data from an API in batches of a specified size. It yields each batch of data, allowing you to process it before fetching the next batch. This approach can be more memory-efficient than fetching all data at once.\n\n#### Implementing asynchronous iterators\n\nGenerators can be used to implement asynchronous iterators, which are useful for working with asynchronous data sources. This example demonstrates an asynchronous iterator for fetching data from an API:\n\n```js live\nasync function* fetchDataAsyncIterator(url, pagesToFetch = 3) {\n  let currPage = 1;\n\n  while (currPage <= pagesToFetch) {\n    const response = await fetch(`${url}?_page=${currPage}`);\n    const data = await response.json();\n    if (data.length === 0) break;\n    yield data;\n    currPage++;\n  }\n}\n\nasync function fetchAndLogData() {\n  const asyncIterator = fetchDataAsyncIterator(\n    'https://jsonplaceholder.typicode.com/todos',\n  );\n\n  for await (const chunk of asyncIterator) {\n    console.log(chunk);\n  }\n}\nfetchAndLogData();\n```\n\nThe generator function `fetchDataAsyncIterator` is an asynchronous iterator that fetches data from an API in pages. It yields each page of data, allowing you to process it before fetching the next page. This approach can be useful for handling large datasets or long-running operations.\n\nGenerators are also used extensively in JavaScript libraries and frameworks, such as [Redux-Saga](https://redux-saga.js.org/) and [RxJS](https://rxjs.dev/), for handling asynchronous operations and reactive programming.\n\n## Summary\n\nIterators and generators provide a powerful and flexible way to work with collections of data in JavaScript. Iterators define a standardized way to traverse data sequences, while generators offer a more expressive and efficient way to create iterators, handle asynchronous operations, and compose complex data pipelines.\n\n## Further reading\n\n- [Iterators and generators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)\n- [Async iteration and generators](https://javascript.info/async-iterators-generators)\n- [Iterables](https://javascript.info/iterable)\n- [Explore Iterators and Generators in JavaScript](https://blog.bitsrc.io/explore-iterators-and-generators-in-javascript-ea4102015377)\n- [Iterators and Generators in JavaScript](https://syntactic-sugar.dev/blog/nested-route/iterators-and-generators)\n"
  },
  {
    "path": "questions/what-are-iterators-and-generators-and-what-are-they-used-for/metadata.json",
    "content": "{\n  \"slug\": \"what-are-iterators-and-generators-and-what-are-they-used-for\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 380,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/what-are-iterators-and-generators-and-what-are-they-used-for/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中的迭代器和生成器是什么，它们有什么用途？\n---\n\n## TL;DR\n\n在 JavaScript 中，迭代器和生成器是用于管理数据序列和以更灵活的方式控制执行流程的强大工具。\n\n**迭代器**是定义序列并可能在其终止时返回值的对象。它遵循一个特定的接口：\n\n* 迭代器对象必须实现一个 `next()` 方法。\n* `next()` 方法返回一个具有两个属性的对象：\n  * `value`：序列中的下一个值。\n  * `done`：一个布尔值，如果迭代器已完成其序列，则为 `true`，否则为 `false`。\n\n这是一个实现迭代器接口的对象的示例。\n\n```js live\nconst iterator = {\n  current: 0,\n  last: 5,\n  next() {\n    if (this.current <= this.last) {\n      return { value: this.current++, done: false };\n    } else {\n      return { value: undefined, done: true };\n    }\n  },\n};\n\nlet result = iterator.next();\nwhile (!result.done) {\n  console.log(result.value); // Logs 0, 1, 2, 3, 4, 5\n  result = iterator.next();\n}\n```\n\n**生成器**是一种特殊的函数，**可以暂停执行并在稍后恢复**。它使用 `function*` 语法和 `yield` 关键字来控制执行流程。当您调用生成器函数时，它不会像普通函数一样完全执行。相反，它返回一个迭代器对象。在返回的迭代器上调用 `next()` 方法会将生成器推进到下一个 `yield` 语句，并且 `yield` 之后的值将成为 `next()` 的返回值。\n\n```js live\nfunction* numberGenerator() {\n  let num = 0;\n  while (num <= 5) {\n    yield num++;\n  }\n}\n\nconst gen = numberGenerator();\nconsole.log(gen.next()); // { value: 0, done: false }\nconsole.log(gen.next()); // { value: 1, done: false }\nconsole.log(gen.next()); // { value: 2, done: false }\nconsole.log(gen.next()); // { value: 3, done: false }\nconsole.log(gen.next()); // { value: 4, done: false }\nconsole.log(gen.next()); // { value: 5, done: false }\nconsole.log(gen.next()); // { value: undefined, done: true }\n```\n\n生成器对于按需创建迭代器非常强大，尤其适用于无限序列或复杂的迭代逻辑。它们可用于：\n\n* 惰性求值 – 仅在需要时处理元素，提高大型数据集的内存效率。\n* 为自定义数据结构实现迭代器。\n* 创建异步迭代器以处理数据流。\n\n***\n\n## 迭代器\n\n迭代器是定义序列并提供 `next()` 方法以访问序列中下一个值的对象。它们用于迭代 `数组`、`字符串` 和自定义 `对象` 等数据结构。迭代器的主要用例包括：\n\n* 实现迭代器协议以使自定义对象可迭代，允许它们与 `for...of` 循环和其他期望可迭代对象的语言结构一起使用。\n* 提供一种标准方式来迭代不同的数据结构，使代码更具可重用性和可维护性。\n\n### 为数字范围创建自定义迭代器\n\n在 JavaScript 中，我们可以通过在任何自定义对象中实现 `[Symbol.iterator]()` 来为迭代器提供默认实现。\n\n```js live\n// 定义一个名为 Range 的类\nclass Range {\n  // 构造函数接受两个参数：start 和 end\n  constructor(start, end) {\n    // 将 start 和 end 值分配给实例\n    this.start = start;\n    this.end = end;\n  }\n\n  // 定义对象的默认迭代器\n  [Symbol.iterator]() {\n    // 将当前值初始化为起始值\n    let current = this.start;\n    const end = this.end;\n\n    // 返回一个带有 next 方法的对象\n    return {\n      // next 方法返回迭代中的下一个值\n      next() {\n        // 如果当前值小于或等于结束值...\n        if (current <= end) {\n          // ...返回一个带有当前值和 done 设置为 false 的对象\n          return { value: current++, done: false };\n        }\n\n        // ...否则，返回一个 value 设置为 undefined 且 done 设置为 true 的对象\n        return { value: undefined, done: true };\n      },\n    };\n  }\n}\n\n// 创建一个 start = 1 且 end = 3 的新 Range 对象\nconst range = new Range(1, 3);\n// 迭代 range 对象\nfor (const number of range) {\n  // 将每个数字记录到控制台\n  console.log(number); // 1, 2, 3\n}\n```\n\n### 使用迭代器协议的内置对象\n\n在 JavaScript 中，几个内置对象实现了迭代器协议，这意味着它们具有默认的 `@@iterator` 方法。这使得它们可以在 `for...of` 循环和扩展运算符等结构中使用。以下是实现迭代器的一些关键内置对象：\n\n1. **数组**：数组具有内置的迭代器，允许您遍历其元素。\n\n   ```js live\n   const array = [1, 2, 3];\n   const iterator = array[Symbol.iterator]();\n\n   console.log(iterator.next()); // { value: 1, done: false }\n   console.log(iterator.next()); // { value: 2, done: false }\n   console.log(iterator.next()); // { value: 3, done: false }\n   console.log(iterator.next()); // { value: undefined, done: true }\n\n   for (const value of array) {\n     console.log(value); // Logs 1, 2, 3\n   }\n   ```\n\n2. **字符串**：字符串具有内置的迭代器，允许您遍历其字符。\n\n   ```js live\n   const string = 'hello';\n   const iterator = string[Symbol.iterator]();\n\n   console.log(iterator.next()); // { value: \"h\", done: false }\n   console.log(iterator.next()); // { value: \"e\", done: false }\n   console.log(iterator.next()); // { value: \"l\", done: false }\n   console.log(iterator.next()); // { value: \"l\", done: false }\n   console.log(iterator.next()); // { value: \"o\", done: false }\n   console.log(iterator.next()); // { value: undefined, done: true }\n\n   for (const char of string) {\n     console.log(char); // Logs h, e, l, l, o\n   }\n   ```\n\n3. **DOM NodeLists**\n\n   ```js live\n   // Create a new div and append it to the DOM\n   const newDiv = document.createElement('div');\n   newDiv.id = 'div1';\n   document.body.appendChild(newDiv);\n\n   const nodeList = document.querySelectorAll('div');\n   const iterator = nodeList[Symbol.iterator]();\n\n   console.log(iterator.next()); // { value: HTMLDivElement, done: false }\n   console.log(iterator.next()); // { value: undefined, done: true }\n\n   for (const node of nodeList) {\n     console.log(node); // Logs each <div> element, in this case only div1\n   }\n   ```\n\n`Map` 和 `Set` 也有内置的迭代器。\n\n## 生成器\n\n生成器是一种特殊的函数，可以暂停和恢复其执行，允许它们动态生成一系列值。它们通常用于创建迭代器，但也有其他应用。生成器的主要用例包括：\n\n* 与手动实现迭代器协议相比，以更简洁易读的方式创建迭代器。\n* 实现惰性求值，仅在需要时生成值，从而节省内存和计算时间。\n* 通过使用 `yield` 和 `await` 以同步风格编写代码，简化异步编程。\n\n生成器提供了一些好处：\n\n* **惰性求值**：它们动态生成值，并且仅在需要时才生成，这可以提高内存效率。\n* **暂停和恢复**：生成器可以暂停执行（通过 `yield`），并且可以在恢复时接收新数据。\n* **异步迭代**：随着 `async/await` 的出现，生成器可用于管理异步数据流。\n\n### 使用生成器函数创建迭代器\n\n我们可以重写我们的 `Range` 示例以使用生成器函数：\n\n```js live\n// Define a class named Range\nclass Range {\n  // The constructor takes two parameters: start and end\n  constructor(start, end) {\n    // Assign the start and end values to the instance\n    this.start = start;\n    this.end = end;\n  }\n\n  // Define the default iterator for the object using a generator\n  *[Symbol.iterator]() {\n    // Initialize the current value to the start value\n    let current = this.start;\n\n    // While the current value is less than or equal to the end value...\n    while (current <= this.end) {\n      // ...yield the current value\n      yield current++;\n    }\n  }\n}\n\n// Create a new Range object with start = 1 and end = 3\nconst range = new Range(1, 3);\n// Iterate over the range object\nfor (const number of range) {\n  // Log each number to the console\n  console.log(number); // 1, 2, 3\n}\n```\n\n### 迭代数据流\n\n生成器非常适合迭代数据流，例如从 API 获取数据或读取文件。此示例演示了如何使用生成器分批从 API 获取数据：\n\n```js live\nasync function* fetchDataInBatches(url, numBatches = 5, batchSize = 10) {\n  let startIndex = 0;\n  let currBatch = 0;\n\n  while (currBatch < numBatches) {\n    const response = await fetch(\n      `${url}?_start=${startIndex}&_limit=${batchSize}`,\n    );\n    const data = await response.json();\n    if (data.length === 0) break;\n    yield data;\n    startIndex += batchSize;\n    currBatch += 1;\n  }\n}\n\nasync function fetchAndLogData() {\n  const dataGenerator = fetchDataInBatches(\n    'https://jsonplaceholder.typicode.com/todos',\n  );\n\n  for await (const batch of dataGenerator) {\n    console.log(batch);\n  }\n}\nfetchAndLogData();\n```\n\n此生成器函数 `fetchDataInBatches` 以指定大小的批次从 API 获取数据。它产生每批数据，允许您在获取下一批数据之前对其进行处理。这种方法可以比一次获取所有数据更节省内存。\n\n#### 实现异步迭代器\n\n生成器可用于实现异步迭代器，这对于处理异步数据源很有用。此示例演示了用于从 API 获取数据的异步迭代器：\n\n```js live\nasync function* fetchDataAsyncIterator(url, pagesToFetch = 3) {\n  let currPage = 1;\n\n  while (currPage <= pagesToFetch) {\n    const response = await fetch(`${url}?_page=${currPage}`);\n    const data = await response.json();\n    if (data.length === 0) break;\n    yield data;\n    currPage++;\n  }\n}\n\nasync function fetchAndLogData() {\n  const asyncIterator = fetchDataAsyncIterator(\n    'https://jsonplaceholder.typicode.com/todos',\n  );\n\n  for await (const chunk of asyncIterator) {\n    console.log(chunk);\n  }\n}\nfetchAndLogData();\n```\n\n生成器函数 `fetchDataAsyncIterator` 是一个异步迭代器，它从 API 中分页获取数据。它产生每页数据，允许您在获取下一页之前对其进行处理。这种方法对于处理大型数据集或长时间运行的操作很有用。\n\n生成器也广泛用于 JavaScript 库和框架中，例如 [Redux-Saga](https://redux-saga.js.org/) 和 [RxJS](https://rxjs.dev/)，用于处理异步操作和响应式编程。\n\n## 总结\n\n迭代器和生成器提供了一种强大而灵活的方式来处理 JavaScript 中的数据集合。 迭代器定义了一种遍历数据序列的标准化方式，而生成器提供了一种更具表现力和效率的方式来创建迭代器、处理异步操作以及组合复杂的数据管道。\n\n## 延伸阅读\n\n* [迭代器和生成器](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators)\n* [异步迭代和生成器](https://javascript.info/async-iterators-generators)\n* [可迭代对象](https://javascript.info/iterable)\n* [探索 JavaScript 中的迭代器和生成器](https://blog.bitsrc.io/explore-iterators-and-generators-in-javascript-ea4102015377)\n* [JavaScript 中的迭代器和生成器](https://syntactic-sugar.dev/blog/nested-route/iterators-and-generators)\n"
  },
  {
    "path": "questions/what-are-javascript-object-getters-and-setters-for/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"5c46612b\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3c1a0797\",\n        \"f096b232\",\n        \"8901ee67\",\n        \"f8497794\",\n        \"2a7816d0\",\n        \"30a45725\",\n        \"a9ee9d27\",\n        \"c90fcbb1\",\n        \"7e333bf2\",\n        \"411b1b57\",\n        \"1f177e65\",\n        \"6c75d18f\",\n        \"2a91e89e\",\n        \"1f4770e5\",\n        \"f989df10\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3c1a0797\",\n        \"f096b232\",\n        \"8901ee67\",\n        \"f8497794\",\n        \"2a7816d0\",\n        \"30a45725\",\n        \"a9ee9d27\",\n        \"c90fcbb1\",\n        \"7e333bf2\",\n        \"411b1b57\",\n        \"1f177e65\",\n        \"6c75d18f\",\n        \"2a91e89e\",\n        \"1f4770e5\",\n        \"f989df10\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-javascript-object-getters-and-setters-for/en-US.mdx",
    "content": "---\ntitle: What are JavaScript object getters and setters for?\n---\n\n## TL;DR\n\nJavaScript object getters and setters are used to control access to an object's properties. They provide a way to encapsulate the implementation details of a property and define custom behavior when getting or setting its value.\n\nGetters and setters are defined using the `get` and `set` keywords, respectively, followed by a function that is executed when the property is accessed or assigned a new value.\n\nHere's a code example demonstrating the use of getters and setters:\n\n```js live\nconst person = {\n  _name: 'John Doe', // Private property\n\n  get name() {\n    // Getter\n    return this._name;\n  },\n  set name(newName) {\n    // Setter\n    if (newName.trim().length > 0) {\n      this._name = newName;\n    } else {\n      console.log('Invalid name');\n    }\n  },\n};\n\n// Accessing the name property using the getter\nconsole.log(person.name); // Output: 'John Doe'\n\n// Setting the name property using the setter\nperson.name = 'Jane Smith'; // Setter is called\nconsole.log(person.name); // Output: 'Jane Smith'\n\nperson.name = ''; // Setter is called, but the value is not set due to validation\nconsole.log(person.name); // Output: 'Jane Smith'\n```\n\n---\n\n## JavaScript object getters and setters\n\nIn JavaScript, getters and setters are special methods that allow you to control how properties of an object are accessed and modified.\n\n- **Getters**: Functions that are invoked whenever you try to access a property using dot notation (e.g., `obj.name`). They provide a way to customize the value that is returned when the property is read.\n- **Setters**: Functions that are called when you try to assign a value to a property using dot notation with the assignment operator (e.g., `obj.name = \"John\"`). They allow you to perform actions like data validation, formatting, or side effects before the actual value is stored in the object.\n\n```js live\nconst person = {\n  _firstName: 'John',\n  _lastName: 'Doe',\n  get fullName() {\n    return `${this._firstName} ${this._lastName}`;\n  },\n  set fullName(value) {\n    const parts = value.split(' ');\n    this._firstName = parts[0];\n    this._lastName = parts[1];\n  },\n};\n\nconsole.log(person.fullName); // Output: John Doe\nperson.fullName = 'Jane Smith';\nconsole.log(person.fullName); // Output: Jane Smith\n```\n\nIn this example, the `fullName` property doesn't have a direct value stored in the object. The getter function calculates it by combining the `_firstName` and `_lastName` properties. The setter splits the assigned value into first and last names and updates the internal properties accordingly.\n\n## Benefits\n\nGetters and setters provide several benefits:\n\n1. **Encapsulation**: They allow you to encapsulate the implementation details of a property, making it easier to change the internal representation without affecting external code that uses the property.\n1. **Data validation**: Setters can be used to validate the values being assigned to a property, ensuring data integrity and consistency.\n1. **Computed Properties**: Getters can be used to compute and return a derived value based on other properties or calculations.\n1. **Side effects**: Setters can be used to perform side effects when a property is changed. For example, you might update a related property or trigger an action when a specific value is assigned/modified, such as logging or debugging.\n\n## Further reading\n\n- [Object.defineProperty() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)\n- [Property flags and descriptors | Javascript.info](https://javascript.info/property-descriptors)\n- [Object.seal() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)\n"
  },
  {
    "path": "questions/what-are-javascript-object-getters-and-setters-for/metadata.json",
    "content": "{\n  \"slug\": \"what-are-javascript-object-getters-and-setters-for\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 460,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-javascript-object-getters-and-setters-for/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 对象 getter 和 setter 有什么用？\n---\n\n## TL;DR\n\nJavaScript 对象 getter 和 setter 用于控制对对象属性的访问。它们提供了一种封装属性的实现细节，并在获取或设置其值时定义自定义行为的方法。\n\nGetters 和 setters 分别使用 `get` 和 `set` 关键字定义，后跟一个在访问属性或为其分配新值时执行的函数。\n\n以下是一个代码示例，演示了 getter 和 setter 的用法：\n\n```js live\nconst person = {\n  _name: 'John Doe', // 私有属性\n\n  get name() {\n    // Getter\n    return this._name;\n  },\n  set name(newName) {\n    // Setter\n    if (newName.trim().length > 0) {\n      this._name = newName;\n    } else {\n      console.log('Invalid name');\n    }\n  },\n};\n\n// 使用 getter 访问 name 属性\nconsole.log(person.name); // 输出：'John Doe'\n\n// 使用 setter 设置 name 属性\nperson.name = 'Jane Smith'; // 调用 Setter\nconsole.log(person.name); // 输出：'Jane Smith'\n\nperson.name = ''; // 调用 Setter，但由于验证，该值未设置\nconsole.log(person.name); // 输出：'Jane Smith'\n```\n\n***\n\n## JavaScript 对象 getter 和 setter\n\n在 JavaScript 中，getter 和 setter 是特殊的方法，允许您控制如何访问和修改对象的属性。\n\n* **Getters**：每当您尝试使用点表示法（例如，`obj.name`）访问属性时调用的函数。它们提供了一种自定义在读取属性时返回的值的方法。\n* **Setters**：当您尝试使用点表示法和赋值运算符（例如，`obj.name = \"John\"`）为属性赋值时调用的函数。它们允许您在将实际值存储在对象中之前执行数据验证、格式化或副作用等操作。\n\n```js live\nconst person = {\n  _firstName: 'John',\n  _lastName: 'Doe',\n  get fullName() {\n    return `${this._firstName} ${this._lastName}`;\n  },\n  set fullName(value) {\n    const parts = value.split(' ');\n    this._firstName = parts[0];\n    this._lastName = parts[1];\n  },\n};\n\nconsole.log(person.fullName); // 输出：John Doe\nperson.fullName = 'Jane Smith';\nconsole.log(person.fullName); // 输出：Jane Smith\n```\n\n在此示例中，`fullName` 属性没有直接存储在对象中的值。getter 函数通过组合 `_firstName` 和 `_lastName` 属性来计算它。setter 将分配的值拆分为名字和姓氏，并相应地更新内部属性。\n\n## 优点\n\nGetters 和 setters 提供了几个好处：\n\n1. **封装**：它们允许您封装属性的实现细节，从而更容易更改内部表示，而不会影响使用该属性的外部代码。\n2. **数据验证**：Setters 可用于验证分配给属性的值，确保数据完整性和一致性。\n3. **计算属性**：Getters 可用于计算并返回基于其他属性或计算的派生值。\n4. **副作用**：当属性更改时，Setters 可用于执行副作用。例如，您可能更新相关属性或在分配/修改特定值时触发操作，例如日志记录或调试。\n\n## 延伸阅读\n\n* [Object.defineProperty() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)\n* [Property flags and descriptors | Javascript.info](https://javascript.info/property-descriptors)\n* [Object.seal() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)\n"
  },
  {
    "path": "questions/what-are-javascript-object-property-flags-and-descriptors/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"233e36c7\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3bda0651\",\n        \"d74435c6\",\n        \"46295349\",\n        \"e715da72\",\n        \"5a6b18\",\n        \"9ba6b014\",\n        \"4d07e1e6\",\n        \"afa1c512\",\n        \"2a7816d0\",\n        \"717ba9b1\",\n        \"a7a3aa55\",\n        \"c9424fb8\",\n        \"9f62c70a\",\n        \"e715da72\",\n        \"a4aa0e23\",\n        \"a3b2613d\",\n        \"96037145\",\n        \"8f608957\",\n        \"9806536d\",\n        \"782fdbb\",\n        \"c47e9be6\",\n        \"d19a9609\",\n        \"e82f6a63\",\n        \"4f1379f7\",\n        \"a46fd8c3\",\n        \"4d560494\",\n        \"87d56d21\",\n        \"1c1c834d\",\n        \"42cfe6b9\",\n        \"1f4770e5\",\n        \"f989df10\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3bda0651\",\n        \"d74435c6\",\n        \"46295349\",\n        \"e715da72\",\n        \"5a6b18\",\n        \"9ba6b014\",\n        \"4d07e1e6\",\n        \"afa1c512\",\n        \"2a7816d0\",\n        \"717ba9b1\",\n        \"a7a3aa55\",\n        \"c9424fb8\",\n        \"9f62c70a\",\n        \"e715da72\",\n        \"a4aa0e23\",\n        \"a3b2613d\",\n        \"96037145\",\n        \"8f608957\",\n        \"9806536d\",\n        \"782fdbb\",\n        \"c47e9be6\",\n        \"d19a9609\",\n        \"e82f6a63\",\n        \"4f1379f7\",\n        \"a46fd8c3\",\n        \"4d560494\",\n        \"87d56d21\",\n        \"1c1c834d\",\n        \"42cfe6b9\",\n        \"1f4770e5\",\n        \"f989df10\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-javascript-object-property-flags-and-descriptors/en-US.mdx",
    "content": "---\ntitle: What are JavaScript object property flags and descriptors?\n---\n\n## TL;DR\n\nIn JavaScript, property flags and descriptors manage the behavior and attributes of object properties.\n\n**Property flags**\n\nProperty flags are used to specify the behavior of a property on an object. Here are the available flags:\n\n- `writable`: Specifies whether the property can be written to. Defaults to `true`.\n- `enumerable`: Specifies whether the property is enumerable. Defaults to `true`.\n- `configurable`: Specifies whether the property can be deleted or its attributes changed. Default is `true`.\n\n**Property descriptors**\n\nThese provide detailed information about an object's property, including its value and flags. They are retrieved using `Object.getOwnPropertyDescriptor()` and set using `Object.defineProperty()`.\n\nThe use cases of property descriptors are as follows:\n\n- Making a property non-writable by setting `writable: false` to ensure data consistency.\n- Hiding a property from enumeration by setting `enumerable: false`.\n- Preventing property deletion and modification by setting `configurable: false`.\n- Freezing or sealing objects to prevent modifications globally.\n\n---\n\n## JavaScript object property flags and descriptors\n\nIn JavaScript, property flags and descriptors are used to manage the behavior and attributes of object properties. These flags and descriptors are essential for understanding how properties are accessed, modified, and inherited.\n\n## Property flags\n\nProperty flags are used to specify the behavior of a property. They are set using the `Object.defineProperty()` method, which allows you to define a property on an object with specific attributes. The available property flags are:\n\n- `writable`: Specifies whether the property can be written to. Defaults to `true`.\n- `enumerable`: Specifies whether the property is enumerable. Defaults to `true`.\n- `configurable`: Specifies whether the property can be deleted or its attributes changed. Default is `true`.\n\n## Property descriptors\n\nProperty descriptors provide detailed information about an object's property, encapsulating its value and flags. They are retrieved using `Object.getOwnPropertyDescriptor()` and set using `Object.defineProperty()`\n\n```js live\nlet user = { name: 'John Doe' };\nlet descriptor = Object.getOwnPropertyDescriptor(user, 'name');\n\nconsole.log(descriptor); // {value: \"John Doe\", writable: true, enumerable: true, configurable: true}\n```\n\n## Manipulating property flags\n\n### `writable` flag\n\nThe `writable` flag specifies whether a property can be written to. When `writable` is `false`, trying to assign value to the property fails silently in non-strict mode, and it throws a `TypeError` in strict mode.\n\n```js live\nconst obj = {};\n\nObject.defineProperty(obj, 'name', {\n  writable: false,\n  value: 'John Doe',\n});\n\nconsole.log(obj.name); // Output: John Doe\nobj.name = 'Jane Doe'; // This does not change name. Generates TypeError in strict mode\nconsole.log(obj.name); // Output: John Doe (unchanged)\n```\n\n### `enumerable` flag\n\nThe `enumerable` flag specifies whether a property is enumerable. The `enumerable flag` is set to `true`, which means the property is visible in a `for...in` loop.\n\n```js live\nconst obj = {};\n\nObject.defineProperty(obj, 'name', {\n  enumerable: false,\n  value: 'John Doe',\n});\n\nfor (const prop in obj) {\n  console.log(prop); // Output: nothing\n}\n\nconst obj1 = {};\n\nObject.defineProperty(obj1, 'name', {\n  enumerable: true,\n  value: 'John Doe',\n});\n\nfor (const prop in obj1) {\n  console.log(prop); // Output: name\n}\n```\n\n## `configurable` flag\n\nThe `configurable` flag specifies whether a property can be deleted or its attributes changed. When `configurable` is `false`, trying to delete or change the property fails silently in non-strict mode, and it throws a `TypeError` in strict mode.\n\n```js live\nconst obj = {};\n\nObject.defineProperty(obj, 'name', {\n  configurable: false,\n  value: 'John Doe',\n});\n\ndelete obj.name; // Does not delete property. Generates TypeError in strict mode\nconsole.log(obj.name); // Output: John Doe (not deleted)\n```\n\n## `Object.seal()`\n\nThe `Object.seal()` method in JavaScript effectively prevents the addition or removal of properties from the object, while still allowing the modification of existing property values. It also makes all properties non-configurable, meaning their descriptors (like `writable`, `enumerable`, and `configurable`) cannot be changed.\n\n## Further reading\n\n- [Object.defineProperty() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)\n- [Property flags and descriptors | Javascript.info](https://javascript.info/property-descriptors)\n- [Object.seal() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)\n"
  },
  {
    "path": "questions/what-are-javascript-object-property-flags-and-descriptors/metadata.json",
    "content": "{\n  \"slug\": \"what-are-javascript-object-property-flags-and-descriptors\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 450,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-javascript-object-property-flags-and-descriptors/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 对象属性标志和描述符是什么？\n---\n\n## TL;DR\n\n在 JavaScript 中，属性标志和描述符管理对象属性的行为和属性。\n\n**属性标志**\n\n属性标志用于指定对象上属性的行为。以下是可用的标志：\n\n* `writable`：指定是否可以写入属性。默认为 `true`。\n* `enumerable`：指定属性是否可枚举。默认为 `true`。\n* `configurable`：指定是否可以删除属性或更改其属性。默认为 `true`。\n\n**属性描述符**\n\n这些提供了关于对象属性的详细信息，包括其值和标志。它们使用 `Object.getOwnPropertyDescriptor()` 检索，并使用 `Object.defineProperty()` 设置。\n\n属性描述符的用例如下：\n\n* 通过设置 `writable: false` 使属性不可写，以确保数据一致性。\n* 通过设置 `enumerable: false` 隐藏属性，使其不被枚举。\n* 通过设置 `configurable: false` 阻止属性删除和修改。\n* 冻结或密封对象以防止全局修改。\n\n***\n\n## JavaScript 对象属性标志和描述符\n\n在 JavaScript 中，属性标志和描述符用于管理对象属性的行为和属性。这些标志和描述符对于理解如何访问、修改和继承属性至关重要。\n\n## 属性标志\n\n属性标志用于指定属性的行为。它们使用 `Object.defineProperty()` 方法设置，该方法允许您使用特定属性在对象上定义属性。可用的属性标志有：\n\n* `writable`：指定是否可以写入属性。默认为 `true`。\n* `enumerable`：指定属性是否可枚举。默认为 `true`。\n* `configurable`：指定是否可以删除属性或更改其属性。默认为 `true`。\n\n## 属性描述符\n\n属性描述符提供有关对象属性的详细信息，封装其值和标志。它们使用 `Object.getOwnPropertyDescriptor()` 检索，并使用 `Object.defineProperty()` 设置\n\n```js live\nlet user = { name: 'John Doe' };\nlet descriptor = Object.getOwnPropertyDescriptor(user, 'name');\n\nconsole.log(descriptor); // {value: \"John Doe\", writable: true, enumerable: true, configurable: true}\n```\n\n## 操纵属性标志\n\n### `writable` 标志\n\n`writable` 标志指定是否可以写入属性。当 `writable` 为 `false` 时，在非严格模式下尝试为该属性赋值会静默失败，而在严格模式下会抛出 `TypeError`。\n\n```js live\nconst obj = {};\n\nObject.defineProperty(obj, 'name', {\n  writable: false,\n  value: 'John Doe',\n});\n\nconsole.log(obj.name); // Output: John Doe\nobj.name = 'Jane Doe'; // This does not change name. Generates TypeError in strict mode\nconsole.log(obj.name); // Output: John Doe (unchanged)\n```\n\n### `enumerable` 标志\n\n`enumerable` 标志指定一个属性是否可枚举。`enumerable` 标志设置为 `true`，这意味着该属性在 `for...in` 循环中可见。\n\n```js live\nconst obj = {};\n\nObject.defineProperty(obj, 'name', {\n  enumerable: false,\n  value: 'John Doe',\n});\n\nfor (const prop in obj) {\n  console.log(prop); // Output: nothing\n}\n\nconst obj1 = {};\n\nObject.defineProperty(obj1, 'name', {\n  enumerable: true,\n  value: 'John Doe',\n});\n\nfor (const prop in obj1) {\n  console.log(prop); // Output: name\n}\n```\n\n## `configurable` 标志\n\n`configurable` 标志指定一个属性是否可以被删除或其属性是否可以被更改。当 `configurable` 为 `false` 时，在非严格模式下尝试删除或更改该属性会静默失败，而在严格模式下会抛出 `TypeError`。\n\n```js live\nconst obj = {};\n\nObject.defineProperty(obj, 'name', {\n  configurable: false,\n  value: 'John Doe',\n});\n\ndelete obj.name; // Does not delete property. Generates TypeError in strict mode\nconsole.log(obj.name); // Output: John Doe (not deleted)\n```\n\n## `Object.seal()`\n\nJavaScript 中的 `Object.seal()` 方法有效地阻止了向对象添加或删除属性，但仍然允许修改现有属性值。它还使所有属性变为不可配置，这意味着它们的描述符（如 `writable`、`enumerable` 和 `configurable`）无法更改。\n\n## 延伸阅读\n\n* [Object.defineProperty() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty)\n* [Property flags and descriptors | Javascript.info](https://javascript.info/property-descriptors)\n* [Object.seal() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)\n"
  },
  {
    "path": "questions/what-are-javascript-polyfills-for/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"e6181a69\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"30b924cf\",\n        \"6014f262\",\n        \"6c5bf15b\",\n        \"c5f93c97\",\n        \"f8d62d30\",\n        \"5cb33d95\",\n        \"2a7816d0\",\n        \"53cdde8\",\n        \"c7231b71\",\n        \"23d67c70\",\n        \"62e43a8f\",\n        \"44b3ebcf\",\n        \"eb0f191f\",\n        \"798b9972\",\n        \"f16e4aed\",\n        \"2a352a25\",\n        \"45df90e8\",\n        \"f82d827c\",\n        \"cd4edc9e\",\n        \"5cb33d95\",\n        \"1f4770e5\",\n        \"81dbf527\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"30b924cf\",\n        \"6014f262\",\n        \"6c5bf15b\",\n        \"c5f93c97\",\n        \"f8d62d30\",\n        \"5cb33d95\",\n        \"2a7816d0\",\n        \"53cdde8\",\n        \"c7231b71\",\n        \"23d67c70\",\n        \"62e43a8f\",\n        \"44b3ebcf\",\n        \"eb0f191f\",\n        \"798b9972\",\n        \"f16e4aed\",\n        \"2a352a25\",\n        \"45df90e8\",\n        \"f82d827c\",\n        \"cd4edc9e\",\n        \"5cb33d95\",\n        \"1f4770e5\",\n        \"81dbf527\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-javascript-polyfills-for/en-US.mdx",
    "content": "---\ntitle: What are JavaScript polyfills for?\n---\n\n## TL;DR\n\nPolyfills in JavaScript are pieces of code that provide modern functionality to older browsers that lack native support for those features. They bridge the gap between the JavaScript language features and APIs available in modern browsers and the limited capabilities of older browser versions.\n\nThey can be implemented manually or included through libraries and are often used in conjunction with feature detection.\n\nCommon use cases include:\n\n- **New JavaScript Methods**: For example, `Array.prototype.includes()`, `Object.assign()`, etc.\n- **New APIs**: Such as `fetch()`, `Promise`, `IntersectionObserver`, etc. Modern browsers support these now but for a long time they have to be polyfilled.\n\nLibraries and services for polyfills:\n\n- **`core-js`**: A modular standard library for JavaScript which includes polyfills for a wide range of ECMAScript features.\n\n  ```js\n  import 'core-js/actual/array/flat-map'; // With this, Array.prototype.flatMap is available to be used.\n\n  [1, 2].flatMap((it) => [it, it]); // => [1, 1, 2, 2]\n  ```\n\n- **Polyfill.io**: A service that provides polyfills based on the features and user agents specified in the request.\n\n  ```js\n  <script src=\"https://polyfill.io/v3/polyfill.min.js\"></script>\n  ```\n\n---\n\n## Polyfills in JavaScript\n\nPolyfills in JavaScript are pieces of code (usually JavaScript) that provide modern functionality on older browsers that do not natively support it. They enable developers to use newer features of the language and APIs while maintaining compatibility with older environments.\n\n## How polyfills work\n\nPolyfills detect if a feature or API is missing in a browser and provide a custom implementation of that feature using existing JavaScript capabilities. This allows developers to write code using the latest JavaScript features and APIs without worrying about browser compatibility issues.\n\nFor example, let's consider the `Array.prototype.includes()` method, which determines if an array includes a specific element. This method is not supported in older browsers like Internet Explorer 11. To address this, we can use a polyfill:\n\n```js live\n// Polyfill for Array.prototype.includes()\nif (!Array.prototype.includes) {\n  Array.prototype.includes = function (searchElement) {\n    for (var i = 0; i < this.length; i++) {\n      if (this[i] === searchElement) {\n        return true;\n      }\n    }\n\n    return false;\n  };\n}\n\nconsole.log([1, 2, 3].includes(2)); // true\nconsole.log([1, 2, 3].includes(4)); // false\n```\n\nBy including this polyfill, we can safely use `Array.prototype.includes()` even in browsers that don't support it natively.\n\n## Implementing polyfills\n\n1. **Identify the missing feature**: Determine if the feature is compatible with the target browsers or detect its presence using feature detection methods like `typeof`, `in`, or `window`.\n1. **Write the fallback implementation**: Develop the fallback implementation that provides similar functionality, either using a pre-existing polyfill library or pure JavaScript code.\n1. **Test the polyfill**: Thoroughly test the polyfill to ensure it functions as intended across different contexts and browsers.\n1. **Implement the polyfill**: Enclose the code that uses the missing feature in an if statement that checks for feature support. If not supported, run the polyfill code instead.\n\n### Considerations\n\n- **Selective loading**: Polyfills should only be loaded for browsers that need them to optimize performance.\n- **Feature detection**: Perform feature detection before applying a polyfill to avoid overwriting native implementations or applying unnecessary polyfills.\n- **Size and performance**: Polyfills can increase the JavaScript bundle size, so minification and compression techniques should be used to mitigate this impact.\n- **Existing libraries**: Consider using existing libraries and tools that offer comprehensive polyfill solutions for multiple features, handling feature detection, conditional loading, and fallbacks efficiently\n\n### Libraries and services for polyfills\n\n- **`core-js`**: A modular standard library for JavaScript which includes polyfills for a wide range of ECMAScript features.\n\n  ```js\n  import 'core-js/actual/array/flat-map'; // With this, Array.prototype.flatMap is available to be used.\n\n  [1, 2].flatMap((it) => [it, it]); // => [1, 1, 2, 2]\n  ```\n\n- **Polyfill.io**: A service that provides polyfills based on the features and user agents specified in the request.\n\n  ```js\n  <script src=\"https://polyfill.io/v3/polyfill.min.js\"></script>\n  ```\n\n## Further reading\n\n- [Polyfill - MDN](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill)\n- [Polyfills and transpilers](https://javascript.info/polyfills)\n- [Polyfills: How do they work?](https://medium.com/alienbrains/polyfills-how-do-they-work-ea6a12b792b)\n- [Polyfill in Javascript](https://www.linkedin.com/pulse/polyfill-javascript-divyansh-singh)\n- [Shubham Dutta](https://dev.to/shubhamdutta2000/polyfills-for-javascript-a-full-overview-3f7m)\n"
  },
  {
    "path": "questions/what-are-javascript-polyfills-for/metadata.json",
    "content": "{\n  \"slug\": \"what-are-javascript-polyfills-for\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 310,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-javascript-polyfills-for/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 的 Polyfill 是什么？\n---\n\n## TL;DR\n\nJavaScript 中的 Polyfill 是一段代码，它为较旧的浏览器提供现代功能，而这些浏览器本身并不原生支持这些功能。它们弥合了现代浏览器中可用的 JavaScript 语言特性和 API 与旧版本浏览器有限功能之间的差距。\n\n它们可以手动实现或通过库引入，并且通常与功能检测结合使用。\n\n常见用例包括：\n\n* **新的 JavaScript 方法**：例如，`Array.prototype.includes()`、`Object.assign()` 等。\n* **新的 API**：例如 `fetch()`、`Promise`、`IntersectionObserver` 等。现代浏览器现在支持这些，但很长一段时间内它们必须被 polyfilled。\n\n用于 polyfill 的库和服务：\n\n* **`core-js`**：一个用于 JavaScript 的模块化标准库，其中包括各种 ECMAScript 特性的 polyfill。\n\n  ```js\n  import 'core-js/actual/array/flat-map'; // With this, Array.prototype.flatMap is available to be used.\n\n  [1, 2].flatMap((it) => [it, it]); // => [1, 1, 2, 2]\n  ```\n\n* **Polyfill.io**：一项服务，根据请求中指定的功能和用户代理提供 polyfill。\n\n  ```js\n  <script src=\"https://polyfill.io/v3/polyfill.min.js\"></script>\n  ```\n\n***\n\n## JavaScript 中的 Polyfill\n\nJavaScript 中的 Polyfill 是一段代码（通常是 JavaScript），它在较旧的浏览器上提供现代功能，而这些浏览器本身并不原生支持这些功能。它们使开发人员能够使用该语言和 API 的较新功能，同时保持与旧环境的兼容性。\n\n## Polyfill 的工作原理\n\nPolyfill 检测浏览器中是否缺少某个功能或 API，并使用现有的 JavaScript 功能提供该功能的自定义实现。这使开发人员能够使用最新的 JavaScript 功能和 API 编写代码，而无需担心浏览器兼容性问题。\n\n例如，让我们考虑一下 `Array.prototype.includes()` 方法，该方法确定数组是否包含特定元素。较旧的浏览器（如 Internet Explorer 11）不支持此方法。为了解决这个问题，我们可以使用 polyfill：\n\n```js live\n// Polyfill for Array.prototype.includes()\nif (!Array.prototype.includes) {\n  Array.prototype.includes = function (searchElement) {\n    for (var i = 0; i < this.length; i++) {\n      if (this[i] === searchElement) {\n        return true;\n      }\n    }\n\n    return false;\n  };\n}\n\nconsole.log([1, 2, 3].includes(2)); // true\nconsole.log([1, 2, 3].includes(4)); // false\n```\n\n通过包含此 polyfill，即使在原生不支持它的浏览器中，我们也可以安全地使用 `Array.prototype.includes()`。\n\n## 实现 polyfill\n\n1. **确定缺失的功能**：确定该功能是否与目标浏览器兼容，或使用 `typeof`、`in` 或 `window` 等功能检测方法检测其是否存在。\n2. **编写后备实现**：开发提供类似功能的后备实现，可以使用预先存在的 polyfill 库或纯 JavaScript 代码。\n3. **测试 polyfill**：彻底测试 polyfill，以确保它在不同的上下文和浏览器中按预期运行。\n4. **实现 polyfill**：将使用缺失功能的代码包含在 if 语句中，该语句检查功能支持。如果不支持，则运行 polyfill 代码。\n\n### 考虑事项\n\n* **选择性加载**：polyfill 应该仅针对需要它们的浏览器加载，以优化性能。\n* **功能检测**：在应用 polyfill 之前执行功能检测，以避免覆盖原生实现或应用不必要的 polyfill。\n* **大小和性能**：polyfill 可能会增加 JavaScript 捆绑包的大小，因此应使用缩小和压缩技术来减轻这种影响。\n* **现有库**：考虑使用现有的库和工具，这些库和工具为多个功能提供全面的 polyfill 解决方案，有效地处理功能检测、条件加载和后备\n\n### 用于 polyfill 的库和服务\n\n* **`core-js`**：一个用于 JavaScript 的模块化标准库，其中包括各种 ECMAScript 特性的 polyfill。\n\n  ```js\n  import 'core-js/actual/array/flat-map'; // With this, Array.prototype.flatMap is available to be used.\n\n  [1, 2].flatMap((it) => [it, it]); // => [1, 1, 2, 2]\n  ```\n\n* **Polyfill.io**：一项服务，根据请求中指定的功能和用户代理提供 polyfill。\n\n  ```js\n  <script src=\"https://polyfill.io/v3/polyfill.min.js\"></script>\n  ```\n\n## 延伸阅读\n\n* [Polyfill - MDN](https://developer.mozilla.org/en-US/docs/Glossary/Polyfill)\n* [Polyfills and transpilers](https://javascript.info/polyfills)\n* [Polyfills: How do they work?](https://medium.com/alienbrains/polyfills-how-do-they-work-ea6a12b792b)\n* [Polyfill in Javascript](https://www.linkedin.com/pulse/polyfill-javascript-divyansh-singh)\n* [Shubham Dutta](https://dev.to/shubhamdutta2000/polyfills-for-javascript-a-full-overview-3f7m)\n"
  },
  {
    "path": "questions/what-are-mocks-and-stubs-and-how-are-they-used-in-testing/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"6b1c69bb\",\n        \"2a7816d0\",\n        \"c7180174\",\n        \"8ac4729d\",\n        \"db5f2029\",\n        \"748ffe75\",\n        \"6ab5ecbf\",\n        \"74edc431\",\n        \"5740dba6\",\n        \"748ffe75\",\n        \"3d044d6e\",\n        \"a014c83\",\n        \"622fba73\",\n        \"1f4770e5\",\n        \"f64b2215\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"6b1c69bb\",\n        \"2a7816d0\",\n        \"c7180174\",\n        \"8ac4729d\",\n        \"db5f2029\",\n        \"748ffe75\",\n        \"6ab5ecbf\",\n        \"74edc431\",\n        \"5740dba6\",\n        \"748ffe75\",\n        \"3d044d6e\",\n        \"a014c83\",\n        \"622fba73\",\n        \"1f4770e5\",\n        \"f64b2215\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"ee245e83\"\n  }\n}\n"
  },
  {
    "path": "questions/what-are-mocks-and-stubs-and-how-are-they-used-in-testing/en-US.mdx",
    "content": "---\ntitle: What are mocks and stubs and how are they used in testing?\n---\n\n## TL;DR\n\nMocks and stubs are tools used in testing to simulate the behavior of real objects. Stubs provide predefined responses to function calls, while mocks are more complex and can verify interactions, such as whether a function was called and with what arguments. Stubs are used to isolate the code being tested from external dependencies, and mocks are used to ensure that the code interacts correctly with those dependencies.\n\n---\n\n## What are mocks and stubs and how are they used in testing?\n\n### Stubs\n\nStubs are simple objects that provide predefined responses to function calls made during tests. They are used to isolate the code being tested from external dependencies, such as databases or APIs, by providing controlled responses.\n\n#### Example\n\n```js\n// A simple stub for a function that fetches user data\nconst fetchUserDataStub = sinon.stub();\nfetchUserDataStub.returns({ id: 1, name: 'John Doe' });\n\n// Using the stub in a test\nconst userData = fetchUserDataStub();\nconsole.log(userData); // { id: 1, name: 'John Doe' }\n```\n\n### Mocks\n\nMocks are more complex than stubs. They not only provide predefined responses but also record information about how they were called. This allows you to verify interactions, such as whether a function was called, how many times it was called, and with what arguments.\n\n#### Example\n\n```js\n// A simple mock for a function that logs user data\nconst logUserDataMock = sinon.mock();\nlogUserDataMock.expects('log').once().withArgs({ id: 1, name: 'John Doe' });\n\n// Using the mock in a test\nlogUserDataMock.log({ id: 1, name: 'John Doe' });\nlogUserDataMock.verify(); // Verifies that the log method was called once with the specified arguments\n```\n\n### When to use stubs and mocks\n\n- **Stubs**: Use stubs when you need to isolate the code being tested from external dependencies and control the responses those dependencies provide.\n- **Mocks**: Use mocks when you need to verify that the code interacts correctly with external dependencies, such as ensuring that a function is called with the correct arguments.\n\n## Further reading\n\n- [Sinon.js documentation](https://sinonjs.org/releases/latest/)\n- [Mocks Aren't Stubs](https://martinfowler.com/articles/mocksArentStubs.html) by Martin Fowler\n- [Sinon Tutorial: JavaScript Testing with Mocks, Spies & Stubs](https://www.sitepoint.com/sinon-tutorial-javascript-testing-mocks-spies-stubs/) on SitePoint\n"
  },
  {
    "path": "questions/what-are-mocks-and-stubs-and-how-are-they-used-in-testing/metadata.json",
    "content": "{\n  \"slug\": \"what-are-mocks-and-stubs-and-how-are-they-used-in-testing\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"advanced\",\n  \"topics\": [\"javascript\", \"testing\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Testing\"\n}\n"
  },
  {
    "path": "questions/what-are-mocks-and-stubs-and-how-are-they-used-in-testing/zh-CN.mdx",
    "content": "---\ntitle: 什么是模拟和存根，以及它们在测试中如何使用？\n---\n\n## TL;DR\n\n模拟和存根是用于测试的工具，用于模拟真实对象的行为。存根为函数调用提供预定义的响应，而模拟更复杂，可以验证交互，例如是否调用了函数以及使用什么参数。存根用于将正在测试的代码与外部依赖项隔离，而模拟用于确保代码与这些依赖项正确交互。\n\n***\n\n## 什么是模拟和存根，以及它们在测试中如何使用？\n\n### 存根\n\n存根是简单的对象，它们为测试期间进行的函数调用提供预定义的响应。它们用于通过提供受控响应来将正在测试的代码与外部依赖项（例如数据库或 API）隔离。\n\n#### 示例\n\n```js\n// 一个用于获取用户数据的函数的简单存根\nconst fetchUserDataStub = sinon.stub();\nfetchUserDataStub.returns({ id: 1, name: 'John Doe' });\n\n// 在测试中使用存根\nconst userData = fetchUserDataStub();\nconsole.log(userData); // { id: 1, name: 'John Doe' }\n```\n\n### 模拟\n\n模拟比存根更复杂。它们不仅提供预定义的响应，还记录有关如何调用它们的信息。这使您可以验证交互，例如是否调用了函数、调用了多少次以及使用什么参数。\n\n#### 示例\n\n```js\n// 一个用于记录用户数据的函数的简单模拟\nconst logUserDataMock = sinon.mock();\nlogUserDataMock.expects('log').once().withArgs({ id: 1, name: 'John Doe' });\n\n// 在测试中使用模拟\nlogUserDataMock.log({ id: 1, name: 'John Doe' });\nlogUserDataMock.verify(); // 验证 log 方法是否使用指定的参数调用了一次\n```\n\n### 何时使用存根和模拟\n\n* **存根**：当您需要将正在测试的代码与外部依赖项隔离并控制这些依赖项提供的响应时，请使用存根。\n* **模拟**：当您需要验证代码是否与外部依赖项正确交互时，例如确保使用正确的参数调用函数时，请使用模拟。\n\n## 延伸阅读\n\n* [Sinon.js documentation](https://sinonjs.org/releases/latest/)\n* [Mocks Aren't Stubs](https://martinfowler.com/articles/mocksArentStubs.html) by Martin Fowler\n* [Sinon Tutorial: JavaScript Testing with Mocks, Spies & Stubs](https://www.sitepoint.com/sinon-tutorial-javascript-testing-mocks-spies-stubs/) on SitePoint\n"
  },
  {
    "path": "questions/what-are-modules-and-why-are-they-useful/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"b77edd7c\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"94016d21\",\n        \"35eb5fbe\",\n        \"2a7816d0\",\n        \"7d35de8e\",\n        \"760c4d8\",\n        \"e5354ea3\",\n        \"6d415e3b\",\n        \"d8d280e1\",\n        \"aa2ac676\",\n        \"cac7fdb8\",\n        \"de3eb95a\",\n        \"33ee4683\",\n        \"e0c9540e\",\n        \"86f854df\",\n        \"fe05ffd7\",\n        \"119f8a\",\n        \"3d68a40d\",\n        \"a232298b\",\n        \"afcabce6\",\n        \"8b451d4e\",\n        \"678c7eef\",\n        \"c833fa2\",\n        \"dd3f296e\",\n        \"e55f825e\",\n        \"f0af1f59\",\n        \"1a1c67e6\",\n        \"5ee88686\",\n        \"1f4770e5\",\n        \"3a8c9a7b\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"94016d21\",\n        \"35eb5fbe\",\n        \"2a7816d0\",\n        \"7d35de8e\",\n        \"760c4d8\",\n        \"e5354ea3\",\n        \"6d415e3b\",\n        \"d8d280e1\",\n        \"aa2ac676\",\n        \"cac7fdb8\",\n        \"de3eb95a\",\n        \"33ee4683\",\n        \"e0c9540e\",\n        \"86f854df\",\n        \"fe05ffd7\",\n        \"119f8a\",\n        \"3d68a40d\",\n        \"a232298b\",\n        \"afcabce6\",\n        \"8b451d4e\",\n        \"678c7eef\",\n        \"c833fa2\",\n        \"dd3f296e\",\n        \"e55f825e\",\n        \"f0af1f59\",\n        \"1a1c67e6\",\n        \"5ee88686\",\n        \"1f4770e5\",\n        \"3a8c9a7b\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-modules-and-why-are-they-useful/en-US.mdx",
    "content": "---\ntitle: What are modules and why are they useful?\n---\n\n## TL;DR\n\nModules are reusable pieces of code that can be imported and exported between different files in a project. They help in organizing code, making it more maintainable and scalable. By using modules, you can avoid global namespace pollution and manage dependencies more effectively. In JavaScript, you can use `import` and `export` statements to work with modules.\n\n```js\n// myModule.js\nexport const myFunction = () => {\n  console.log('Hello, World!');\n};\n\n// main.js\nimport { myFunction } from './myModule.js';\nmyFunction(); // Outputs: Hello, World!\n```\n\n---\n\n## What are modules and why are they useful?\n\n### Definition of modules\n\nModules are self-contained units of code that encapsulate functionality and can be imported and exported between different parts of an application. They allow developers to break down complex applications into smaller, manageable pieces.\n\n### Benefits of using modules\n\n#### Code organization\n\nModules help in organizing code by grouping related functionalities together. This makes the codebase easier to navigate and understand.\n\n#### Maintainability\n\nBy breaking down the code into smaller modules, it becomes easier to maintain and update. Changes in one module are less likely to affect other parts of the application.\n\n#### Reusability\n\nModules can be reused across different parts of an application or even in different projects. This reduces code duplication and promotes the DRY (Don't Repeat Yourself) principle.\n\n#### Avoiding global namespace pollution\n\nModules help in avoiding global namespace pollution by encapsulating variables and functions within their own scope. This reduces the risk of naming conflicts and makes the code more robust.\n\n#### Dependency management\n\nModules make it easier to manage dependencies between different parts of an application. You can explicitly declare what a module depends on and what it exports, making the code more predictable and easier to debug.\n\n### Working with modules in JavaScript\n\n#### Exporting from a module\n\nYou can export variables, functions, or classes from a module using the `export` keyword.\n\n```js\n// myModule.js\nexport const myVariable = 42;\nexport function myFunction() {\n  console.log('Hello, World!');\n}\nexport class MyClass {\n  constructor() {\n    console.log('MyClass instance created');\n  }\n}\n```\n\n#### Importing into a module\n\nYou can import variables, functions, or classes from another module using the `import` keyword.\n\n```js\n// main.js\nimport { myVariable, myFunction, MyClass } from './myModule.js';\n\nconsole.log(myVariable); // Outputs: 42\nmyFunction(); // Outputs: Hello, World!\nconst myClassInstance = new MyClass(); // Outputs: MyClass instance created\n```\n\n#### Default exports\n\nA module can have a default export, which can be imported without using curly braces.\n\n```js\n// myModule.js\nconst myDefaultFunction = () => {\n  console.log('Default export function');\n};\nexport default myDefaultFunction;\n\n// main.js\nimport myDefaultFunction from './myModule.js';\nmyDefaultFunction(); // Outputs: Default export function\n```\n\n## Further reading\n\n- [MDN Web Docs: Import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\n- [MDN Web Docs: Export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\n- [JavaScript Modules: A Beginner’s Guide](https://www.sitepoint.com/understanding-es6-modules/)\n"
  },
  {
    "path": "questions/what-are-modules-and-why-are-they-useful/metadata.json",
    "content": "{\n  \"slug\": \"what-are-modules-and-why-are-they-useful\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Modules\"\n}\n"
  },
  {
    "path": "questions/what-are-modules-and-why-are-they-useful/zh-CN.mdx",
    "content": "---\ntitle: 什么是模块以及它们为什么有用？\n---\n\n## TL;DR\n\n模块是可重用的代码片段，可以在项目中的不同文件之间导入和导出。它们有助于组织代码，使其更易于维护和扩展。通过使用模块，您可以避免全局命名空间污染并更有效地管理依赖关系。在 JavaScript 中，您可以使用 `import` 和 `export` 语句来处理模块。\n\n```js\n// myModule.js\nexport const myFunction = () => {\n  console.log('Hello, World!');\n};\n\n// main.js\nimport { myFunction } from './myModule.js';\nmyFunction(); // Outputs: Hello, World!\n```\n\n***\n\n## 什么是模块以及它们为什么有用？\n\n### 模块的定义\n\n模块是自包含的代码单元，封装了功能，可以在应用程序的不同部分之间导入和导出。它们允许开发人员将复杂的应用程序分解成更小、更易于管理的部分。\n\n### 使用模块的好处\n\n#### 代码组织\n\n模块通过将相关功能组合在一起，帮助组织代码。这使得代码库更易于导航和理解。\n\n#### 可维护性\n\n通过将代码分解成更小的模块，更容易维护和更新。一个模块中的更改不太可能影响应用程序的其他部分。\n\n#### 可重用性\n\n模块可以在应用程序的不同部分甚至不同项目中重复使用。这减少了代码重复，并促进了 DRY（不要重复自己）原则。\n\n#### 避免全局命名空间污染\n\n模块通过将变量和函数封装在其自己的作用域内，有助于避免全局命名空间污染。这降低了命名冲突的风险，并使代码更健壮。\n\n#### 依赖管理\n\n模块使管理应用程序不同部分之间的依赖关系更容易。您可以显式声明一个模块依赖于什么以及它导出什么，使代码更可预测且更易于调试。\n\n### 在 JavaScript 中使用模块\n\n#### 从模块导出\n\n您可以使用 `export` 关键字从模块中导出变量、函数或类。\n\n```js\n// myModule.js\nexport const myVariable = 42;\nexport function myFunction() {\n  console.log('Hello, World!');\n}\nexport class MyClass {\n  constructor() {\n    console.log('MyClass instance created');\n  }\n}\n```\n\n#### 导入到模块中\n\n您可以使用 `import` 关键字从另一个模块导入变量、函数或类。\n\n```js\n// main.js\nimport { myVariable, myFunction, MyClass } from './myModule.js';\n\nconsole.log(myVariable); // Outputs: 42\nmyFunction(); // Outputs: Hello, World!\nconst myClassInstance = new MyClass(); // Outputs: MyClass instance created\n```\n\n#### 默认导出\n\n一个模块可以有一个默认导出，可以在不使用大括号的情况下导入。\n\n```js\n// myModule.js\nconst myDefaultFunction = () => {\n  console.log('Default export function');\n};\nexport default myDefaultFunction;\n\n// main.js\nimport myDefaultFunction from './myModule.js';\nmyDefaultFunction(); // Outputs: Default export function\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)\n* [MDN Web Docs: Export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)\n* [JavaScript Modules: A Beginner’s Guide](https://www.sitepoint.com/understanding-es6-modules/)\n"
  },
  {
    "path": "questions/what-are-progressive-web-applications-pwas/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"53aedac1\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"87137522\",\n        \"2a7816d0\",\n        \"c128350b\",\n        \"25841bc3\",\n        \"c809c133\",\n        \"b6df0131\",\n        \"3e0f9fdd\",\n        \"a013ec6f\",\n        \"a4184ac7\",\n        \"e2d426d2\",\n        \"48fe022b\",\n        \"5b09eda8\",\n        \"7768403f\",\n        \"6ecf6518\",\n        \"8cc56a7\",\n        \"5994c607\",\n        \"2819c383\",\n        \"b3fe5e2a\",\n        \"1f4770e5\",\n        \"1e062e5d\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"87137522\",\n        \"2a7816d0\",\n        \"c128350b\",\n        \"25841bc3\",\n        \"c809c133\",\n        \"b6df0131\",\n        \"3e0f9fdd\",\n        \"a013ec6f\",\n        \"a4184ac7\",\n        \"e2d426d2\",\n        \"48fe022b\",\n        \"5b09eda8\",\n        \"7768403f\",\n        \"6ecf6518\",\n        \"8cc56a7\",\n        \"5994c607\",\n        \"2819c383\",\n        \"b3fe5e2a\",\n        \"1f4770e5\",\n        \"1e062e5d\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-progressive-web-applications-pwas/en-US.mdx",
    "content": "---\ntitle: What are Progressive Web Applications (PWAs)?\n---\n\n## TL;DR\n\nProgressive Web Applications (PWAs) are web applications that use modern web capabilities to deliver an app-like experience to users. They are reliable, fast, and engaging. PWAs can work offline, send push notifications, and be installed on a user's home screen. They leverage technologies like service workers, web app manifests, and HTTPS to provide these features.\n\n---\n\n## What are Progressive Web Applications (PWAs)?\n\n### Definition\n\nProgressive Web Applications (PWAs) are web applications that combine the best of web and mobile apps. They are built using standard web technologies such as HTML, CSS, and JavaScript but offer enhanced capabilities that make them feel like native apps.\n\n### Key characteristics\n\n- **Progressive**: They work for every user, regardless of browser choice, because they are built with progressive enhancement as a core tenet.\n- **Responsive**: They fit any form factor, whether it's a desktop, mobile, or tablet.\n- **Connectivity independent**: They can work offline or on low-quality networks using service workers.\n- **App-like**: They provide an app-like experience to users with app-style interactions and navigation.\n- **Fresh**: They are always up-to-date thanks to the service worker update process.\n- **Safe**: They are served via HTTPS to prevent snooping and ensure content hasn't been tampered with.\n- **Discoverable**: They are identifiable as \"applications\" thanks to W3C manifests and service worker registration, allowing search engines to find them.\n- **Re-engageable**: They can send push notifications to re-engage users.\n- **Installable**: They allow users to add apps they find most useful to their home screen without the hassle of an app store.\n- **Linkable**: They can be easily shared via URL and do not require complex installation.\n\n### Core technologies\n\n#### Service workers\n\nService workers are scripts that run in the background, separate from the web page, enabling features like offline functionality, background sync, and push notifications.\n\n```js\nif ('serviceWorker' in navigator) {\n  navigator.serviceWorker\n    .register('/service-worker.js')\n    .then(function (registration) {\n      console.log('Service Worker registered with scope:', registration.scope);\n    })\n    .catch(function (error) {\n      console.log('Service Worker registration failed:', error);\n    });\n}\n```\n\n#### Web app manifest\n\nThe web app manifest is a JSON file that provides metadata about the application (name, icons, start URL, etc.) and allows it to be installed on the user's home screen.\n\n```json\n{\n  \"name\": \"My PWA\",\n  \"short_name\": \"PWA\",\n  \"start_url\": \"/index.html\",\n  \"display\": \"standalone\",\n  \"background_color\": \"#ffffff\",\n  \"theme_color\": \"#000000\",\n  \"icons\": [\n    {\n      \"src\": \"icon/lowres.webp\",\n      \"sizes\": \"48x48\",\n      \"type\": \"image/webp\"\n    },\n    {\n      \"src\": \"icon/hd_hi.ico\",\n      \"sizes\": \"72x72 96x96 128x128 256x256\"\n    }\n  ]\n}\n```\n\n#### HTTPS\n\nPWAs must be served over HTTPS to ensure security and privacy. This is a requirement for service workers and other advanced web features.\n\n### Benefits\n\n- **Improved performance**: PWAs load faster and provide a smoother user experience.\n- **Increased engagement**: Features like push notifications and home screen installation help keep users engaged.\n- **Cost-effective**: Developing a PWA can be more cost-effective than building separate native apps for different platforms.\n\n## Further reading\n\n- [Google Developers: Progressive Web Apps](https://developers.google.com/web/progressive-web-apps)\n- [MDN Web Docs: Progressive web apps (PWAs)](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps)\n- [Web.dev: What are Progressive Web Apps?](https://web.dev/what-are-pwas/)\n"
  },
  {
    "path": "questions/what-are-progressive-web-applications-pwas/metadata.json",
    "content": "{\n  \"slug\": \"what-are-progressive-web-applications-pwas\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"browser\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/what-are-progressive-web-applications-pwas/zh-CN.mdx",
    "content": "---\ntitle: 什么是渐进式 Web 应用程序 (PWA)？\n---\n\n## TL;DR\n\n渐进式 Web 应用程序 (PWA) 是使用现代 Web 功能为用户提供类似应用程序体验的 Web 应用程序。它们可靠、快速且引人入胜。PWA 可以离线工作、发送推送通知，并安装在用户的 home 屏幕上。它们利用服务工作者、Web 应用程序清单和 HTTPS 等技术来提供这些功能。\n\n***\n\n## 什么是渐进式 Web 应用程序 (PWA)？\n\n### 定义\n\n渐进式 Web 应用程序 (PWA) 是结合了 Web 和移动应用程序优点的 Web 应用程序。它们使用 HTML、CSS 和 JavaScript 等标准 Web 技术构建，但提供了增强的功能，使其感觉像原生应用程序。\n\n### 关键特征\n\n* **渐进式**：它们适用于每个用户，无论浏览器选择如何，因为它们以渐进式增强为核心原则构建。\n* **响应式**：它们适合任何外形尺寸，无论是桌面、移动设备还是平板电脑。\n* **独立于连接**：它们可以使用服务工作者离线或在低质量网络上工作。\n* **类似应用程序**：它们通过类似应用程序的交互和导航为用户提供类似应用程序的体验。\n* **新鲜**：由于服务工作者更新过程，它们始终保持最新状态。\n* **安全**：它们通过 HTTPS 提供，以防止窥探并确保内容未被篡改。\n* **可发现**：由于 W3C 清单和服务工作者注册，它们被标识为“应用程序”，从而允许搜索引擎找到它们。\n* **可重新参与**：它们可以发送推送通知以重新吸引用户。\n* **可安装**：它们允许用户将他们认为最有用的应用程序添加到他们的 home 屏幕，而无需麻烦的应用程序商店。\n* **可链接**：它们可以通过 URL 轻松共享，并且不需要复杂的安装。\n\n### 核心技术\n\n#### 服务工作者\n\n服务工作者是在后台运行的脚本，与网页分开，支持离线功能、后台同步和推送通知等功能。\n\n```js\nif ('serviceWorker' in navigator) {\n  navigator.serviceWorker\n    .register('/service-worker.js')\n    .then(function (registration) {\n      console.log('Service Worker registered with scope:', registration.scope);\n    })\n    .catch(function (error) {\n      console.log('Service Worker registration failed:', error);\n    });\n}\n```\n\n#### Web 应用程序清单\n\nWeb 应用程序清单是一个 JSON 文件，它提供有关应用程序的元数据（名称、图标、启动 URL 等），并允许将其安装在用户的 home 屏幕上。\n\n```json\n{\n  \"name\": \"My PWA\",\n  \"short_name\": \"PWA\",\n  \"start_url\": \"/index.html\",\n  \"display\": \"standalone\",\n  \"background_color\": \"#ffffff\",\n  \"theme_color\": \"#000000\",\n  \"icons\": [\n    {\n      \"src\": \"icon/lowres.webp\",\n      \"sizes\": \"48x48\",\n      \"type\": \"image/webp\"\n    },\n    {\n      \"src\": \"icon/hd_hi.ico\",\n      \"sizes\": \"72x72 96x96 128x128 256x256\"\n    }\n  ]\n}\n```\n\n#### HTTPS\n\nPWA 必须通过 HTTPS 提供以确保安全性和隐私。这是服务工作者和其他高级 Web 功能的要求。\n\n### 优势\n\n* **改进的性能**：PWA 加载速度更快，并提供更流畅的用户体验。\n* **增加的参与度**：推送通知和 home 屏幕安装等功能有助于保持用户的参与度。\n* **具有成本效益**：开发 PWA 可能比为不同平台构建单独的本地应用程序更具成本效益。\n\n## 延伸阅读\n\n* [Google Developers: Progressive Web Apps](https://developers.google.com/web/progressive-web-apps)\n* [MDN Web Docs: Progressive web apps (PWAs)](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps)\n* [Web.dev: What are Progressive Web Apps?](https://web.dev/what-are-pwas/)\n"
  },
  {
    "path": "questions/what-are-promises-and-how-do-they-work/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"972d7668\",\n        \"2e5d8b18\",\n        \"2a7816d0\",\n        \"7b0ef71b\",\n        \"25841bc3\",\n        \"8d58a92e\",\n        \"e1eb96f4\",\n        \"8b2e7a29\",\n        \"a0e95d3d\",\n        \"a65a9210\",\n        \"b8d009d2\",\n        \"fd1653dc\",\n        \"940ecc2c\",\n        \"49045cb5\",\n        \"b31c193\",\n        \"b3413023\",\n        \"8e15a651\",\n        \"f4d4913a\",\n        \"343890f2\",\n        \"e5721686\",\n        \"1046830e\",\n        \"64794c1e\",\n        \"1f4770e5\",\n        \"9771f947\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"972d7668\",\n        \"2e5d8b18\",\n        \"2a7816d0\",\n        \"7b0ef71b\",\n        \"25841bc3\",\n        \"8d58a92e\",\n        \"e1eb96f4\",\n        \"8b2e7a29\",\n        \"a0e95d3d\",\n        \"a65a9210\",\n        \"b8d009d2\",\n        \"fd1653dc\",\n        \"940ecc2c\",\n        \"49045cb5\",\n        \"b31c193\",\n        \"b3413023\",\n        \"8e15a651\",\n        \"f4d4913a\",\n        \"343890f2\",\n        \"e5721686\",\n        \"1046830e\",\n        \"64794c1e\",\n        \"1f4770e5\",\n        \"9771f947\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"43e8bb48\"\n  }\n}\n"
  },
  {
    "path": "questions/what-are-promises-and-how-do-they-work/en-US.mdx",
    "content": "---\ntitle: What are Promises and how do they work?\n---\n\n## TL;DR\n\nPromises in JavaScript are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They have three states: `pending`, `fulfilled`, and `rejected`. You can handle the results of a promise using the `.then()` method for success and the `.catch()` method for errors.\n\n```js live\nlet promise = new Promise((resolve, reject) => {\n  // asynchronous operation\n  const success = true;\n  if (success) {\n    resolve('Success!');\n  } else {\n    reject('Error!');\n  }\n});\n\npromise\n  .then((result) => {\n    console.log(result); // 'Success!' (this will print)\n  })\n  .catch((error) => {\n    console.error(error); // 'Error!'\n  });\n```\n\n---\n\n## What are Promises and how do they work?\n\n### Definition\n\nPromises are a way to handle asynchronous operations in JavaScript. They provide a cleaner, more readable way to handle asynchronous code compared to traditional callback functions.\n\n### States of a Promise\n\nA promise can be in one of three states:\n\n- `Pending`: The initial state, neither fulfilled nor rejected.\n- `Fulfilled`: The operation completed successfully.\n- `Rejected`: The operation failed.\n\n### Creating a Promise\n\nYou create a promise using the `Promise` constructor, which takes a function with two arguments: `resolve` and `reject`. These are callbacks that you call to change the state of the promise.\n\n```js live\nlet promise = new Promise((resolve, reject) => {\n  // asynchronous operation\n  const success = true;\n  if (success) {\n    resolve('Success!');\n  } else {\n    reject('Error!');\n  }\n});\n```\n\n### Handling a Promise\n\nTo handle the result of a promise, you use the `.then()` method for a successful outcome and the `.catch()` method for an error.\n\n```js live\nlet promise = new Promise((resolve, reject) => {\n  // asynchronous operation\n  const success = false;\n  if (success) {\n    resolve('Success!');\n  } else {\n    reject('Error!');\n  }\n});\n\npromise\n  .then((result) => {\n    console.log(result); // 'Success!'\n  })\n  .catch((error) => {\n    console.error(error); // 'Error!' (this will print)\n  });\n```\n\n### Chaining Promises\n\nPromises can be chained to handle multiple asynchronous operations in sequence. Each `.then()` returns a new promise, allowing for further chaining.\n\n```js live\nnew Promise((resolve, reject) => {\n  setTimeout(() => {\n    resolve('Promise 1 resolved after 1 second');\n  }, 1000);\n})\n  .then((result) => {\n    console.log(result);\n    return 'Another promise';\n  })\n  .then((anotherResult) => {\n    console.log(anotherResult);\n  })\n  .catch((error) => {\n    console.error(error);\n  });\n```\n\n### Combining Promises\n\nYou can use `Promise.all()` to run multiple promises in parallel and wait for all of them to complete.\n\n```js live\nlet promise1 = Promise.resolve('First');\nlet promise2 = Promise.resolve('Second');\nlet promise3 = new Promise((resolve, reject) => {\n  setTimeout(() => {\n    resolve('Third');\n  }, 2000);\n});\n\nPromise.all([promise1, promise2, promise3]).then((results) => {\n  console.log(results); // ['First', 'Second', 'Third']\n});\n```\n\nIn the above example, while `promise1` and `promise2` resolve instantly, `Promise.all` waits for `promise3`, which takes 2 seconds, before logging the results.\n\n## Further reading\n\n- [MDN Web Docs: Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\n- [JavaScript.info: Promises](https://javascript.info/promise-basics)\n"
  },
  {
    "path": "questions/what-are-promises-and-how-do-they-work/metadata.json",
    "content": "{\n  \"slug\": \"what-are-promises-and-how-do-they-work\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Asynchronous JavaScript\"\n}\n"
  },
  {
    "path": "questions/what-are-promises-and-how-do-they-work/zh-CN.mdx",
    "content": "---\ntitle: 什么是 Promise 以及它们如何工作？\n---\n\n## TL;DR\n\nJavaScript 中的 Promise 是表示异步操作最终完成（或失败）及其结果值的对象。它们有三种状态：`pending`、`fulfilled` 和 `rejected`。您可以使用 `.then()` 方法处理 Promise 的结果以获取成功的结果，使用 `.catch()` 方法处理错误。\n\n```js live\nlet promise = new Promise((resolve, reject) => {\n  // asynchronous operation\n  const success = true;\n  if (success) {\n    resolve('Success!');\n  } else {\n    reject('Error!');\n  }\n});\n\npromise\n  .then((result) => {\n    console.log(result); // 'Success!' (this will print)\n  })\n  .catch((error) => {\n    console.error(error); // 'Error!'\n  });\n```\n\n***\n\n## 什么是 Promise 以及它们如何工作？\n\n### 定义\n\nPromise 是一种在 JavaScript 中处理异步操作的方式。与传统的 callback 函数相比，它们提供了一种更清晰、更易读的方式来处理异步代码。\n\n### Promise 的状态\n\n一个 Promise 可以处于以下三种状态之一：\n\n* `Pending`：初始状态，既未完成也未拒绝。\n* `Fulfilled`：操作成功完成。\n* `Rejected`：操作失败。\n\n### 创建一个 Promise\n\n您可以使用 `Promise` 构造函数创建一个 Promise，该构造函数接受一个带有两个参数的函数：`resolve` 和 `reject`。这些是您用来更改 Promise 状态的回调函数。\n\n```js live\nlet promise = new Promise((resolve, reject) => {\n  // asynchronous operation\n  const success = true;\n  if (success) {\n    resolve('Success!');\n  } else {\n    reject('Error!');\n  }\n});\n```\n\n### 处理 Promise\n\n要处理 Promise 的结果，您可以使用 `.then()` 方法来获取成功的结果，使用 `.catch()` 方法来获取错误。\n\n```js live\nlet promise = new Promise((resolve, reject) => {\n  // asynchronous operation\n  const success = false;\n  if (success) {\n    resolve('Success!');\n  } else {\n    reject('Error!');\n  }\n});\n\npromise\n  .then((result) => {\n    console.log(result); // 'Success!'\n  })\n  .catch((error) => {\n    console.error(error); // 'Error!' (this will print)\n  });\n```\n\n### 链式 Promise\n\nPromise 可以链接起来以按顺序处理多个异步操作。每个 `.then()` 都会返回一个新的 Promise，从而允许进一步链接。\n\n```js live\nnew Promise((resolve, reject) => {\n  setTimeout(() => {\n    resolve('Promise 1 resolved after 1 second');\n  }, 1000);\n})\n  .then((result) => {\n    console.log(result);\n    return 'Another promise';\n  })\n  .then((anotherResult) => {\n    console.log(anotherResult);\n  })\n  .catch((error) => {\n    console.error(error);\n  });\n```\n\n### 组合 Promise\n\n您可以使用 `Promise.all()` 并行运行多个 promise，并等待它们全部完成。\n\n```js live\nlet promise1 = Promise.resolve('First');\nlet promise2 = Promise.resolve('Second');\nlet promise3 = new Promise((resolve, reject) => {\n  setTimeout(() => {\n    resolve('Third');\n  }, 2000);\n});\n\nPromise.all([promise1, promise2, promise3]).then((results) => {\n  console.log(results); // ['First', 'Second', 'Third']\n});\n```\n\n在上面的例子中，虽然 `promise1` 和 `promise2` 立即完成，但 `Promise.all` 会等待 `promise3`，它需要 2 秒钟，然后才会记录结果。\n\n## 延伸阅读\n\n* [MDN Web Docs: Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\n* [JavaScript.info: Promises](https://javascript.info/promise-basics)\n"
  },
  {
    "path": "questions/what-are-proxies-in-javascript-used-for/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"1792064b\",\n        \"e17d8fa2\",\n        \"9dee662b\",\n        \"fb2e4b76\",\n        \"65ed4859\",\n        \"2a7816d0\",\n        \"f6caf337\",\n        \"819fe3\",\n        \"b786ee7\",\n        \"3c7af4ff\",\n        \"ca3db77f\",\n        \"3a81da43\",\n        \"9c639e26\",\n        \"becb2d1\",\n        \"4591913\",\n        \"d818552d\",\n        \"14f124cd\",\n        \"77e7e192\",\n        \"8d5f7b65\",\n        \"85b9f81a\",\n        \"9c8f784d\",\n        \"b880edd8\",\n        \"19606c83\",\n        \"d37daf2a\",\n        \"43a614a8\",\n        \"bb5f3c18\",\n        \"10e7c501\",\n        \"6f129e4f\",\n        \"9741b8e2\",\n        \"43f23e8e\",\n        \"ca09745c\",\n        \"65435984\",\n        \"be11f5be\",\n        \"98345b7d\",\n        \"1184dada\",\n        \"b916b863\",\n        \"67a1d4f3\",\n        \"db1e30d\",\n        \"1f4770e5\",\n        \"f191c537\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"1792064b\",\n        \"e17d8fa2\",\n        \"9dee662b\",\n        \"fb2e4b76\",\n        \"65ed4859\",\n        \"2a7816d0\",\n        \"f6caf337\",\n        \"819fe3\",\n        \"b786ee7\",\n        \"3c7af4ff\",\n        \"ca3db77f\",\n        \"3a81da43\",\n        \"9c639e26\",\n        \"becb2d1\",\n        \"4591913\",\n        \"d818552d\",\n        \"14f124cd\",\n        \"77e7e192\",\n        \"8d5f7b65\",\n        \"85b9f81a\",\n        \"9c8f784d\",\n        \"b880edd8\",\n        \"19606c83\",\n        \"d37daf2a\",\n        \"43a614a8\",\n        \"bb5f3c18\",\n        \"10e7c501\",\n        \"6f129e4f\",\n        \"9741b8e2\",\n        \"43f23e8e\",\n        \"ca09745c\",\n        \"65435984\",\n        \"be11f5be\",\n        \"98345b7d\",\n        \"1184dada\",\n        \"b916b863\",\n        \"67a1d4f3\",\n        \"db1e30d\",\n        \"1f4770e5\",\n        \"f191c537\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"95b4aadc\"\n  }\n}\n"
  },
  {
    "path": "questions/what-are-proxies-in-javascript-used-for/en-US.mdx",
    "content": "---\ntitle: What are proxies in JavaScript used for?\n---\n\n## TL;DR\n\nIn JavaScript, a proxy is an object that acts as an intermediary between an object and the code. Proxies are used to intercept and customize the fundamental operations of JavaScript objects, such as property access, assignment, function invocation, and more.\n\nHere's a basic example of using a `Proxy` to log every property access:\n\n```js live\nconst myObject = {\n  name: 'John',\n  age: 42,\n};\n\nconst handler = {\n  get: function (target, prop, receiver) {\n    console.log(`Someone accessed property \"${prop}\"`);\n    return target[prop];\n  },\n};\n\nconst proxiedObject = new Proxy(myObject, handler);\n\nconsole.log(proxiedObject.name);\n// Someone accessed property \"name\"\n// 'John'\n\nconsole.log(proxiedObject.age);\n// Someone accessed property \"age\"\n// 42\n```\n\nUse cases include:\n\n- **Property access interception**: Intercept and customize property access on an object.\n  - **Property assignment validation**: Validate property values before they are set on the target object.\n  - **Logging and debugging**: Create wrappers for logging and debugging interactions with an object\n  - **Creating reactive systems**: Trigger updates in other parts of your application when object properties change (data binding).\n  - **Data transformation**: Transforming data being set or retrieved from an object.\n  - **Mocking and stubbing in tests**: Create mock or stub objects for testing purposes, allowing you to isolate dependencies and focus on the unit under test\n- **Function invocation interception**: Used to cache and return the result of frequently accessed methods if they involve network calls or computationally intensive logic, improving performance\n- **Dynamic property creation**: Useful for defining properties on-the-fly with default values and avoid storing redundant data in objects.\n\n---\n\n## JavaScript proxies\n\nIn JavaScript, a proxy is an object that allows you to customize the behavior of another object, often referred to as the target object. Proxies can intercept and redefine various operations for the target object, such as property access, assignment, enumeration, function invocation, and more. This makes proxies a powerful tool for a variety of use cases, including but not limited to validation, logging, performance monitoring, and implementing advanced data structures.\n\nHere are some common use cases and examples of how proxies can be used in JavaScript:\n\n### Property access interception\n\nProxies can be used to intercept and customize property access on an object.\n\n```js live\nconst target = {\n  message: 'Hello, world!',\n};\n\nconst handler = {\n  get: function (target, property) {\n    if (property in target) {\n      return target[property];\n    }\n\n    return `Property ${property} does not exist.`;\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nconsole.log(proxy.message); // Hello, world!\nconsole.log(proxy.nonExistentProperty); // Property nonExistentProperty does not exist.\n```\n\n#### Creating wrappers for logging and debugging\n\nThis is useful for creating wrappers for logging and debugging interactions with an object.\n\n```js live\nconst target = {\n  name: 'Alice',\n  age: 30,\n};\n\nconst handler = {\n  get: function (target, property) {\n    console.log(`Getting property ${property}`);\n    return target[property];\n  },\n  set: function (target, property, value) {\n    console.log(`Setting property ${property} to ${value}`);\n    target[property] = value;\n    return true;\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nconsole.log(proxy.name); // Output: Getting property name\n//         Alice\nproxy.age = 31; // Output: Setting property age to 31\nconsole.log(proxy.age); // Output: Getting property age\n//         31\n```\n\n#### Property assignment validation\n\nProxies can be used to validate property values before they are set on the target object.\n\n```js live\nconst target = {\n  age: 25,\n};\n\nconst handler = {\n  set: function (target, property, value) {\n    if (property === 'age' && typeof value !== 'number') {\n      throw new TypeError('Age must be a number');\n    }\n    target[property] = value;\n    return true;\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nproxy.age = 30; // Works fine\nproxy.age = 'thirty'; // Throws TypeError: Age must be a number\n```\n\n#### Creating reactive systems\n\nProxies are often used to trigger updates in other parts of your application when object properties change (data binding).\n\nA practical example is JavaScript frameworks like [Vue.js](https://vuejs.org/), where proxies are used to [create reactive systems that automatically update the UI when data changes](https://vuejs.org/guide/extras/reactivity-in-depth.html).\n\n```js live\nconst target = {\n  firstName: 'John',\n  lastName: 'Doe',\n};\n\nconst handler = {\n  set: function (target, property, value) {\n    console.log(`Property ${property} set to ${value}`);\n    target[property] = value;\n    // Automatically update the UI or perform other actions\n    return true;\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nproxy.firstName = 'Jane'; // Output: Property firstName set to Jane\n```\n\nOther use cases for access interception include:\n\n- **Mocking and stubbing**: Proxies can be used to create mock or stub objects for testing purposes, allowing you to isolate dependencies and focus on the unit under test.\n\n### Function invocation interception\n\nProxies can intercept and customize function calls.\n\n```js live\nconst target = function (name) {\n  return `Hello, ${name}!`;\n};\n\nconst handler = {\n  apply: function (target, thisArg, argumentsList) {\n    console.log(`Called with arguments: ${argumentsList}`);\n    return target.apply(thisArg, argumentsList);\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nconsole.log(proxy('Alice')); // Called with arguments: Alice\n// Hello, Alice!\n```\n\nThis interception can be used to cache and return the result of frequently accessed methods if they involve network calls or computationally intensive logic, improving performance by reducing the number of requests/computations made.\n\n### Dynamic property creation\n\nProxies can be used to dynamically create properties or methods on an object. This is useful for defining properties on-the-fly with default values and avoid storing redundant data in objects.\n\n```js live\nconst target = {};\n\nconst handler = {\n  get: function (target, property) {\n    if (!(property in target)) {\n      target[property] = `Dynamic property ${property}`;\n    }\n    return target[property];\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nconsole.log(proxy.newProp); // Output: Dynamic property newProp\nconsole.log(proxy.anotherProp); // Output: Dynamic property anotherProp\n```\n\n### Implementing object relational mappers (ORMs)\n\nProxies can be used to create objects for database records by intercepting property access to lazily load data from the database. This provides a more object-oriented interface to interact with a database.\n\n## Real world use cases\n\nMany popular libraries, especially state management solutions, are built on top of JavaScript proxies:\n\n- **[Vue.js](https://vuejs.org/)**: Vue.js is a progressive framework for building user interfaces. In Vue 3, proxies are used extensively to implement the reactivity system.\n- **[MobX](https://mobx.js.org/)**: MobX uses proxies to make objects and arrays observable, allowing components to automatically react to state changes.\n- **[Immer](https://immerjs.github.io/immer/)**: Immer is a library that allows you to work with immutable state in a more convenient way. It uses proxies to track changes and produce the next immutable state.\n\n## Summary\n\nProxies in JavaScript provide a powerful and flexible way to intercept and customize operations on objects. They are useful for a wide range of applications, including validation, logging, debugging, dynamic property creation, and implementing reactive systems. By using proxies, developers can create more robust, maintainable, and feature-rich applications.\n\n## Further reading\n\n- [Proxy - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)\n- [Proxy and Reflect | JavaScript.info](https://javascript.info/proxy)\n"
  },
  {
    "path": "questions/what-are-proxies-in-javascript-used-for/metadata.json",
    "content": "{\n  \"slug\": \"what-are-proxies-in-javascript-used-for\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 470,\n  \"difficulty\": \"easy\"\n}\n"
  },
  {
    "path": "questions/what-are-proxies-in-javascript-used-for/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中的代理有什么用？\n---\n\n## TL;DR\n\n在 JavaScript 中，代理是一个充当对象和代码之间中介的 对象。代理用于拦截和自定义 JavaScript 对象的基本操作，例如属性访问、赋值、函数调用等。\n\n以下是使用 `Proxy` 记录每个属性访问的基本示例：\n\n```js live\nconst myObject = {\n  name: 'John',\n  age: 42,\n};\n\nconst handler = {\n  get: function (target, prop, receiver) {\n    console.log(`Someone accessed property \"${prop}\"`);\n    return target[prop];\n  },\n};\n\nconst proxiedObject = new Proxy(myObject, handler);\n\nconsole.log(proxiedObject.name);\n// Someone accessed property \"name\"\n// 'John'\n\nconsole.log(proxiedObject.age);\n// Someone accessed property \"age\"\n// 42\n```\n\n用例包括：\n\n* **属性访问拦截**：拦截和自定义对对象的属性访问。\n  * **属性赋值验证**：在将属性值设置到目标对象之前验证它们。\n  * **日志记录和调试**：创建用于记录和调试与对象交互的包装器\n  * **创建反应式系统**：当对象属性更改时，触发应用程序其他部分的更新（数据绑定）。\n  * **数据转换**：转换从对象设置或检索的数据。\n  * **在测试中模拟和存根**：为测试目的创建模拟或存根对象，允许您隔离依赖项并专注于被测单元\n* **函数调用拦截**：用于缓存和返回经常访问的方法的结果（如果它们涉及网络调用或计算密集型逻辑），从而提高性能\n* **动态属性创建**：用于即时定义具有默认值的属性，并避免在对象中存储冗余数据。\n\n***\n\n## JavaScript 代理\n\n在 JavaScript 中，代理是一个允许您自定义另一个对象（通常称为目标对象）行为的对象。代理可以拦截和重新定义目标对象的各种操作，例如属性访问、赋值、枚举、函数调用等。这使得代理成为各种用例的强大工具，包括但不限于验证、日志记录、性能监控和实现高级数据结构。\n\n以下是代理在 JavaScript 中使用的一些常见用例和示例：\n\n### 属性访问拦截\n\n代理可用于拦截和自定义对对象的属性访问。\n\n```js live\nconst target = {\n  message: 'Hello, world!',\n};\n\nconst handler = {\n  get: function (target, property) {\n    if (property in target) {\n      return target[property];\n    }\n\n    return `Property ${property} does not exist.`;\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nconsole.log(proxy.message); // Hello, world!\nconsole.log(proxy.nonExistentProperty); // Property nonExistentProperty does not exist.\n```\n\n#### 创建用于日志记录和调试的包装器\n\n这对于创建用于记录和调试与对象交互的包装器很有用。\n\n```js live\nconst target = {\n  name: 'Alice',\n  age: 30,\n};\n\nconst handler = {\n  get: function (target, property) {\n    console.log(`Getting property ${property}`);\n    return target[property];\n  },\n  set: function (target, property, value) {\n    console.log(`Setting property ${property} to ${value}`);\n    target[property] = value;\n    return true;\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nconsole.log(proxy.name); // Output: Getting property name\n//         Alice\nproxy.age = 31; // Output: Setting property age to 31\nconsole.log(proxy.age); // Output: Getting property age\n//         31\n```\n\n#### 属性赋值验证\n\n代理可用于在将属性值设置到目标对象之前验证它们。\n\n```js live\nconst target = {\n  age: 25,\n};\n\nconst handler = {\n  set: function (target, property, value) {\n    if (property === 'age' && typeof value !== 'number') {\n      throw new TypeError('Age must be a number');\n    }\n    target[property] = value;\n    return true;\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nproxy.age = 30; // Works fine\nproxy.age = 'thirty'; // Throws TypeError: Age must be a number\n```\n\n#### 创建响应式系统\n\n代理通常用于在对象属性更改时触发应用程序其他部分的更新（数据绑定）。\n\n一个实际的例子是像 [Vue.js](https://vuejs.org/) 这样的 JavaScript 框架，其中代理用于[创建响应式系统，当数据更改时自动更新 UI](https://vuejs.org/guide/extras/reactivity-in-depth.html)。\n\n```js live\nconst target = {\n  firstName: 'John',\n  lastName: 'Doe',\n};\n\nconst handler = {\n  set: function (target, property, value) {\n    console.log(`Property ${property} set to ${value}`);\n    target[property] = value;\n    // Automatically update the UI or perform other actions\n    return true;\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nproxy.firstName = 'Jane'; // Output: Property firstName set to Jane\n```\n\n访问拦截的其他用例包括：\n\n* **模拟和存根**：代理可用于创建用于测试目的的模拟或存根对象，允许您隔离依赖项并专注于被测单元。\n\n### 函数调用拦截\n\n代理可以拦截和自定义函数调用。\n\n```js live\nconst target = function (name) {\n  return `Hello, ${name}!`;\n};\n\nconst handler = {\n  apply: function (target, thisArg, argumentsList) {\n    console.log(`Called with arguments: ${argumentsList}`);\n    return target.apply(thisArg, argumentsList);\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nconsole.log(proxy('Alice')); // Called with arguments: Alice\n// Hello, Alice!\n```\n\n如果频繁访问的方法涉及网络调用或计算密集型逻辑，则此拦截可用于缓存并返回结果，从而通过减少发出的请求/计算次数来提高性能。\n\n### 动态属性创建\n\n代理可用于动态地在对象上创建属性或方法。这对于使用默认值即时定义属性并避免在对象中存储冗余数据非常有用。\n\n```js live\nconst target = {};\n\nconst handler = {\n  get: function (target, property) {\n    if (!(property in target)) {\n      target[property] = `Dynamic property ${property}`;\n    }\n    return target[property];\n  },\n};\n\nconst proxy = new Proxy(target, handler);\n\nconsole.log(proxy.newProp); // Output: Dynamic property newProp\nconsole.log(proxy.anotherProp); // Output: Dynamic property anotherProp\n```\n\n### 实现对象关系映射器 (ORM)\n\n代理可用于创建数据库记录的对象，方法是拦截属性访问以从数据库中惰性加载数据。这提供了一个更面向对象的接口来与数据库交互。\n\n## 实际用例\n\n许多流行的库，尤其是状态管理解决方案，都是建立在 JavaScript 代理之上的：\n\n* **[Vue.js](https://vuejs.org/)**: Vue.js 是一个用于构建用户界面的渐进式框架。在 Vue 3 中，代理被广泛用于实现响应式系统。\n* **[MobX](https://mobx.js.org/)**: MobX 使用代理使对象和数组可观察，允许组件自动响应状态变化。\n* **[Immer](https://immerjs.github.io/immer/)**: Immer 是一个允许你以更方便的方式处理不可变状态的库。它使用代理来跟踪更改并生成下一个不可变状态。\n\n## 总结\n\nJavaScript 中的代理提供了一种强大而灵活的方式来拦截和自定义对象上的操作。它们适用于广泛的应用程序，包括验证、日志记录、调试、动态属性创建和实现响应式系统。通过使用代理，开发人员可以创建更强大、更易于维护且功能更丰富的应用程序。\n\n## 延伸阅读\n\n* [Proxy - JavaScript | MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy)\n* [Proxy and Reflect | JavaScript.info](https://zh.javascript.info/proxy)\n"
  },
  {
    "path": "questions/what-are-rest-parameters-and-how-are-they-used/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"28fb9ff6\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"1565e945\",\n        \"687a2be1\",\n        \"2a7816d0\",\n        \"39bbed2f\",\n        \"25841bc3\",\n        \"1b87c763\",\n        \"eea083fa\",\n        \"a1a9c693\",\n        \"7c3f8893\",\n        \"4abfb705\",\n        \"8824fed9\",\n        \"5883129f\",\n        \"5cbf814\",\n        \"687a2be1\",\n        \"33174994\",\n        \"415fae55\",\n        \"a5e52a92\",\n        \"e19c111a\",\n        \"4135df60\",\n        \"31704ea\",\n        \"d4ff1ce1\",\n        \"1f4770e5\",\n        \"a94ca589\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"1565e945\",\n        \"687a2be1\",\n        \"2a7816d0\",\n        \"39bbed2f\",\n        \"25841bc3\",\n        \"1b87c763\",\n        \"eea083fa\",\n        \"a1a9c693\",\n        \"7c3f8893\",\n        \"4abfb705\",\n        \"8824fed9\",\n        \"5883129f\",\n        \"5cbf814\",\n        \"687a2be1\",\n        \"33174994\",\n        \"415fae55\",\n        \"a5e52a92\",\n        \"e19c111a\",\n        \"4135df60\",\n        \"31704ea\",\n        \"d4ff1ce1\",\n        \"1f4770e5\",\n        \"a94ca589\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-rest-parameters-and-how-are-they-used/en-US.mdx",
    "content": "---\ntitle: What are rest parameters and how are they used?\n---\n\n## TL;DR\n\nRest parameters in JavaScript allow a function to accept an indefinite number of arguments as an array. They are denoted by three dots (`...`) followed by the name of the array. This feature is useful for functions that need to handle multiple arguments without knowing the exact number in advance.\n\n```js live\nfunction sum(...numbers) {\n  return numbers.reduce((acc, curr) => acc + curr, 0);\n}\n\nconsole.log(sum(1, 2, 3, 4)); // Output: 10\n```\n\n---\n\n## Rest parameters\n\n### Definition\n\nRest parameters allow a function to accept an indefinite number of arguments as an array. They are represented by three dots (`...`) followed by the name of the array.\n\n### Syntax\n\nThe syntax for rest parameters is straightforward. You place three dots before the last parameter in the function definition:\n\n```js live\nfunction myFunction(a, b, ...rest) {\n  // 'rest' is an array containing the remaining arguments\n  console.log(rest); // [3, 4, 5]\n}\nmyFunction(1, 2, 3, 4, 5);\n```\n\n### Usage\n\nRest parameters are useful in various scenarios, such as when you need to handle multiple arguments without knowing their exact number in advance.\n\n#### Example: Summing numbers\n\nHere's a simple example of a function that sums an indefinite number of arguments:\n\n```js live\nfunction sum(...numbers) {\n  return numbers.reduce((acc, curr) => acc + curr, 0);\n}\n\nconsole.log(sum(1, 2, 3, 4)); // Output: 10\n```\n\nIn this example, the `sum` function uses the rest parameter `numbers` to collect all the arguments passed to it into an array. The `reduce` method is then used to sum up the elements of the array.\n\n#### Example: Combining arrays\n\nRest parameters can also be used to combine multiple arrays into one:\n\n```js live\nfunction combineArrays(...arrays) {\n  return arrays.flat();\n}\n\nconsole.log(combineArrays([1, 2], [3, 4], [5, 6])); // Output: [1, 2, 3, 4, 5, 6]\n```\n\nIn this example, the `combineArrays` function uses the rest parameter `arrays` to collect all the arrays passed to it into a single array. The `flat` method is then used to flatten the array of arrays into a single array.\n\n### Important points\n\n- Rest parameters must be the last parameter in the function definition.\n- Only one rest parameter is allowed per function.\n- Rest parameters are different from the `arguments` object, which is an array-like object available within all non-arrow functions.\n\n## Further reading\n\n- [MDN Web Docs: Rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)\n- [JavaScript.info: Rest parameters and spread syntax](https://javascript.info/rest-parameters-spread)\n- [W3Schools: JavaScript Function Parameters](https://www.w3schools.com/js/js_function_parameters.asp)\n"
  },
  {
    "path": "questions/what-are-rest-parameters-and-how-are-they-used/metadata.json",
    "content": "{\n  \"slug\": \"what-are-rest-parameters-and-how-are-they-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Operators & Control Flow\"\n}\n"
  },
  {
    "path": "questions/what-are-rest-parameters-and-how-are-they-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是剩余参数以及如何使用它们？\n---\n\n## TL;DR\n\nJavaScript 中的剩余参数允许函数将不定数量的参数作为数组接受。它们由三个点 (`...`) 后跟数组的名称表示。此功能对于需要处理多个参数而无需预先知道确切数量的函数很有用。\n\n```js live\nfunction sum(...numbers) {\n  return numbers.reduce((acc, curr) => acc + curr, 0);\n}\n\nconsole.log(sum(1, 2, 3, 4)); // Output: 10\n```\n\n***\n\n## 剩余参数\n\n### 定义\n\n剩余参数允许函数将不定数量的参数作为数组接受。它们由三个点 (`...`) 后跟数组的名称表示。\n\n### 语法\n\n剩余参数的语法很简单。您将三个点放在函数定义中最后一个参数的前面：\n\n```js live\nfunction myFunction(a, b, ...rest) {\n  // 'rest' is an array containing the remaining arguments\n  console.log(rest); // [3, 4, 5]\n}\nmyFunction(1, 2, 3, 4, 5);\n```\n\n### 用法\n\n剩余参数在各种情况下都很有用，例如当您需要处理多个参数而无需预先知道它们的确切数量时。\n\n#### 示例：求和数字\n\n这是一个对不定数量的参数求和的函数的简单示例：\n\n```js live\nfunction sum(...numbers) {\n  return numbers.reduce((acc, curr) => acc + curr, 0);\n}\n\nconsole.log(sum(1, 2, 3, 4)); // Output: 10\n```\n\n在这个例子中，`sum` 函数使用剩余参数 `numbers` 将传递给它的所有参数收集到一个数组中。然后使用 `reduce` 方法对数组的元素求和。\n\n#### 示例：合并数组\n\n剩余参数也可用于将多个数组合并为一个：\n\n```js live\nfunction combineArrays(...arrays) {\n  return arrays.flat();\n}\n\nconsole.log(combineArrays([1, 2], [3, 4], [5, 6])); // Output: [1, 2, 3, 4, 5, 6]\n```\n\n在这个例子中，`combineArrays` 函数使用剩余参数 `arrays` 将传递给它的所有数组收集到一个数组中。然后使用 `flat` 方法将数组的数组展平为单个数组。\n\n### 重要提示\n\n* Rest 参数必须是函数定义中的最后一个参数。\n* 每个函数只允许一个 rest 参数。\n* Rest 参数与 `arguments` 对象不同，`arguments` 对象是一个类似数组的对象，可在所有非箭头函数中使用。\n\n## 延伸阅读\n\n* [MDN Web 文档：Rest 参数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/rest_parameters)\n* [JavaScript.info：Rest 参数和展开语法](https://zh.javascript.info/rest-parameters-spread)\n* [W3Schools：JavaScript 函数参数](https://www.w3schools.com/js/js_function_parameters.asp)\n"
  },
  {
    "path": "questions/what-are-server-sent-events/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"51c64fdf\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"83baecdd\",\n        \"55ecde0c\",\n        \"454290fa\",\n        \"2e4ffa4f\",\n        \"91abdf7e\",\n        \"e6c42032\",\n        \"1b2ee0a9\",\n        \"dfb629f\",\n        \"bca5ce78\",\n        \"2a7816d0\",\n        \"ebd29b4d\",\n        \"b2ca17f1\",\n        \"48bd7142\",\n        \"b6ada2c3\",\n        \"722e9703\",\n        \"9a7585f1\",\n        \"be7b0b3\",\n        \"39dd268e\",\n        \"226476b4\",\n        \"6cee5ab5\",\n        \"4f0feaeb\",\n        \"3d9ca7fd\",\n        \"b0f9ac60\",\n        \"67a1d4f3\",\n        \"af98fae2\",\n        \"1f4770e5\",\n        \"aae9ac85\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"83baecdd\",\n        \"55ecde0c\",\n        \"454290fa\",\n        \"2e4ffa4f\",\n        \"91abdf7e\",\n        \"e6c42032\",\n        \"1b2ee0a9\",\n        \"dfb629f\",\n        \"bca5ce78\",\n        \"2a7816d0\",\n        \"ebd29b4d\",\n        \"b2ca17f1\",\n        \"48bd7142\",\n        \"b6ada2c3\",\n        \"722e9703\",\n        \"9a7585f1\",\n        \"be7b0b3\",\n        \"39dd268e\",\n        \"226476b4\",\n        \"6cee5ab5\",\n        \"4f0feaeb\",\n        \"3d9ca7fd\",\n        \"b0f9ac60\",\n        \"67a1d4f3\",\n        \"af98fae2\",\n        \"1f4770e5\",\n        \"aae9ac85\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-server-sent-events/en-US.mdx",
    "content": "---\ntitle: What are server-sent events?\n---\n\n## TL;DR\n\n[Server-sent events (SSE)](https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface) is a standard that allows a web page to receive automatic updates from a server via an HTTP connection. Server-sent events are used with `EventSource` instances that opens a connection with a server and allows client to receive events from the server. Connections created by server-sent events are persistent (similar to the `WebSocket`s), however there are a few differences:\n\n| Property | `WebSocket` | `EventSource` |\n| --- | --- | --- |\n| Direction | Bi-directional – both client and server can exchange messages | Unidirectional – only server sends data |\n| Data type | Binary and text data | Only text |\n| Protocol | WebSocket protocol (`ws://`) | Regular HTTP (`http://`) |\n\n**Creating an event source**\n\n```js\nconst eventSource = new EventSource('/sse-stream');\n```\n\n**Listening for events**\n\n```js\n// Fired when the connection is established.\neventSource.addEventListener('open', () => {\n  console.log('Connection opened');\n});\n\n// Fired when a message is received from the server.\neventSource.addEventListener('message', (event) => {\n  console.log('Received message:', event.data);\n});\n\n// Fired when an error occurs.\neventSource.addEventListener('error', (error) => {\n  console.error('Error occurred:', error);\n});\n```\n\n**Sending events from server**\n\n```js\nconst express = require('express');\nconst app = express();\n\napp.get('/sse-stream', (req, res) => {\n  // `Content-Type` need to be set to `text/event-stream`.\n  res.setHeader('Content-Type', 'text/event-stream');\n  res.setHeader('Cache-Control', 'no-cache');\n  res.setHeader('Connection', 'keep-alive');\n\n  // Each message should be prefixed with data.\n  const sendEvent = (data) => res.write(`data: ${data}\\n\\n`);\n\n  sendEvent('Hello from server');\n\n  const intervalId = setInterval(() => sendEvent(new Date().toString()), 1000);\n\n  res.on('close', () => {\n    console.log('Client closed connection');\n    clearInterval(intervalId);\n  });\n});\n\napp.listen(3000, () => console.log('Server started on port 3000'));\n```\n\nIn this example, the server sends a \"Hello from server\" message initially, and then sends the current date every second. The connection is kept alive until the client closes it\n\n---\n\n## Server-sent events (SSE)\n\nServer-sent events (SSE) is a standard that allows a server to push updates to a web client over a single, long-lived HTTP connection. It enables real-time updates without the client having to constantly poll the server for new data.\n\n## How SSE works\n\n1. The client creates a new `EventSource` object, passing the URL of the `server-side` script that will generate the event stream:\n\n   ```js\n   const eventSource = new EventSource('/event-stream');\n   ```\n\n2. The server-side script sets the appropriate headers to indicate that it will be sending an event stream (`Content-Type: text/event-stream`), and then starts sending events to the client.\n3. Each event sent by the server follows a specific format, with fields like `event`, `data`, and `id`. For example:\n\n   ```js\n   event: message\n   data: Hello, world!\n\n   event: update\n   id: 123\n   data: {\"temperature\": 25, \"humidity\": 60}\n   ```\n\n4. On the client-side, the `EventSource` object receives these events and dispatches them as browser events, which can be handled using event listeners or the `onmessage` event handler:\n\n   ```js\n   eventSource.onmessage = function (event) {\n     console.log('Received message:', event.data);\n   };\n\n   eventSource.addEventListener('update', function (event) {\n     console.log('Received update:', JSON.parse(event.data));\n   });\n   ```\n\n5. The `EventSource` object automatically handles reconnection if the connection is lost, and it can resume the event stream from the last received event ID using the `Last-Event-ID HTTP header`.\n\n## SSE features\n\n- **Unidirectional**: Only the server can send data to the client. For bidirectional communication, web sockets would be more appropriate.\n- **Retry mechanism**: The client will retry the connection if it fails, with the retry interval specified by the `retry:` field from the server.\n- **Text-only data**: SSE can only transmit text data, which means binary data needs to be encoded (e.g., Base64) before transmission. This can lead to increased overhead and inefficiency for applications that need to transmit large binary payloads.\n- **Built-in browser support**: Supported by most modern browsers without additional libraries.\n- **Event types**: SSE supports custom event types using the `event:` field, allowing categorization of messages.\n- **`Last-Event-Id`**: The client sends the `Last-Event-Id` header when reconnecting, allowing the server to resume the stream from the last received event. However, there is no built-in mechanism to replay missed events during the disconnection period. You may need to implement a mechanism to handle missed events, such as using the `Last-Event-Id` header.\n- **Connection limitations**: Browsers have a limit on the maximum number of concurrent SSE connections, typically around 6 per domain. This can be a bottleneck if you need to establish multiple SSE connections from the same client. Using HTTP/2 will mitigate this issue.\n\n## Implementing SSE in JavaScript\n\nThe following code demonstrates a minimal implementation of SSE on the client and the server:\n\n- The server sets the appropriate headers to establish an SSE connection.\n- Messages are sent to the client every 5 seconds.\n- The server cleans up the interval and ends the response when the client disconnects.\n\nOn the client:\n\n```js\n// Create a new EventSource object\nconst eventSource = new EventSource('/sse');\n\n// Event listener for receiving messages\neventSource.onmessage = function (event) {\n  console.log('New message:', event.data);\n};\n\n// Event listener for errors\neventSource.onerror = function (error) {\n  console.error('Error occurred:', error);\n};\n\n// Optional: Event listener for open connection\neventSource.onopen = function () {\n  console.log('Connection opened');\n};\n```\n\nOn the server:\n\n```js\nconst http = require('http');\n\nhttp\n  .createServer((req, res) => {\n    if (req.url === '/sse') {\n      // Set headers for SSE\n      res.writeHead(200, {\n        'Content-Type': 'text/event-stream',\n        'Cache-Control': 'no-cache',\n        Connection: 'keep-alive',\n      });\n\n      // Function to send a message\n      const sendMessage = (message) => {\n        res.write(`data: ${message}\\n\\n`); // Messages are delimited with double line breaks.\n      };\n\n      // Send a message every 5 seconds\n      const intervalId = setInterval(() => {\n        sendMessage(`Current time: ${new Date().toLocaleTimeString()}`);\n      }, 5000);\n\n      // Handle client disconnect\n      req.on('close', () => {\n        clearInterval(intervalId);\n        res.end();\n      });\n    } else {\n      res.writeHead(404);\n      res.end();\n    }\n  })\n  .listen(8080, () => {\n    console.log('SSE server running on port 8080');\n  });\n```\n\n## Summary\n\nServer-sent events provide an efficient and straightforward way to push updates from a server to a client in real-time. They are particularly well-suited for applications that require continuous data streams but do not need full bidirectional communication. With built-in support in modern browsers, SSE is a reliable choice for many real-time web applications.\n\n## Further reading\n\n- [Using server-sent events - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)\n- [Server-sent Events - javascript.info](https://javascript.info/server-sent-events)\n- [Server-sent Events: A WebSockets alternative ready for another look](https://ably.com/topic/server-sent-events)\n- [What are SSE (Server-Sent Events) and how do they work?](https://bunny.net/academy/http/what-is-sse-server-sent-events-and-how-do-they-work/)\n"
  },
  {
    "path": "questions/what-are-server-sent-events/metadata.json",
    "content": "{\n  \"slug\": \"what-are-server-sent-events\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"networking\"],\n  \"importance\": \"medium\",\n  \"ranking\": 440,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/what-are-server-sent-events/zh-CN.mdx",
    "content": "---\ntitle: 什么是服务器发送事件？\n---\n\n## TL;DR\n\n[服务器发送事件 (SSE)](https://html.spec.whatwg.org/multipage/comms.html#the-eventsource-interface) 是一种标准，允许网页通过 HTTP 连接从服务器接收自动更新。服务器发送事件与 `EventSource` 实例一起使用，该实例打开与服务器的连接，并允许客户端从服务器接收事件。服务器发送事件创建的连接是持久的（类似于 `WebSocket`），但是有一些区别：\n\n| 属性 | `WebSocket` | `EventSource` |\n| --- | --- | --- |\n| 方向 | 双向 – 客户端和服务器都可以交换消息 | 单向 – 只有服务器发送数据 |\n| 数据类型 | 二进制和文本数据 | 仅文本数据 |\n| 协议 | WebSocket 协议 (`ws://`) | 常规 HTTP (`http://`) |\n\n**创建事件源**\n\n```js\nconst eventSource = new EventSource('/sse-stream');\n```\n\n**监听事件**\n\n```js\n// 建立连接时触发。\neventSource.addEventListener('open', () => {\n  console.log('连接已打开');\n});\n\n// 从服务器收到消息时触发。\neventSource.addEventListener('message', (event) => {\n  console.log('收到消息：', event.data);\n});\n\n// 发生错误时触发。\neventSource.addEventListener('error', (error) => {\n  console.error('发生错误：', error);\n});\n```\n\n**从服务器发送事件**\n\n```js\nconst express = require('express');\nconst app = express();\n\napp.get('/sse-stream', (req, res) => {\n  // `Content-Type` 需要设置为 `text/event-stream`。\n  res.setHeader('Content-Type', 'text/event-stream');\n  res.setHeader('Cache-Control', 'no-cache');\n  res.setHeader('Connection', 'keep-alive');\n\n  // 每条消息都应以 data 开头。\n  const sendEvent = (data) => res.write(`data: ${data}\\n\\n`);\n\n  sendEvent('来自服务器的问候');\n\n  const intervalId = setInterval(() => sendEvent(new Date().toString()), 1000);\n\n  res.on('close', () => {\n    console.log('客户端关闭连接');\n    clearInterval(intervalId);\n  });\n});\n\napp.listen(3000, () => console.log('服务器已在端口 3000 启动'));\n```\n\n在此示例中，服务器最初发送“来自服务器的问候”消息，然后每秒发送当前日期。连接保持活动状态，直到客户端将其关闭\n\n***\n\n## 服务器发送事件 (SSE)\n\n服务器发送事件 (SSE) 是一种标准，允许服务器通过单个、长连接的 HTTP 连接将更新推送到 Web 客户端。它支持实时更新，而无需客户端不断轮询服务器以获取新数据。\n\n## SSE 的工作原理\n\n1. 客户端创建一个新的 `EventSource` 对象，传递将生成事件流的 `服务器端` 脚本的 URL：\n\n   ```js\n   const eventSource = new EventSource('/event-stream');\n   ```\n\n2. 服务器端脚本设置适当的标头以指示它将发送事件流 (`Content-Type: text/event-stream`)，然后开始向客户端发送事件。\n\n3. 服务器发送的每个事件都遵循特定的格式，包含 `event`、`data` 和 `id` 等字段。例如：\n\n   ```js\n   event: message\n   data: Hello, world!\n\n   event: update\n   id: 123\n   data: {\"temperature\": 25, \"humidity\": 60}\n   ```\n\n4. 在客户端，`EventSource` 对象接收这些事件并将其作为浏览器事件分派，可以使用事件侦听器或 `onmessage` 事件处理程序来处理这些事件：\n\n   ```js\n   eventSource.onmessage = function (event) {\n     console.log('Received message:', event.data);\n   };\n\n   eventSource.addEventListener('update', function (event) {\n     console.log('Received update:', JSON.parse(event.data));\n   });\n   ```\n\n5. 如果连接断开，`EventSource` 对象会自动处理重新连接，并且可以使用 `Last-Event-ID HTTP 标头` 从上次接收到的事件 ID 恢复事件流。\n\n## SSE 功能\n\n* **单向**：只有服务器才能向客户端发送数据。对于双向通信，Web 套接字将更合适。\n* **重试机制**：如果连接失败，客户端将重试连接，重试间隔由服务器的 `retry:` 字段指定。\n* **仅文本数据**：SSE 只能传输文本数据，这意味着在传输之前需要对二进制数据进行编码（例如，Base64）。对于需要传输大型二进制有效负载的应用程序，这可能会导致开销增加和效率低下。\n* **内置浏览器支持**：受大多数现代浏览器支持，无需其他库。\n* **事件类型**：SSE 使用 `event:` 字段支持自定义事件类型，允许对消息进行分类。\n* **`Last-Event-Id`**：客户端在重新连接时发送 `Last-Event-Id` 标头，允许服务器从上次接收到的事件恢复流。但是，没有内置的机制来重放断开连接期间错过的事件。您可能需要实现一种机制来处理错过的事件，例如使用 `Last-Event-Id` 标头。\n* **连接限制**：浏览器对并发 SSE 连接的最大数量有限制，通常每个域大约 6 个。如果需要从同一客户端建立多个 SSE 连接，这可能会成为瓶颈。使用 HTTP/2 将缓解此问题。\n\n## 在 JavaScript 中实现 SSE\n\n以下代码演示了客户端和服务器上 SSE 的最小实现：\n\n* 服务器设置适当的标头以建立 SSE 连接。\n* 消息每 5 秒发送到客户端。\n* 当客户端断开连接时，服务器清理间隔并结束响应。\n\n在客户端上：\n\n```js\n// Create a new EventSource object\nconst eventSource = new EventSource('/sse');\n\n// Event listener for receiving messages\neventSource.onmessage = function (event) {\n  console.log('New message:', event.data);\n};\n\n// Event listener for errors\neventSource.onerror = function (error) {\n  console.error('Error occurred:', error);\n};\n\n// Optional: Event listener for open connection\neventSource.onopen = function () {\n  console.log('Connection opened');\n};\n```\n\n在服务器上：\n\n```js\nconst http = require('http');\n\nhttp\n  .createServer((req, res) => {\n    if (req.url === '/sse') {\n      // Set headers for SSE\n      res.writeHead(200, {\n        'Content-Type': 'text/event-stream',\n        'Cache-Control': 'no-cache',\n        Connection: 'keep-alive',\n      });\n\n      // Function to send a message\n      const sendMessage = (message) => {\n        res.write(`data: ${message}\\n\\n`); // Messages are delimited with double line breaks.\n      };\n\n      // Send a message every 5 seconds\n      const intervalId = setInterval(() => {\n        sendMessage(`Current time: ${new Date().toLocaleTimeString()}`);\n      }, 5000);\n\n      // Handle client disconnect\n      req.on('close', () => {\n        clearInterval(intervalId);\n        res.end();\n      });\n    } else {\n      res.writeHead(404);\n      res.end();\n    }\n  })\n  .listen(8080, () => {\n    console.log('SSE server running on port 8080');\n  });\n```\n\n## 总结\n\n服务器发送事件提供了一种高效且直接的方式，可以将更新从服务器推送到客户端。它们特别适用于需要连续数据流但不需要完全双向通信的应用程序。由于现代浏览器内置了支持，SSE 是许多实时 Web 应用程序的可靠选择。\n\n## 延伸阅读\n\n* [使用服务器发送事件 - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)\n* [服务器发送事件 - javascript.info](https://javascript.info/server-sent-events)\n* [服务器发送事件：一个准备好再次审视的 WebSockets 替代方案](https://ably.com/topic/server-sent-events)\n* [什么是 SSE（服务器发送事件）以及它们如何工作？](https://bunny.net/academy/http/what-is-sse-server-sent-events-and-how-do-they-work/)\n"
  },
  {
    "path": "questions/what-are-sets-and-maps-and-how-are-they-used/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"3d261f3d\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"34bc80c5\",\n        \"1f91b5dd\",\n        \"2a7816d0\",\n        \"1e0a1760\",\n        \"3e35102c\",\n        \"ee945bdb\",\n        \"e86d7b3f\",\n        \"700ddb74\",\n        \"203ebe3f\",\n        \"86995dff\",\n        \"578a5b43\",\n        \"19c254ba\",\n        \"56281c57\",\n        \"2abf5c73\",\n        \"d4a2e6b5\",\n        \"cc2b3f0e\",\n        \"6308073\",\n        \"bbd54685\",\n        \"645d5fef\",\n        \"86995dff\",\n        \"611209ef\",\n        \"19c254ba\",\n        \"29df1c46\",\n        \"1f4770e5\",\n        \"a34dcc85\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"34bc80c5\",\n        \"1f91b5dd\",\n        \"2a7816d0\",\n        \"1e0a1760\",\n        \"3e35102c\",\n        \"ee945bdb\",\n        \"e86d7b3f\",\n        \"700ddb74\",\n        \"203ebe3f\",\n        \"86995dff\",\n        \"578a5b43\",\n        \"19c254ba\",\n        \"56281c57\",\n        \"2abf5c73\",\n        \"d4a2e6b5\",\n        \"cc2b3f0e\",\n        \"6308073\",\n        \"bbd54685\",\n        \"645d5fef\",\n        \"86995dff\",\n        \"611209ef\",\n        \"19c254ba\",\n        \"29df1c46\",\n        \"1f4770e5\",\n        \"a34dcc85\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-sets-and-maps-and-how-are-they-used/en-US.mdx",
    "content": "---\ntitle: What are `Set`s and `Map`s and how are they used?\n---\n\n## TL;DR\n\n`Set`s and `Map`s are built-in JavaScript objects that help manage collections of data. A `Set` is a collection of unique values, while a `Map` is a collection of key-value pairs where keys can be of any type. `Set`s are useful for storing unique items, and `Map`s are useful for associating values with keys.\n\n```js live\n// Set example\nlet mySet = new Set([1, 2, 3, 3]); // Set {1, 2, 3} (duplicate values are not added)\nmySet.add(4);\nconsole.log(mySet); // Set {1, 2, 3, 4}\n\n// Map example\nlet myMap = new Map();\nmyMap.set('key1', 'value1');\nmyMap.set('key2', 'value2');\nconsole.log(myMap.get('key1')); // 'value1'\n```\n\n---\n\n## Set\n\n### What is a `Set`?\n\nA `Set` is a collection of values where each value must be unique. It is similar to an array but does not allow duplicate values.\n\n### How to create a `Set`\n\nYou can create a `Set` using the `Set` constructor:\n\n```js live\nlet mySet = new Set([1, 2, 3, 3]);\nconsole.log(mySet); // Set {1, 2, 3}\n```\n\n### Common methods\n\n- `add(value)`: Adds a new element with the given value to the `Set`.\n- `delete(value)`: Removes the element associated with the value.\n- `has(value)`: Returns a boolean indicating whether the value exists in the `Set`.\n- `clear()`: Removes all elements from the `Set`.\n- `size`: Returns the number of elements in the `Set`.\n\n### Example usage\n\n```js live\nlet mySet = new Set();\nmySet.add(1);\nmySet.add(2);\nmySet.add(2); // Duplicate value, will not be added\nconsole.log(mySet.has(1)); // true\nconsole.log(mySet.size); // 2\nmySet.delete(1);\nconsole.log(mySet.has(1)); // false\nmySet.clear();\nconsole.log(mySet.size); // 0\n```\n\n## Map\n\n### What is a `Map`?\n\nA `Map` is a collection of key-value pairs where keys can be of any type, including objects, functions, and primitives.\n\n### How to create a `Map`\n\nYou can create a `Map` using the `Map` constructor:\n\n```js live\nlet myMap = new Map();\nmyMap.set('key1', 'value1');\nmyMap.set('key2', 'value2');\nconsole.log(myMap); // Map { key1: \"value1\", key2: \"value2\" }\n```\n\n### Common methods\n\n- `set(key, value)`: Adds or updates an element with the specified key and value.\n- `get(key)`: Returns the value associated with the key.\n- `delete(key)`: Removes the element associated with the key.\n- `has(key)`: Returns a boolean indicating whether the key exists in the `Map`.\n- `clear()`: Removes all elements from the `Map`.\n- `size`: Returns the number of elements in the `Map`.\n\n### Example usage\n\n```js live\nlet myMap = new Map();\nmyMap.set('key1', 'value1');\nmyMap.set('key2', 'value2');\nconsole.log(myMap.get('key1')); // 'value1'\nconsole.log(myMap.has('key2')); // true\nconsole.log(myMap.size); // 2\nmyMap.delete('key1');\nconsole.log(myMap.has('key1')); // false\nmyMap.clear();\nconsole.log(myMap.size); // 0\n```\n\n## Further reading\n\n- [MDN Web Docs: Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)\n- [MDN Web Docs: Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n- [JavaScript.info: Set and Map](https://javascript.info/map-set)\n"
  },
  {
    "path": "questions/what-are-sets-and-maps-and-how-are-they-used/metadata.json",
    "content": "{\n  \"slug\": \"what-are-sets-and-maps-and-how-are-they-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Sets & Maps\"\n}\n"
  },
  {
    "path": "questions/what-are-sets-and-maps-and-how-are-they-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是 `Set` 和 `Map` 以及如何使用它们？\n---\n\n## TL;DR\n\n`Set` 和 `Map` 是内置的 JavaScript 对象，可帮助管理数据集合。`Set` 是唯一值的集合，而 `Map` 是键值对的集合，其中键可以是任何类型。`Set` 适用于存储唯一项，而 `Map` 适用于将值与键关联。\n\n```js live\n// Set example\nlet mySet = new Set([1, 2, 3, 3]); // Set {1, 2, 3} (duplicate values are not added)\nmySet.add(4);\nconsole.log(mySet); // Set {1, 2, 3, 4}\n\n// Map example\nlet myMap = new Map();\nmyMap.set('key1', 'value1');\nmyMap.set('key2', 'value2');\nconsole.log(myMap.get('key1')); // 'value1'\n```\n\n***\n\n## Set\n\n### 什么是 `Set`？\n\n`Set` 是值的集合，其中每个值都必须是唯一的。它类似于数组，但不允许重复值。\n\n### 如何创建 `Set`\n\n您可以使用 `Set` 构造函数创建 `Set`：\n\n```js live\nlet mySet = new Set([1, 2, 3, 3]);\nconsole.log(mySet); // Set {1, 2, 3}\n```\n\n### 常用方法\n\n* `add(value)`: 将具有给定值的元素添加到 `Set`。\n* `delete(value)`: 删除与该值关联的元素。\n* `has(value)`: 返回一个布尔值，指示该值是否存在于 `Set` 中。\n* `clear()`: 从 `Set` 中删除所有元素。\n* `size`: 返回 `Set` 中的元素数量。\n\n### 使用示例\n\n```js live\nlet mySet = new Set();\nmySet.add(1);\nmySet.add(2);\nmySet.add(2); // Duplicate value, will not be added\nconsole.log(mySet.has(1)); // true\nconsole.log(mySet.size); // 2\nmySet.delete(1);\nconsole.log(mySet.has(1)); // false\nmySet.clear();\nconsole.log(mySet.size); // 0\n```\n\n## Map\n\n### 什么是 `Map`？\n\n`Map` 是键值对的集合，其中键可以是任何类型，包括对象、函数和基本类型。\n\n### 如何创建 `Map`\n\n您可以使用 `Map` 构造函数创建 `Map`：\n\n```js live\nlet myMap = new Map();\nmyMap.set('key1', 'value1');\nmyMap.set('key2', 'value2');\nconsole.log(myMap); // Map { key1: \"value1\", key2: \"value2\" }\n```\n\n### 常用方法\n\n* `set(key, value)`: 添加或更新具有指定键和值的一个元素。\n* `get(key)`: 返回与该键关联的值。\n* `delete(key)`: 移除与该键关联的元素。\n* `has(key)`: 返回一个布尔值，指示该键是否存在于 `Map` 中。\n* `clear()`: 从 `Map` 中移除所有元素。\n* `size`: 返回 `Map` 中元素的数量。\n\n### 使用示例\n\n```js live\nlet myMap = new Map();\nmyMap.set('key1', 'value1');\nmyMap.set('key2', 'value2');\nconsole.log(myMap.get('key1')); // 'value1'\nconsole.log(myMap.has('key2')); // true\nconsole.log(myMap.size); // 2\nmyMap.delete('key1');\nconsole.log(myMap.has('key1')); // false\nmyMap.clear();\nconsole.log(myMap.size); // 0\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)\n* [MDN Web Docs: Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n* [JavaScript.info: Set and Map](https://javascript.info/map-set)\n"
  },
  {
    "path": "questions/what-are-some-best-practices-for-handling-sensitive-data-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"103fb802\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"5cb4cb2a\",\n        \"2a7816d0\",\n        \"4dfad4fa\",\n        \"3222d51c\",\n        \"db93c569\",\n        \"fa093fb2\",\n        \"c3a9a22a\",\n        \"ec85ba13\",\n        \"cc899d4a\",\n        \"80e5991f\",\n        \"2b208b45\",\n        \"17683845\",\n        \"58103032\",\n        \"bf8819d8\",\n        \"35dee7ab\",\n        \"62e1f24a\",\n        \"e3a5e55f\",\n        \"f3220a13\",\n        \"8cbc1e25\",\n        \"c9e53633\",\n        \"1f4770e5\",\n        \"9ab11a3\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"5cb4cb2a\",\n        \"2a7816d0\",\n        \"4dfad4fa\",\n        \"3222d51c\",\n        \"db93c569\",\n        \"fa093fb2\",\n        \"c3a9a22a\",\n        \"ec85ba13\",\n        \"cc899d4a\",\n        \"80e5991f\",\n        \"2b208b45\",\n        \"17683845\",\n        \"58103032\",\n        \"bf8819d8\",\n        \"35dee7ab\",\n        \"62e1f24a\",\n        \"e3a5e55f\",\n        \"f3220a13\",\n        \"8cbc1e25\",\n        \"c9e53633\",\n        \"1f4770e5\",\n        \"9ab11a3\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-some-best-practices-for-handling-sensitive-data-in-javascript/en-US.mdx",
    "content": "---\ntitle: What are some best practices for handling sensitive data in JavaScript?\n---\n\n## TL;DR\n\nHandling sensitive data in JavaScript requires careful attention to security practices. Avoid storing sensitive data in client-side storage like localStorage or sessionStorage. Use HTTPS to encrypt data in transit. Implement proper authentication and authorization mechanisms. Sanitize and validate all inputs to prevent injection attacks. Consider using environment variables for sensitive data in server-side code.\n\n---\n\n## Best practices for handling sensitive data in JavaScript\n\n### Avoid client-side storage for sensitive data\n\nStoring sensitive data such as tokens, passwords, or personal information in client-side storage like `localStorage` or `sessionStorage` is risky because it can be easily accessed by malicious scripts. Instead, use secure cookies with the `HttpOnly` and `Secure` flags.\n\n```js\n// Example of setting a secure cookie in an Express.js server\nres.cookie('token', token, { httpOnly: true, secure: true });\n```\n\n### Use HTTPS\n\nAlways use HTTPS to encrypt data in transit between the client and server. This ensures that sensitive data is not exposed to eavesdroppers.\n\n### Implement proper authentication and authorization\n\nEnsure that your application has robust authentication and authorization mechanisms. Use libraries and frameworks that are well-tested and maintained.\n\n```js\n// Example of using JSON Web Tokens (JWT) for authentication\nconst jwt = require('jsonwebtoken');\n\nconst token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, {\n  expiresIn: '1h',\n});\n```\n\n### Sanitize and validate inputs\n\nAlways sanitize and validate user inputs to prevent injection attacks such as SQL injection and cross-site scripting (XSS).\n\n```js\n// Example of input validation using the express-validator library\nconst { body, validationResult } = require('express-validator');\n\napp.post(\n  '/submit',\n  [body('email').isEmail(), body('password').isLength({ min: 5 })],\n  (req, res) => {\n    const errors = validationResult(req);\n    if (!errors.isEmpty()) {\n      return res.status(400).json({ errors: errors.array() });\n    }\n    // Proceed with handling the request\n  },\n);\n```\n\n### Use environment variables\n\nStore sensitive data such as API keys and database credentials in environment variables rather than hardcoding them in your source code.\n\n```js\n// Example of accessing environment variables in Node.js\nconst dbPassword = process.env.DB_PASSWORD;\n```\n\n### Regularly update dependencies\n\nKeep your dependencies up to date to ensure that you have the latest security patches. Use tools like `npm audit` to identify and fix vulnerabilities.\n\n```bash\n# Example of running npm audit\nnpm audit fix\n```\n\n## Further reading\n\n- [OWASP Top Ten Security Risks](https://owasp.org/www-project-top-ten/)\n- [MDN Web Docs: HTTPS](https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security)\n- [Express.js Security Best Practices](https://expressjs.com/en/advanced/best-practice-security.html)\n- [JSON Web Tokens (JWT) Introduction](https://jwt.io/introduction/)\n- [express-validator Documentation](https://express-validator.github.io/docs/)\n"
  },
  {
    "path": "questions/what-are-some-best-practices-for-handling-sensitive-data-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"what-are-some-best-practices-for-handling-sensitive-data-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Security\"\n}\n"
  },
  {
    "path": "questions/what-are-some-best-practices-for-handling-sensitive-data-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 在 JavaScript 中处理敏感数据的一些最佳实践是什么？\n---\n\n## TL;DR\n\n在 JavaScript 中处理敏感数据需要特别注意安全实践。 避免将敏感数据存储在客户端存储中，如 localStorage 或 sessionStorage。 使用 HTTPS 加密传输中的数据。 实施适当的身份验证和授权机制。 净化和验证所有输入以防止注入攻击。 考虑在服务器端代码中使用环境变量来存储敏感数据。\n\n***\n\n## 在 JavaScript 中处理敏感数据的最佳实践\n\n### 避免将敏感数据存储在客户端\n\n将敏感数据（如令牌、密码或个人信息）存储在客户端存储（如 `localStorage` 或 `sessionStorage`）中存在风险，因为恶意脚本可以轻松访问它。 而是使用带有 `HttpOnly` 和 `Secure` 标志的安全 cookie。\n\n```js\n// Example of setting a secure cookie in an Express.js server\nres.cookie('token', token, { httpOnly: true, secure: true });\n```\n\n### 使用 HTTPS\n\n始终使用 HTTPS 加密客户端和服务器之间传输的数据。 这可确保敏感数据不会暴露给窃听者。\n\n### 实施适当的身份验证和授权\n\n确保您的应用程序具有强大的身份验证和授权机制。 使用经过充分测试和维护的库和框架。\n\n```js\n// Example of using JSON Web Tokens (JWT) for authentication\nconst jwt = require('jsonwebtoken');\n\nconst token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, {\n  expiresIn: '1h',\n});\n```\n\n### 净化和验证输入\n\n始终净化和验证用户输入，以防止注入攻击，例如 SQL 注入和跨站点脚本 (XSS)。\n\n```js\n// Example of input validation using the express-validator library\nconst { body, validationResult } = require('express-validator');\n\napp.post(\n  '/submit',\n  [body('email').isEmail(), body('password').isLength({ min: 5 })],\n  (req, res) => {\n    const errors = validationResult(req);\n    if (!errors.isEmpty()) {\n      return res.status(400).json({ errors: errors.array() });\n    }\n    // Proceed with handling the request\n  },\n);\n```\n\n### 使用环境变量\n\n将敏感数据（如 API 密钥和数据库凭据）存储在环境变量中，而不是在源代码中对其进行硬编码。\n\n```js\n// Example of accessing environment variables in Node.js\nconst dbPassword = process.env.DB_PASSWORD;\n```\n\n### 定期更新依赖项\n\n保持您的依赖项为最新，以确保您拥有最新的安全补丁。使用 `npm audit` 等工具来识别和修复漏洞。\n\n```bash\n# Example of running npm audit\nnpm audit fix\n```\n\n## 延伸阅读\n\n* [OWASP 十大安全风险](https://owasp.org/www-project-top-ten/)\n* [MDN Web 文档：HTTPS](https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security)\n* [Express.js 安全最佳实践](https://expressjs.com/en/advanced/best-practice-security.html)\n* [JSON Web Tokens (JWT) 简介](https://jwt.io/introduction/)\n* [express-validator 文档](https://express-validator.github.io/docs/)\n"
  },
  {
    "path": "questions/what-are-some-best-practices-for-writing-maintainable-and-effective-tests/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"9891f6dc\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"6a50b786\",\n        \"2a7816d0\",\n        \"683ef6c1\",\n        \"c56b37b3\",\n        \"391c3ab8\",\n        \"dbe7da10\",\n        \"7428775f\",\n        \"3f9e27d3\",\n        \"ccbd3c1f\",\n        \"d8e3d3fb\",\n        \"1df0f7b8\",\n        \"ae21dbed\",\n        \"610a9440\",\n        \"193c9794\",\n        \"2b7727c1\",\n        \"51123f9\",\n        \"8fb04426\",\n        \"21e2ead\",\n        \"d041b6ce\",\n        \"68df128b\",\n        \"50b8876a\",\n        \"a93c6d57\",\n        \"6326c70f\",\n        \"29899051\",\n        \"f9e47e8b\",\n        \"cc580d1d\",\n        \"ed153471\",\n        \"1f4770e5\",\n        \"29af9e07\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"6a50b786\",\n        \"2a7816d0\",\n        \"683ef6c1\",\n        \"c56b37b3\",\n        \"391c3ab8\",\n        \"dbe7da10\",\n        \"7428775f\",\n        \"3f9e27d3\",\n        \"ccbd3c1f\",\n        \"d8e3d3fb\",\n        \"1df0f7b8\",\n        \"ae21dbed\",\n        \"610a9440\",\n        \"193c9794\",\n        \"2b7727c1\",\n        \"51123f9\",\n        \"8fb04426\",\n        \"21e2ead\",\n        \"d041b6ce\",\n        \"68df128b\",\n        \"50b8876a\",\n        \"a93c6d57\",\n        \"6326c70f\",\n        \"29899051\",\n        \"f9e47e8b\",\n        \"cc580d1d\",\n        \"ed153471\",\n        \"1f4770e5\",\n        \"29af9e07\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-some-best-practices-for-writing-maintainable-and-effective-tests/en-US.mdx",
    "content": "---\ntitle: What are some best practices for writing maintainable and effective tests in JavaScript?\n---\n\n## TL;DR\n\nTo write maintainable and effective tests, ensure they are clear, concise, and focused on a single behavior. Use descriptive names for test cases and avoid hardcoding values. Mock external dependencies and keep tests isolated. Regularly review and refactor tests to keep them up-to-date with the codebase.\n\n---\n\n## Best practices for writing maintainable and effective tests\n\n### Write clear and descriptive test names\n\n- Use names that clearly describe the behavior being tested\n- Avoid abbreviations and keep names meaningful\n\n### Keep tests focused\n\n- Ensure each test case focuses on a single behavior or functionality\n- Avoid testing multiple things in a single test\n\n### Use the AAA pattern (Arrange, Act, Assert)\n\n- **Arrange**: Set up the initial state and dependencies\n- **Act**: Execute the behavior being tested\n- **Assert**: Verify the outcome\n\n```js\ntest('should add two numbers correctly', () => {\n  // Arrange\n  const a = 1;\n  const b = 2;\n\n  // Act\n  const result = add(a, b);\n\n  // Assert\n  expect(result).toBe(3);\n});\n```\n\n### Avoid hardcoding values\n\n- Use variables and constants to make tests more readable and maintainable\n\n```js\nconst input = 5;\nconst expectedOutput = 25;\n\ntest('should return the square of a number', () => {\n  const result = square(input);\n  expect(result).toBe(expectedOutput);\n});\n```\n\n### Mock external dependencies\n\n- Use mocking libraries to simulate external dependencies like APIs, databases, or third-party services\n- Keep tests isolated from external factors\n\n```js\njest.mock('axios');\n\ntest('should fetch data from API', async () => {\n  const data = { id: 1, name: 'John Doe' };\n  axios.get.mockResolvedValue({ data });\n\n  const result = await fetchData();\n\n  expect(result).toEqual(data);\n});\n```\n\n### Keep tests isolated\n\n- Ensure tests do not depend on each other\n- Reset state and clean up after each test\n\n```js\nafterEach(() => {\n  jest.clearAllMocks();\n});\n```\n\n### Regularly review and refactor tests\n\n- Keep tests up-to-date with changes in the codebase\n- Remove redundant or outdated tests\n- Refactor tests to improve readability and maintainability\n\n### Use test coverage tools\n\n- Measure test coverage to identify untested parts of the codebase\n- Aim for high coverage but prioritize meaningful tests over 100% coverage\n\n### Write tests before fixing bugs\n\n- Reproduce the bug with a failing test\n- Fix the bug and ensure the test passes\n\n### Use a consistent style\n\n- Follow a consistent style and conventions for writing tests\n- Use linters and formatters to enforce consistency\n\n## Further reading\n\n- [Jest documentation](https://jestjs.io/docs/getting-started)\n- [Mocha documentation](https://mochajs.org/)\n- [Testing Library documentation](https://testing-library.com/docs/)\n- [Effective testing with Jest](https://kentcdodds.com/blog/effective-snapshot-testing)\n- [Test-driven development (TDD)](https://martinfowler.com/bliki/TestDrivenDevelopment.html)\n"
  },
  {
    "path": "questions/what-are-some-best-practices-for-writing-maintainable-and-effective-tests/metadata.json",
    "content": "{\n  \"slug\": \"what-are-some-best-practices-for-writing-maintainable-and-effective-tests\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"testing\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Testing\"\n}\n"
  },
  {
    "path": "questions/what-are-some-best-practices-for-writing-maintainable-and-effective-tests/zh-CN.mdx",
    "content": "---\ntitle: 在 JavaScript 中编写可维护且有效的测试的最佳实践是什么？\n---\n\n## 总结\n\n要编写可维护且有效的测试，请确保它们清晰、简洁，并侧重于单一行为。对测试用例使用描述性名称，并避免硬编码值。模拟外部依赖项并保持测试隔离。定期审查和重构测试，以使其与代码库保持同步。\n\n***\n\n## 编写可维护且有效的测试的最佳实践\n\n### 编写清晰且具有描述性的测试名称\n\n* 使用清晰描述被测行为的名称\n* 避免使用缩写，并保持名称有意义\n\n### 保持测试专注\n\n* 确保每个测试用例都侧重于单一行为或功能\n* 避免在单个测试中测试多项内容\n\n### 使用 AAA 模式（Arrange, Act, Assert）\n\n* **Arrange**：设置初始状态和依赖项\n* **Act**：执行被测行为\n* **Assert**：验证结果\n\n```js\ntest('should add two numbers correctly', () => {\n  // Arrange\n  const a = 1;\n  const b = 2;\n\n  // Act\n  const result = add(a, b);\n\n  // Assert\n  expect(result).toBe(3);\n});\n```\n\n### 避免硬编码值\n\n* 使用变量和常量使测试更具可读性和可维护性\n\n```js\nconst input = 5;\nconst expectedOutput = 25;\n\ntest('should return the square of a number', () => {\n  const result = square(input);\n  expect(result).toBe(expectedOutput);\n});\n```\n\n### 模拟外部依赖项\n\n* 使用模拟库来模拟外部依赖项，如 API、数据库或第三方服务\n* 保持测试与外部因素隔离\n\n```js\njest.mock('axios');\n\ntest('should fetch data from API', async () => {\n  const data = { id: 1, name: 'John Doe' };\n  axios.get.mockResolvedValue({ data });\n\n  const result = await fetchData();\n\n  expect(result).toEqual(data);\n});\n```\n\n### 保持测试隔离\n\n* 确保测试不相互依赖\n* 在每次测试后重置状态并清理\n\n```js\nafterEach(() => {\n  jest.clearAllMocks();\n});\n```\n\n### 定期审查和重构测试\n\n* 使测试与代码库中的更改保持同步\n* 删除冗余或过时的测试\n* 重构测试以提高可读性和可维护性\n\n### 使用测试覆盖率工具\n\n* 衡量测试覆盖率以识别代码库中未测试的部分\n* 争取高覆盖率，但优先考虑有意义的测试而不是 100% 的覆盖率\n\n### 在修复错误之前编写测试\n\n* 用失败的测试重现错误\n* 修复错误并确保测试通过\n\n### 使用一致的风格\n\n* 遵循编写测试的一致风格和约定\n* 使用 linters 和格式化程序来强制一致性\n\n## 延伸阅读\n\n* [Jest documentation](https://jestjs.io/docs/getting-started)\n* [Mocha documentation](https://mochajs.org/)\n* [Testing Library documentation](https://testing-library.com/docs/)\n* [Effective testing with Jest](https://kentcdodds.com/blog/effective-snapshot-testing)\n* [Test-driven development (TDD)](https://martinfowler.com/bliki/TestDrivenDevelopment.html)\n"
  },
  {
    "path": "questions/what-are-some-common-performance-bottlenecks-in-javascript-applications/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"214e612b\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"9d40d291\",\n        \"2a7816d0\",\n        \"4f4d41e\",\n        \"3ec06181\",\n        \"42bfdf1f\",\n        \"e1b03eaa\",\n        \"b356f884\",\n        \"8985808d\",\n        \"2f749967\",\n        \"18674338\",\n        \"fcbf17fa\",\n        \"567451fb\",\n        \"1c6c0071\",\n        \"12a25703\",\n        \"6f79dc80\",\n        \"9283bde8\",\n        \"f0864546\",\n        \"99d08231\",\n        \"9d2be4e0\",\n        \"d4dca9bc\",\n        \"75e5d34a\",\n        \"ca9a5cfe\",\n        \"df15d3ce\",\n        \"7f164625\",\n        \"eca56594\",\n        \"bb2003e5\",\n        \"77e9bf08\",\n        \"b44f4bc9\",\n        \"531ec191\",\n        \"16ec829f\",\n        \"d75cc67d\",\n        \"9aa3760d\",\n        \"1f4770e5\",\n        \"64321219\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"9d40d291\",\n        \"2a7816d0\",\n        \"4f4d41e\",\n        \"3ec06181\",\n        \"42bfdf1f\",\n        \"e1b03eaa\",\n        \"b356f884\",\n        \"8985808d\",\n        \"2f749967\",\n        \"18674338\",\n        \"fcbf17fa\",\n        \"567451fb\",\n        \"1c6c0071\",\n        \"12a25703\",\n        \"6f79dc80\",\n        \"9283bde8\",\n        \"f0864546\",\n        \"99d08231\",\n        \"9d2be4e0\",\n        \"d4dca9bc\",\n        \"75e5d34a\",\n        \"ca9a5cfe\",\n        \"df15d3ce\",\n        \"7f164625\",\n        \"eca56594\",\n        \"bb2003e5\",\n        \"77e9bf08\",\n        \"b44f4bc9\",\n        \"531ec191\",\n        \"16ec829f\",\n        \"d75cc67d\",\n        \"9aa3760d\",\n        \"1f4770e5\",\n        \"64321219\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-some-common-performance-bottlenecks-in-javascript-applications/en-US.mdx",
    "content": "---\ntitle: What are some common performance bottlenecks in JavaScript applications?\n---\n\n## TL;DR\n\nCommon performance bottlenecks in JavaScript applications include inefficient DOM manipulation, excessive use of global variables, blocking the main thread with heavy computations, memory leaks, and improper use of asynchronous operations. To mitigate these issues, you can use techniques like debouncing and throttling, optimizing DOM updates, and leveraging web workers for heavy computations.\n\n---\n\n## Inefficient DOM manipulation\n\n### Frequent DOM updates\n\nFrequent DOM updates can be costly because the browser has to re-render the page each time the DOM changes. Batch DOM updates together to minimize reflows and repaints.\n\n```js\n// Inefficient\nfor (let i = 0; i < 1000; i++) {\n  const div = document.createElement('div');\n  div.textContent = i;\n  document.body.appendChild(div);\n}\n\n// Efficient\nconst fragment = document.createDocumentFragment();\nfor (let i = 0; i < 1000; i++) {\n  const div = document.createElement('div');\n  div.textContent = i;\n  fragment.appendChild(div);\n}\ndocument.body.appendChild(fragment);\n```\n\n### Layout thrashing\n\nLayout thrashing occurs when you read and write to the DOM repeatedly, causing multiple reflows and repaints. Minimize layout thrashing by batching reads and writes separately.\n\n```js\n// Inefficient\nboxes.forEach((box) => {\n  const height = box.offsetHeight; // Read\n  box.style.height = `${height + 10}px`; // Write\n});\n\n// Efficient\n// Batch read\nconst heights = [];\nboxes.forEach((box) => {\n  heights.push(box.offsetHeight);\n});\n\n// Batch write\nboxes.forEach((box, i) => {\n  box.style.height = `${heights[i] + 10}px`;\n});\n```\n\n## Excessive use of global variables\n\nGlobal variables can lead to memory leaks and make the code harder to maintain. Use local variables and closures to limit the scope of variables.\n\n```js\n// Inefficient\nvar globalVar = 'I am global';\n\n// Efficient\nfunction myFunction() {\n  let localVar = 'I am local';\n}\n```\n\n## Blocking the main thread\n\n### Heavy computations\n\nHeavy computations can block the main thread, making the UI unresponsive. Use web workers to offload heavy computations to a background thread.\n\n```js\n// Main thread\nconst worker = new Worker('worker.js');\nworker.postMessage('start');\n\n// worker.js\nself.onmessage = function (e) {\n  if (e.data === 'start') {\n    // Perform heavy computation\n    self.postMessage('done');\n  }\n};\n```\n\n### Synchronous operations\n\nAvoid synchronous operations like `alert`, `prompt`, and synchronous XHR requests, as they block the main thread.\n\n```js\n// Inefficient\nalert('This blocks the main thread');\n\n// Efficient\nconsole.log('This does not block the main thread');\n```\n\n## Memory leaks\n\nMemory leaks occur when memory that is no longer needed is not released. Common causes include circular references and unremoved event listeners.\n\n### Circular references\n\n```js\n// Inefficient\nfunction createCircularReference() {\n  const obj1 = {};\n  const obj2 = {};\n  obj1.ref = obj2;\n  obj2.ref = obj1;\n}\n\n// Efficient\nfunction createNonCircularReference() {\n  const obj1 = {};\n  const obj2 = {};\n  obj1.ref = obj2;\n}\n```\n\n### Unremoved event listeners\n\n```js\n// Inefficient\nelement.addEventListener('click', handleClick);\n\n// Efficient\nelement.removeEventListener('click', handleClick);\n```\n\n## Improper use of asynchronous operations\n\n### Unoptimized promises\n\nChain promises properly to avoid blocking the main thread.\n\n```js\n// Inefficient\nfetch('url')\n  .then((response) => response.json())\n  .then((data) => {\n    // Process data\n  });\n\n// Efficient\nasync function fetchData() {\n  const response = await fetch('url');\n  const data = await response.json();\n  // Process data\n}\nfetchData();\n```\n\n### Debouncing and throttling\n\nUse debouncing and throttling to limit the rate of function execution, especially for event handlers.\n\n```js\n// Debouncing\nfunction debounce(func, wait) {\n  let timeout;\n  return function (...args) {\n    clearTimeout(timeout);\n    timeout = setTimeout(() => func.apply(this, args), wait);\n  };\n}\n\n// Throttling\nfunction throttle(func, limit) {\n  let inThrottle;\n  return function (...args) {\n    if (!inThrottle) {\n      func.apply(this, args);\n      inThrottle = true;\n      setTimeout(() => (inThrottle = false), limit);\n    }\n  };\n}\n```\n\n## Further reading\n\n- [MDN Web Docs: Performance](https://developer.mozilla.org/en-US/docs/Web/Performance)\n- [Google Developers: Web Performance Optimization](https://developers.google.com/web/fundamentals/performance)\n"
  },
  {
    "path": "questions/what-are-some-common-performance-bottlenecks-in-javascript-applications/metadata.json",
    "content": "{\n  \"slug\": \"what-are-some-common-performance-bottlenecks-in-javascript-applications\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"performance\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Performance Optimization\"\n}\n"
  },
  {
    "path": "questions/what-are-some-common-performance-bottlenecks-in-javascript-applications/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 应用程序中常见的一些性能瓶颈是什么？\n---\n\n## TL;DR\n\nJavaScript 应用程序中常见的性能瓶颈包括低效的 DOM 操作、过度使用全局变量、使用繁重的计算阻塞主线程、内存泄漏以及不正确地使用异步操作。为了缓解这些问题，您可以使用诸如防抖和节流之类的技术、优化 DOM 更新以及利用 Web Worker 进行繁重的计算。\n\n***\n\n## 低效的 DOM 操作\n\n### 频繁的 DOM 更新\n\n频繁的 DOM 更新可能代价高昂，因为每次 DOM 更改时，浏览器都必须重新渲染页面。将 DOM 更新批量处理在一起，以最大限度地减少回流和重绘。\n\n```js\n// Inefficient\nfor (let i = 0; i < 1000; i++) {\n  const div = document.createElement('div');\n  div.textContent = i;\n  document.body.appendChild(div);\n}\n\n// Efficient\nconst fragment = document.createDocumentFragment();\nfor (let i = 0; i < 1000; i++) {\n  const div = document.createElement('div');\n  div.textContent = i;\n  fragment.appendChild(div);\n}\ndocument.body.appendChild(fragment);\n```\n\n### 布局抖动\n\n当您反复读取和写入 DOM 时，就会发生布局抖动，从而导致多次回流和重绘。通过分别批量处理读取和写入来最大限度地减少布局抖动。\n\n```js\n// Inefficient\nboxes.forEach((box) => {\n  const height = box.offsetHeight; // Read\n  box.style.height = `${height + 10}px`; // Write\n});\n\n// Efficient\n// Batch read\nconst heights = [];\nboxes.forEach((box) => {\n  heights.push(box.offsetHeight);\n});\n\n// Batch write\nboxes.forEach((box, i) => {\n  box.style.height = `${heights[i] + 10}px`;\n});\n```\n\n## 过度使用全局变量\n\n全局变量可能导致内存泄漏，并使代码更难维护。使用局部变量和闭包来限制变量的范围。\n\n```js\n// Inefficient\nvar globalVar = 'I am global';\n\n// Efficient\nfunction myFunction() {\n  let localVar = 'I am local';\n}\n```\n\n## 阻塞主线程\n\n### 繁重的计算\n\n繁重的计算会阻塞主线程，从而导致 UI 无响应。使用 Web Worker 将繁重的计算分流到后台线程。\n\n```js\n// Main thread\nconst worker = new Worker('worker.js');\nworker.postMessage('start');\n\n// worker.js\nself.onmessage = function (e) {\n  if (e.data === 'start') {\n    // Perform heavy computation\n    self.postMessage('done');\n  }\n};\n```\n\n### 同步操作\n\n避免使用 `alert`、`prompt` 等同步操作以及同步 XHR 请求，因为它们会阻塞主线程。\n\n```js\n// Inefficient\nalert('This blocks the main thread');\n\n// Efficient\nconsole.log('This does not block the main thread');\n```\n\n## 内存泄漏\n\n当不再需要的内存未被释放时，就会发生内存泄漏。常见原因包括循环引用和未移除的事件监听器。\n\n### 循环引用\n\n```js\n// Inefficient\nfunction createCircularReference() {\n  const obj1 = {};\n  const obj2 = {};\n  obj1.ref = obj2;\n  obj2.ref = obj1;\n}\n\n// Efficient\nfunction createNonCircularReference() {\n  const obj1 = {};\n  const obj2 = {};\n  obj1.ref = obj2;\n}\n```\n\n### 未移除的事件监听器\n\n```js\n// Inefficient\nelement.addEventListener('click', handleClick);\n\n// Efficient\nelement.removeEventListener('click', handleClick);\n```\n\n## 异步操作使用不当\n\n### 未优化的 Promise\n\n正确地链式调用 Promise，以避免阻塞主线程。\n\n```js\n// Inefficient\nfetch('url')\n  .then((response) => response.json())\n  .then((data) => {\n    // Process data\n  });\n\n// Efficient\nasync function fetchData() {\n  const response = await fetch('url');\n  const data = await response.json();\n  // Process data\n}\nfetchData();\n```\n\n### Debouncing 和 throttling\n\n使用 debouncing 和 throttling 来限制函数执行的速率，尤其是在处理事件处理程序时。\n\n```js\n// Debouncing\nfunction debounce(func, wait) {\n  let timeout;\n  return function (...args) {\n    clearTimeout(timeout);\n    timeout = setTimeout(() => func.apply(this, args), wait);\n  };\n}\n\n// Throttling\nfunction throttle(func, limit) {\n  let inThrottle;\n  return function (...args) {\n    if (!inThrottle) {\n      func.apply(this, args);\n      inThrottle = true;\n      setTimeout(() => (inThrottle = false), limit);\n    }\n  };\n}\n```\n\n## 延伸阅读\n\n* [MDN Web 文档：性能](https://developer.mozilla.org/zh-CN/docs/Web/Performance)\n* [Google Developers：Web 性能优化](https://developers.google.com/web/fundamentals/performance)\n"
  },
  {
    "path": "questions/what-are-some-common-security-headers-and-their-purpose/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"67a753b8\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"43ca4189\",\n        \"edc2b6f1\",\n        \"2a7816d0\",\n        \"e7c7af49\",\n        \"4a793cc4\",\n        \"f83e64ad\",\n        \"1362dcc6\",\n        \"b675949c\",\n        \"5a9cfba\",\n        \"3ad390f9\",\n        \"17d3c818\",\n        \"4e84adb4\",\n        \"4a8a617b\",\n        \"d9fde042\",\n        \"7bc259cd\",\n        \"57735479\",\n        \"74ec24d3\",\n        \"fbbc8b6e\",\n        \"2a0eaea6\",\n        \"cf1be31b\",\n        \"272df81\",\n        \"70fb4fc4\",\n        \"3e2a1f86\",\n        \"7220b399\",\n        \"fec2887a\",\n        \"839194b0\",\n        \"643fa59b\",\n        \"1f4770e5\",\n        \"849f0c72\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"43ca4189\",\n        \"edc2b6f1\",\n        \"2a7816d0\",\n        \"e7c7af49\",\n        \"4a793cc4\",\n        \"f83e64ad\",\n        \"1362dcc6\",\n        \"b675949c\",\n        \"5a9cfba\",\n        \"3ad390f9\",\n        \"17d3c818\",\n        \"4e84adb4\",\n        \"4a8a617b\",\n        \"d9fde042\",\n        \"7bc259cd\",\n        \"57735479\",\n        \"74ec24d3\",\n        \"fbbc8b6e\",\n        \"2a0eaea6\",\n        \"cf1be31b\",\n        \"272df81\",\n        \"70fb4fc4\",\n        \"3e2a1f86\",\n        \"7220b399\",\n        \"fec2887a\",\n        \"839194b0\",\n        \"643fa59b\",\n        \"1f4770e5\",\n        \"849f0c72\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-some-common-security-headers-and-their-purpose/en-US.mdx",
    "content": "---\ntitle: What are some common security headers and their purpose?\n---\n\n## TL;DR\n\nSecurity headers are HTTP response headers that help protect web applications from various attacks. Some common security headers include:\n\n- `Content-Security-Policy (CSP)`: Prevents cross-site scripting (XSS) and other code injection attacks by specifying allowed content sources.\n- `X-Content-Type-Options`: Prevents MIME type sniffing by instructing the browser to follow the declared `Content-Type`.\n- `Strict-Transport-Security (HSTS)`: Enforces secure (HTTPS) connections to the server.\n- `X-Frame-Options`: Prevents clickjacking by controlling whether a page can be displayed in a frame.\n- `X-XSS-Protection`: Enables the cross-site scripting (XSS) filter built into most browsers.\n- `Referrer-Policy`: Controls how much referrer information is included with requests.\n\n---\n\n## Common security headers and their purpose\n\n### Content-Security-Policy (CSP)\n\nThe `Content-Security-Policy` header helps prevent cross-site scripting (XSS) and other code injection attacks by specifying which content sources are allowed to be loaded on the web page. For example:\n\n```http\nContent-Security-Policy: default-src 'self'; img-src 'self' https://example.com; script-src 'self' 'unsafe-inline'\n```\n\nThis policy allows content to be loaded only from the same origin (`'self'`), images from the same origin or `https://example.com`, and scripts from the same origin or inline scripts.\n\n### X-Content-Type-Options\n\nThe `X-Content-Type-Options` header prevents MIME type sniffing by instructing the browser to follow the declared `Content-Type`. This helps mitigate attacks based on content type misinterpretation. The most common value is `nosniff`:\n\n```http\nX-Content-Type-Options: nosniff\n```\n\n### Strict-Transport-Security (HSTS)\n\nThe `Strict-Transport-Security` header enforces secure (HTTPS) connections to the server. It instructs the browser to only interact with the site using HTTPS, even if the user attempts to access it via HTTP. For example:\n\n```http\nStrict-Transport-Security: max-age=31536000; includeSubDomains; preload\n```\n\nThis policy tells the browser to enforce HTTPS for one year (`max-age=31536000`), including all subdomains (`includeSubDomains`), and allows the site to be included in browsers' HSTS preload lists (`preload`).\n\n### X-Frame-Options\n\nThe `X-Frame-Options` header prevents clickjacking by controlling whether a page can be displayed in a frame. Common values are `DENY` and `SAMEORIGIN`:\n\n```http\nX-Frame-Options: DENY\n```\n\nThis policy prevents the page from being displayed in a frame, iframe, or object.\n\n### X-XSS-Protection\n\nThe `X-XSS-Protection` header enables the cross-site scripting (XSS) filter built into most browsers. It can block pages or sanitize scripts that appear to be malicious. For example:\n\n```http\nX-XSS-Protection: 1; mode=block\n```\n\nThis policy enables the XSS filter and instructs the browser to block the page if an attack is detected.\n\n### Referrer-Policy\n\nThe `Referrer-Policy` header controls how much referrer information is included with requests. It helps protect user privacy and can prevent information leakage. Common values include `no-referrer`, `no-referrer-when-downgrade`, and `strict-origin-when-cross-origin`:\n\n```http\nReferrer-Policy: no-referrer\n```\n\nThis policy ensures that no referrer information is sent with requests.\n\n## Further reading\n\n- [MDN Web Docs: HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)\n- [OWASP Secure Headers Project](https://owasp.org/www-project-secure-headers/)\n- [Content Security Policy (CSP) - MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n- [Strict-Transport-Security (HSTS) - MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security)\n"
  },
  {
    "path": "questions/what-are-some-common-security-headers-and-their-purpose/metadata.json",
    "content": "{\n  \"slug\": \"what-are-some-common-security-headers-and-their-purpose\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Security\"\n}\n"
  },
  {
    "path": "questions/what-are-some-common-security-headers-and-their-purpose/zh-CN.mdx",
    "content": "---\ntitle: 常见的安全标头及其用途是什么？\n---\n\n## TL;DR\n\n安全标头是 HTTP 响应标头，可帮助保护 Web 应用程序免受各种攻击。 一些常见的安全标头包括：\n\n* `Content-Security-Policy (CSP)`：通过指定允许的内容来源来防止跨站点脚本 (XSS) 和其他代码注入攻击。\n* `X-Content-Type-Options`：通过指示浏览器遵循声明的 `Content-Type` 来防止 MIME 类型嗅探。\n* `Strict-Transport-Security (HSTS)`：强制对服务器进行安全 (HTTPS) 连接。\n* `X-Frame-Options`：通过控制页面是否可以在框架中显示来防止点击劫持。\n* `X-XSS-Protection`：启用内置于大多数浏览器中的跨站点脚本 (XSS) 过滤器。\n* `Referrer-Policy`：控制请求中包含多少引用者信息。\n\n***\n\n## 常见的安全标头及其用途\n\n### Content-Security-Policy (CSP)\n\n`Content-Security-Policy` 标头通过指定允许在网页上加载哪些内容来源来帮助防止跨站点脚本 (XSS) 和其他代码注入攻击。 例如：\n\n```http\nContent-Security-Policy: default-src 'self'; img-src 'self' https://example.com; script-src 'self' 'unsafe-inline'\n```\n\n此策略允许仅从同一来源 (`'self'`)、来自同一来源或 `https://example.com` 的图像以及来自同一来源或内联脚本的脚本加载内容。\n\n### X-Content-Type-Options\n\n`X-Content-Type-Options` 标头通过指示浏览器遵循声明的 `Content-Type` 来防止 MIME 类型嗅探。 这有助于减轻基于内容类型误解的攻击。 最常见的值是 `nosniff`：\n\n```http\nX-Content-Type-Options: nosniff\n```\n\n### Strict-Transport-Security (HSTS)\n\n`Strict-Transport-Security` 标头强制对服务器进行安全 (HTTPS) 连接。 它指示浏览器仅使用 HTTPS 与站点交互，即使用户尝试通过 HTTP 访问它。 例如：\n\n```http\nStrict-Transport-Security: max-age=31536000; includeSubDomains; preload\n```\n\n此策略告诉浏览器强制 HTTPS 一年 (`max-age=31536000`)，包括所有子域 (`includeSubDomains`)，并允许将该站点包含在浏览器的 HSTS 预加载列表中 (`preload`)。\n\n### X-Frame-Options\n\n`X-Frame-Options` 标头通过控制页面是否可以在框架中显示来防止点击劫持。 常见值为 `DENY` 和 `SAMEORIGIN`：\n\n```http\nX-Frame-Options: DENY\n```\n\n此策略可防止页面在框架、iframe 或对象中显示。\n\n### X-XSS-Protection\n\n标头 `X-XSS-Protection` 启用内置于大多数浏览器中的跨站点脚本 (XSS) 过滤器。它可以阻止页面或清除看似恶意的脚本。例如：\n\n```http\nX-XSS-Protection: 1; mode=block\n```\n\n此策略启用 XSS 过滤器，并指示浏览器在检测到攻击时阻止该页面。\n\n### Referrer-Policy\n\n标头 `Referrer-Policy` 控制请求中包含多少引用者信息。它有助于保护用户隐私并防止信息泄露。常见值包括 `no-referrer`、`no-referrer-when-downgrade` 和 `strict-origin-when-cross-origin`：\n\n```http\nReferrer-Policy: no-referrer\n```\n\n此策略确保不随请求发送任何引用者信息。\n\n## 延伸阅读\n\n* [MDN Web Docs: HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers)\n* [OWASP Secure Headers Project](https://owasp.org/www-project-secure-headers/)\n* [Content Security Policy (CSP) - MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n* [Strict-Transport-Security (HSTS) - MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security)\n"
  },
  {
    "path": "questions/what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"2a723ac3\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"e032cb\",\n        \"c80a9eb\",\n        \"ccfde37f\",\n        \"902aa66c\",\n        \"ea98c021\",\n        \"2a7816d0\",\n        \"cfed8f3c\",\n        \"b4b9ddba\",\n        \"e952606d\",\n        \"c846b3f3\",\n        \"b7196cf9\",\n        \"87a68710\",\n        \"bb1495f8\",\n        \"2c46ac72\",\n        \"197f8bb2\",\n        \"4122c8b9\",\n        \"2ec4cc73\",\n        \"88841075\",\n        \"7445787\",\n        \"4db14557\",\n        \"52c1c0e8\",\n        \"e3411010\",\n        \"73818f\",\n        \"1f4770e5\",\n        \"fc4017d8\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"e032cb\",\n        \"c80a9eb\",\n        \"ccfde37f\",\n        \"902aa66c\",\n        \"ea98c021\",\n        \"2a7816d0\",\n        \"cfed8f3c\",\n        \"b4b9ddba\",\n        \"e952606d\",\n        \"c846b3f3\",\n        \"b7196cf9\",\n        \"87a68710\",\n        \"bb1495f8\",\n        \"2c46ac72\",\n        \"197f8bb2\",\n        \"4122c8b9\",\n        \"2ec4cc73\",\n        \"88841075\",\n        \"7445787\",\n        \"4db14557\",\n        \"52c1c0e8\",\n        \"e3411010\",\n        \"73818f\",\n        \"1f4770e5\",\n        \"fc4017d8\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript/en-US.mdx",
    "content": "---\ntitle: What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?\n---\n\n## TL;DR\n\nUsing languages that compile to JavaScript, like TypeScript or CoffeeScript, can offer several advantages such as improved syntax, type safety, and better tooling. However, they also come with disadvantages like added build steps, potential performance overhead, and the need to learn new syntax.\n\nAdvantages:\n\n- Improved syntax and readability\n- Type safety and error checking\n- Better tooling and editor support\n\nDisadvantages:\n\n- Added build steps and complexity\n- Potential performance overhead\n- Learning curve for new syntax\n\n---\n\n## Advantages of writing JavaScript code in a language that compiles to JavaScript\n\n### Improved syntax and readability\n\nLanguages like TypeScript and CoffeeScript often provide a more concise and readable syntax compared to vanilla JavaScript. This can make the code easier to write and maintain.\n\n```typescript\n// TypeScript example\nclass Person {\n  constructor(private name: string) {}\n\n  greet() {\n    console.log(`Hello, ${this.name}`);\n  }\n}\n```\n\n### Type safety and error checking\n\nTypeScript, for example, adds static type checking to JavaScript, which can catch errors at compile time rather than at runtime. This can lead to more robust and reliable code.\n\n```typescript\n// TypeScript example\nfunction add(a: number, b: number): number {\n  return a + b;\n}\n```\n\n### Better tooling and editor support\n\nLanguages that compile to JavaScript often come with enhanced tooling and editor support, such as autocompletion, refactoring tools, and better debugging capabilities. This can improve developer productivity.\n\n## Disadvantages of writing JavaScript code in a language that compiles to JavaScript\n\n### Added build steps and complexity\n\nUsing a language that compiles to JavaScript introduces an additional build step in the development process. This can complicate the build pipeline and increase the time it takes to see changes reflected in the browser.\n\n```json\n// Example of a build configuration for TypeScript\n{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"module\": \"commonjs\",\n    \"outDir\": \"./dist\",\n    \"rootDir\": \"./src\",\n    \"strict\": true\n  }\n}\n```\n\n### Potential performance overhead\n\nWhile the compiled JavaScript code is often optimized, there can be cases where the performance is not as good as hand-written JavaScript. This is especially true if the compiler introduces unnecessary abstractions.\n\n### Learning curve for new syntax\n\nDevelopers need to learn the new syntax and features of the language that compiles to JavaScript. This can be a barrier to entry and may require additional training and resources.\n\n## Further reading\n\n- [TypeScript Official Documentation](https://www.typescriptlang.org/docs/)\n- [CoffeeScript Official Documentation](https://coffeescript.org/)\n- [Babel: The JavaScript Compiler](https://babeljs.io/)\n- [Comparing TypeScript and JavaScript](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)\n"
  },
  {
    "path": "questions/what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript/metadata.json",
    "content": "{\n  \"slug\": \"what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": false,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript/pt-BR.mdx",
    "content": "---\ntitle: Quais são algumas das vantagens/desvantagens de escrever código JavaScript em uma linguagem que compila para JavaScript?\n---\n\nAlguns exemplos de linguagens que compilam para JavaScript incluem CoffeeScript, Elm, ClojureScript, PureScript e TypeScript.\n\n## Vantagens\n\n- Corrige alguns dos problemas de longa data em JavaScript e desencoraja anti-padrões do JavaScript.\n- Permite que você escreva um código mais curto, fornecendo açúcar sintático em cima do JavaScript, o que o ES5 não possui, mas o ES2015 é excelente.\n- Tipos estáticos são incríveis (no caso do TypeScript) para projetos grandes que precisam ser mantidos ao longo do tempo.\n\n## Desvantagens\n\n- É preciso ter um processo de construção/compilação, já que os navegadores apenas executam JavaScript e seu código precisará ser compilado em JavaScript antes de ser enviado aos navegadores.\n- Depuração pode ser difícil se seus mapas de origem não mapearem corretamente para sua origem pré-compilada.\n- A maioria dos desenvolvedores não está familiarizada com essas linguagens e precisará aprendê-las. Há um custo de aprendizado envolvido para sua equipe se você usá-lo em seus projetos.\n- Comunidade menor (dependendo da linguagem), o que significa que recursos, tutoriais, bibliotecas e ferramentas serão mais difíceis de encontrar.\n- O suporte de IDE/editor pode ser limitado.\n- Essas linguagens sempre estarão atrasadas em relação ao padrão mais recente do JavaScript.\n- Os desenvolvedores devem estar cientes do que seu código está sendo compilado, pois é isso que realmente será executado e é isso que importa no final.\n\nNa prática, o ES2015 melhorou significativamente o JavaScript e tornou muito mais agradável escrevê-lo. Não há mais uma grande necessidade de usar o CoffeeScript nos dias de hoje. Em vez disso, o TypeScript é a escolha preferida devido à segurança de tipo adicionada e à experiência de desenvolvedor melhorada que ele proporciona.\n"
  },
  {
    "path": "questions/what-are-some-of-the-advantages-disadvantages-of-writing-javascript-code-in-a-language-that-compiles-to-javascript/zh-CN.mdx",
    "content": "---\ntitle: 用编译为 JavaScript 的语言编写 JavaScript 代码有哪些优缺点？\n---\n\n## TL;DR\n\n使用编译为 JavaScript 的语言（如 TypeScript 或 CoffeeScript）可以提供一些优势，例如改进的语法、类型安全性和更好的工具。但是，它们也有缺点，例如增加了构建步骤、潜在的性能开销以及需要学习新语法。\n\n优点：\n\n* 改进的语法和可读性\n* 类型安全性和错误检查\n* 更好的工具和编辑器支持\n\n缺点：\n\n* 增加了构建步骤和复杂性\n* 潜在的性能开销\n* 学习新语法的曲线\n\n***\n\n## 用编译为 JavaScript 的语言编写 JavaScript 代码的优点\n\n### 改进的语法和可读性\n\n与原始 JavaScript 相比，TypeScript 和 CoffeeScript 等语言通常提供更简洁、更易读的语法。这可以使代码更容易编写和维护。\n\n```typescript\n// TypeScript example\nclass Person {\n  constructor(private name: string) {}\n\n  greet() {\n    console.log(`Hello, ${this.name}`);\n  }\n}\n```\n\n### 类型安全性和错误检查\n\n例如，TypeScript 将静态类型检查添加到 JavaScript 中，这可以在编译时而不是运行时捕获错误。这可以使代码更健壮、更可靠。\n\n```typescript\n// TypeScript example\nfunction add(a: number, b: number): number {\n  return a + b;\n}\n```\n\n### 更好的工具和编辑器支持\n\n编译为 JavaScript 的语言通常附带增强的工具和编辑器支持，例如自动完成、重构工具和更好的调试功能。这可以提高开发人员的工作效率。\n\n## 用编译为 JavaScript 的语言编写 JavaScript 代码的缺点\n\n### 增加了构建步骤和复杂性\n\n使用编译为 JavaScript 的语言会在开发过程中引入额外的构建步骤。这会使构建流程复杂化，并增加在浏览器中看到更改所需的时间。\n\n```json\n// Example of a build configuration for TypeScript\n{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"module\": \"commonjs\",\n    \"outDir\": \"./dist\",\n    \"rootDir\": \"./src\",\n    \"strict\": true\n  }\n}\n```\n\n### 潜在的性能开销\n\n虽然编译后的 JavaScript 代码通常经过优化，但在某些情况下，其性能可能不如手写的 JavaScript。如果编译器引入不必要的抽象，尤其如此。\n\n### 新语法的学习曲线\n\n开发人员需要学习编译为 JavaScript 的语言的新语法和特性。这可能成为进入的障碍，并且可能需要额外的培训和资源。\n\n## 延伸阅读\n\n* [TypeScript 官方文档](https://www.typescriptlang.org/docs/)\n* [CoffeeScript 官方文档](https://coffeescript.org/)\n* [Babel：JavaScript 编译器](https://babeljs.io/)\n* [比较 TypeScript 和 JavaScript](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)\n"
  },
  {
    "path": "questions/what-are-some-popular-javascript-testing-frameworks/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"55736c1c\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"41de5666\",\n        \"2a7816d0\",\n        \"723afb36\",\n        \"20112cd5\",\n        \"58caca19\",\n        \"2157cfb7\",\n        \"e76b9a8\",\n        \"64e16708\",\n        \"4cefc826\",\n        \"916d976a\",\n        \"a9a77e98\",\n        \"e76b9a8\",\n        \"d3e74489\",\n        \"d6870afa\",\n        \"1c610157\",\n        \"8e439ffa\",\n        \"e76b9a8\",\n        \"7d846c04\",\n        \"a07a2d68\",\n        \"eb62d3e0\",\n        \"4160e701\",\n        \"e76b9a8\",\n        \"63996b52\",\n        \"1f4770e5\",\n        \"5460ef5\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"41de5666\",\n        \"2a7816d0\",\n        \"723afb36\",\n        \"20112cd5\",\n        \"58caca19\",\n        \"2157cfb7\",\n        \"e76b9a8\",\n        \"64e16708\",\n        \"4cefc826\",\n        \"916d976a\",\n        \"a9a77e98\",\n        \"e76b9a8\",\n        \"d3e74489\",\n        \"d6870afa\",\n        \"1c610157\",\n        \"8e439ffa\",\n        \"e76b9a8\",\n        \"7d846c04\",\n        \"a07a2d68\",\n        \"eb62d3e0\",\n        \"4160e701\",\n        \"e76b9a8\",\n        \"63996b52\",\n        \"1f4770e5\",\n        \"5460ef5\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-some-popular-javascript-testing-frameworks/en-US.mdx",
    "content": "---\ntitle: What are some popular JavaScript testing frameworks?\n---\n\n## TL;DR\n\nSome popular JavaScript testing frameworks include Jest, Mocha, Jasmine, and Cypress. Jest is known for its simplicity and integration with React. Mocha is highly flexible and often used with other libraries like Chai for assertions. Jasmine is a behavior-driven development framework that requires no additional libraries. Cypress is an end-to-end testing framework that provides a great developer experience.\n\n---\n\n## Popular JavaScript testing frameworks\n\n### Jest\n\nJest is a testing framework developed by Facebook, primarily used for testing React applications. It is known for its simplicity and ease of use.\n\n- It comes with a built-in test runner, assertion library, and mocking support\n- It has a zero-configuration setup, making it easy to get started\n- It provides features like snapshot testing and code coverage out of the box\n\nExample:\n\n```js\ntest('adds 1 + 2 to equal 3', () => {\n  expect(1 + 2).toBe(3);\n});\n```\n\n### Mocha\n\nMocha is a flexible testing framework that can be used with various assertion libraries like Chai. It is known for its extensive configuration options and support for asynchronous testing.\n\n- It provides a simple and flexible API for writing tests\n- It supports both BDD (Behavior-Driven Development) and TDD (Test-Driven Development) styles\n- It can be easily integrated with other libraries and tools\n\nExample:\n\n```js\nconst assert = require('assert');\n\ndescribe('Array', function () {\n  describe('#indexOf()', function () {\n    it('should return -1 when the value is not present', function () {\n      assert.strictEqual([1, 2, 3].indexOf(4), -1);\n    });\n  });\n});\n```\n\n### Jasmine\n\nJasmine is a behavior-driven development framework that requires no additional libraries. It is known for its simplicity and ease of use.\n\n- It provides a clean and readable syntax for writing tests\n- It includes built-in assertion and mocking libraries\n- It supports asynchronous testing\n\nExample:\n\n```js\ndescribe('A suite', function () {\n  it('contains a spec with an expectation', function () {\n    expect(true).toBe(true);\n  });\n});\n```\n\n### Cypress\n\nCypress is an end-to-end testing framework that provides a great developer experience. It is known for its fast and reliable tests.\n\n- It provides a simple and intuitive API for writing tests\n- It includes built-in support for assertions, mocking, and stubbing\n- It provides real-time reloading and debugging capabilities\n\nExample:\n\n```js\ndescribe('My First Test', function () {\n  it('Visits the Kitchen Sink', function () {\n    cy.visit('https://example.cypress.io');\n    cy.contains('type').click();\n    cy.url().should('include', '/commands/actions');\n  });\n});\n```\n\n## Further reading\n\n- [Jest documentation](https://jestjs.io/docs/getting-started)\n- [Mocha documentation](https://mochajs.org/#getting-started)\n- [Jasmine documentation](https://jasmine.github.io/pages/getting_started.html)\n- [Cypress documentation](https://docs.cypress.io/guides/overview/why-cypress)\n"
  },
  {
    "path": "questions/what-are-some-popular-javascript-testing-frameworks/metadata.json",
    "content": "{\n  \"slug\": \"what-are-some-popular-javascript-testing-frameworks\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"testing\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Testing\"\n}\n"
  },
  {
    "path": "questions/what-are-some-popular-javascript-testing-frameworks/zh-CN.mdx",
    "content": "---\ntitle: 有哪些流行的 JavaScript 测试框架？\n---\n\n## 总结\n\n一些流行的 JavaScript 测试框架包括 Jest、Mocha、Jasmine 和 Cypress。Jest 以其简单性和与 React 的集成而闻名。Mocha 非常灵活，通常与其他库（如 Chai）一起用于断言。Jasmine 是一个行为驱动开发框架，不需要额外的库。Cypress 是一个端到端测试框架，提供出色的开发者体验。\n\n***\n\n## 流行的 JavaScript 测试框架\n\n### Jest\n\nJest 是 Facebook 开发的测试框架，主要用于测试 React 应用程序。它以其简单性和易用性而闻名。\n\n* 它自带内置的测试运行器、断言库和模拟支持\n* 它的设置无需配置，易于上手\n* 它提供了快照测试和开箱即用的代码覆盖率等功能\n\n示例：\n\n```js\ntest('adds 1 + 2 to equal 3', () => {\n  expect(1 + 2).toBe(3);\n});\n```\n\n### Mocha\n\nMocha 是一个灵活的测试框架，可以与各种断言库（如 Chai）一起使用。它以其广泛的配置选项和对异步测试的支持而闻名。\n\n* 它提供了一个简单而灵活的 API 用于编写测试\n* 它支持 BDD（行为驱动开发）和 TDD（测试驱动开发）风格\n* 它可以轻松地与其他库和工具集成\n\n示例：\n\n```js\nconst assert = require('assert');\n\ndescribe('Array', function () {\n  describe('#indexOf()', function () {\n    it('should return -1 when the value is not present', function () {\n      assert.strictEqual([1, 2, 3].indexOf(4), -1);\n    });\n  });\n});\n```\n\n### Jasmine\n\nJasmine 是一个行为驱动开发框架，不需要额外的库。它以其简单性和易用性而闻名。\n\n* 它为编写测试提供了清晰易读的语法\n* 它包括内置的断言和模拟库\n* 它支持异步测试\n\n示例：\n\n```js\ndescribe('A suite', function () {\n  it('contains a spec with an expectation', function () {\n    expect(true).toBe(true);\n  });\n});\n```\n\n### Cypress\n\nCypress 是一个端到端测试框架，提供出色的开发者体验。它以其快速可靠的测试而闻名。\n\n* 它为编写测试提供了一个简单直观的 API\n* 它包括对断言、模拟和存根的内置支持\n* 它提供实时重新加载和调试功能\n\n示例：\n\n```js\ndescribe('My First Test', function () {\n  it('Visits the Kitchen Sink', function () {\n    cy.visit('https://example.cypress.io');\n    cy.contains('type').click();\n    cy.url().should('include', '/commands/actions');\n  });\n});\n```\n\n## 延伸阅读\n\n* [Jest documentation](https://jestjs.io/docs/getting-started)\n* [Mocha documentation](https://mochajs.org/#getting-started)\n* [Jasmine documentation](https://jasmine.github.io/pages/getting_started.html)\n* [Cypress documentation](https://docs.cypress.io/guides/overview/why-cypress)\n"
  },
  {
    "path": "questions/what-are-some-techniques-for-reducing-reflows-and-repaints/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"e71c8ca\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"4a3db965\",\n        \"2a7816d0\",\n        \"8c2a2cb5\",\n        \"5a7e8ea8\",\n        \"18fc41dc\",\n        \"37ba4328\",\n        \"6c91fbda\",\n        \"8413ba48\",\n        \"db488ca\",\n        \"65a9540f\",\n        \"d5f4f592\",\n        \"8fbeb744\",\n        \"70b67439\",\n        \"99a5a5c0\",\n        \"9d06be04\",\n        \"417ae958\",\n        \"c93e3767\",\n        \"e7458e3d\",\n        \"de830d0b\",\n        \"42700f78\",\n        \"32537e85\",\n        \"1d560b1c\",\n        \"10e479a8\",\n        \"ff3456ab\",\n        \"1f4770e5\",\n        \"d8cb0be0\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4a3db965\",\n        \"2a7816d0\",\n        \"8c2a2cb5\",\n        \"5a7e8ea8\",\n        \"18fc41dc\",\n        \"37ba4328\",\n        \"6c91fbda\",\n        \"8413ba48\",\n        \"db488ca\",\n        \"65a9540f\",\n        \"d5f4f592\",\n        \"8fbeb744\",\n        \"70b67439\",\n        \"99a5a5c0\",\n        \"9d06be04\",\n        \"417ae958\",\n        \"c93e3767\",\n        \"e7458e3d\",\n        \"de830d0b\",\n        \"42700f78\",\n        \"32537e85\",\n        \"1d560b1c\",\n        \"10e479a8\",\n        \"ff3456ab\",\n        \"1f4770e5\",\n        \"d8cb0be0\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-some-techniques-for-reducing-reflows-and-repaints/en-US.mdx",
    "content": "---\ntitle: What are some techniques for reducing reflows and repaints?\n---\n\n## TL;DR\n\nTo reduce reflows and repaints, you can minimize DOM manipulations, batch DOM changes, use CSS classes for style changes, avoid complex CSS selectors, and use `requestAnimationFrame` for animations. Additionally, consider using `will-change` for elements that will change frequently and avoid layout thrashing by reading and writing to the DOM separately.\n\n---\n\n## Techniques for reducing reflows and repaints\n\n### Minimize DOM manipulations\n\nFrequent changes to the DOM can cause multiple reflows and repaints. To minimize this:\n\n- Use `documentFragment` to batch DOM updates\n- Clone nodes, make changes, and then replace the original node\n\n### Batch DOM changes\n\nGrouping multiple DOM changes together can reduce the number of reflows and repaints:\n\n- Use `innerHTML` to update multiple elements at once\n- Use `requestAnimationFrame` to batch updates\n\n### Use CSS classes for style changes\n\nInstead of changing styles directly via JavaScript, use CSS classes:\n\n```js live\nconst element = document.createElement('h1');\nelement.classList.add('text-center');\n\nconsole.log(element); // Notice that the class has been added.\n```\n\n### Avoid complex CSS selectors\n\nComplex selectors can slow down the rendering process:\n\n- Use simple and direct selectors\n- Avoid deep nesting\n\n### Use `requestAnimationFrame` for animations\n\nUsing `requestAnimationFrame` ensures that animations are synchronized with the browser's repaint cycle:\n\n```js\nfunction animate() {\n  // Animation logic\n  requestAnimationFrame(animate);\n}\nrequestAnimationFrame(animate);\n```\n\n### Use `will-change` for frequently changing elements\n\nThe `will-change` property can hint to the browser about which elements will change, allowing it to optimize rendering:\n\n```css\n.element {\n  will-change: transform;\n}\n```\n\n### Avoid layout thrashing\n\nReading and writing to the DOM separately can prevent layout thrashing:\n\n```js live\n// Mock div element\nconst element = document.createElement('div');\n\nconst height = element.offsetHeight; // Read\nelement.style.height = `${height + 10}px`; // Write\n\nconsole.log(element);\n```\n\n## Further reading\n\n- [MDN Web Docs: Reflow](https://developer.mozilla.org/en-US/docs/Glossary/Reflow)\n- [Google Developers: Avoid large, complex layouts and layout thrashing](https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing)\n- [CSS-Tricks: Debouncing and Throttling Explained Through Examples](https://css-tricks.com/debouncing-throttling-explained-examples/)\n"
  },
  {
    "path": "questions/what-are-some-techniques-for-reducing-reflows-and-repaints/metadata.json",
    "content": "{\n  \"slug\": \"what-are-some-techniques-for-reducing-reflows-and-repaints\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"advanced\",\n  \"topics\": [\"browser\", \"javascript\", \"performance\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Performance Optimization\"\n}\n"
  },
  {
    "path": "questions/what-are-some-techniques-for-reducing-reflows-and-repaints/zh-CN.mdx",
    "content": "---\ntitle: 有哪些减少重排和重绘的技术？\n---\n\n## TL;DR\n\n要减少重排和重绘，您可以尽量减少 DOM 操作、批量处理 DOM 更改、使用 CSS 类进行样式更改、避免复杂的 CSS 选择器，并使用 `requestAnimationFrame` 进行动画。此外，请考虑对将经常更改的元素使用 `will-change`，并通过分别读取和写入 DOM 来避免布局颠簸。\n\n***\n\n## 减少重排和重绘的技术\n\n### 尽量减少 DOM 操作\n\n频繁更改 DOM 可能会导致多次重排和重绘。要尽量减少这种情况：\n\n* 使用 `documentFragment` 批量更新 DOM\n* 克隆节点，进行更改，然后替换原始节点\n\n### 批量处理 DOM 更改\n\n将多个 DOM 更改组合在一起可以减少重排和重绘的次数：\n\n* 使用 `innerHTML` 一次更新多个元素\n* 使用 `requestAnimationFrame` 批量更新\n\n### 使用 CSS 类进行样式更改\n\n不要通过 JavaScript 直接更改样式，而是使用 CSS 类：\n\n```js live\nconst element = document.createElement('h1');\nelement.classList.add('text-center');\n\nconsole.log(element); // Notice that the class has been added.\n```\n\n### 避免复杂的 CSS 选择器\n\n复杂的选择器会减慢渲染过程：\n\n* 使用简单直接的选择器\n* 避免深度嵌套\n\n### 使用 `requestAnimationFrame` 进行动画\n\n使用 `requestAnimationFrame` 可确保动画与浏览器的重绘周期同步：\n\n```js\nfunction animate() {\n  // Animation logic\n  requestAnimationFrame(animate);\n}\nrequestAnimationFrame(animate);\n```\n\n### 对频繁更改的元素使用 `will-change`\n\n `will-change` 属性可以向浏览器提示哪些元素将要更改，从而允许它优化渲染：\n\n```css\n.element {\n  will-change: transform;\n}\n```\n\n### 避免布局震荡\n\n分别读取和写入 DOM 可以防止布局震荡：\n\n```js live\n// Mock div element\nconst element = document.createElement('div');\n\nconst height = element.offsetHeight; // Read\nelement.style.height = `${height + 10}px`; // Write\n\nconsole.log(element);\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Reflow](https://developer.mozilla.org/en-US/docs/Glossary/Reflow)\n* [Google Developers: Avoid large, complex layouts and layout thrashing](https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing)\n* [CSS-Tricks: Debouncing and Throttling Explained Through Examples](https://css-tricks.com/debouncing-throttling-explained-examples/)\n"
  },
  {
    "path": "questions/what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"fd7aa1c3\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"110638ec\",\n        \"2a7816d0\",\n        \"833a8ee0\",\n        \"384fd303\",\n        \"bc08155e\",\n        \"194c11d9\",\n        \"b9694daf\",\n        \"55b499f4\",\n        \"da0f98f5\",\n        \"1e792481\",\n        \"f46bccb1\",\n        \"d1aec808\",\n        \"c8907e97\",\n        \"bb75cfe2\",\n        \"78c4b9ca\",\n        \"af4d4f76\",\n        \"dc7392f7\",\n        \"1f4770e5\",\n        \"7ab720bb\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"110638ec\",\n        \"2a7816d0\",\n        \"833a8ee0\",\n        \"384fd303\",\n        \"bc08155e\",\n        \"194c11d9\",\n        \"b9694daf\",\n        \"55b499f4\",\n        \"da0f98f5\",\n        \"1e792481\",\n        \"f46bccb1\",\n        \"d1aec808\",\n        \"c8907e97\",\n        \"bb75cfe2\",\n        \"78c4b9ca\",\n        \"af4d4f76\",\n        \"dc7392f7\",\n        \"1f4770e5\",\n        \"7ab720bb\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code/en-US.mdx",
    "content": "---\ntitle: What are some tools and techniques for identifying security vulnerabilities in JavaScript code?\n---\n\n## TL;DR\n\nTo identify security vulnerabilities in JavaScript code, you can use static code analysis tools like ESLint with security plugins, dynamic analysis tools like OWASP ZAP, and dependency checkers like npm audit. Additionally, manual code reviews and adhering to secure coding practices are essential techniques.\n\n---\n\n## Tools and techniques for identifying security vulnerabilities in JavaScript code\n\n### Static code analysis tools\n\nStatic code analysis tools examine your code without executing it. They can identify potential security vulnerabilities by analyzing the code structure and patterns.\n\n- **ESLint**: A popular linting tool for JavaScript that can be extended with security-focused plugins like `eslint-plugin-security` to catch common security issues.\n\n  ```bash\n  npm install eslint eslint-plugin-security --save-dev\n  ```\n\n  ```js\n  // .eslintrc.json\n  {\n    \"plugins\": [\"security\"],\n    \"extends\": [\"plugin:security/recommended\"]\n  }\n  ```\n\n- **SonarQube**: A platform that provides continuous inspection of code quality and security vulnerabilities. It supports JavaScript and integrates with various CI/CD pipelines.\n\n### Dynamic analysis tools\n\nDynamic analysis tools test your application while it is running to identify security vulnerabilities.\n\n- **OWASP ZAP (Zed Attack Proxy)**: An open-source tool for finding security vulnerabilities in web applications. It can be used to perform automated scans and manual testing.\n\n  ```bash\n  zap.sh -daemon -port 8080 -config api.disablekey=true\n  ```\n\n- **Burp Suite**: A comprehensive platform for web application security testing. It includes tools for scanning, crawling, and exploiting vulnerabilities.\n\n### Dependency checkers\n\nDependency checkers analyze the third-party libraries and packages your project depends on to identify known vulnerabilities.\n\n- **npm audit**: A built-in tool for npm that checks for vulnerabilities in your project's dependencies.\n\n  ```bash\n  npm audit\n  ```\n\n- **Snyk**: A tool that continuously monitors your dependencies for vulnerabilities and provides fixes.\n  ```bash\n  snyk test\n  ```\n\n### Manual code reviews\n\nManual code reviews involve developers examining each other's code to identify potential security issues. This technique is effective because it leverages human intuition and experience.\n\n### Secure coding practices\n\nAdhering to secure coding practices can help prevent security vulnerabilities from being introduced in the first place.\n\n- **Input validation**: Always validate and sanitize user inputs to prevent injection attacks.\n- **Output encoding**: Encode data before rendering it to prevent cross-site scripting (XSS) attacks.\n- **Use HTTPS**: Ensure that your application uses HTTPS to encrypt data in transit.\n- **Principle of least privilege**: Grant the minimum necessary permissions to users and services.\n\n## Further reading\n\n- [OWASP Top Ten](https://owasp.org/www-project-top-ten/)\n- [ESLint](https://eslint.org/)\n- [SonarQube](https://www.sonarqube.org/)\n- [OWASP ZAP](https://www.zaproxy.org/)\n- [Burp Suite](https://portswigger.net/burp)\n- [npm audit](https://docs.npmjs.com/cli/v7/commands/npm-audit)\n- [Snyk](https://snyk.io/)\n"
  },
  {
    "path": "questions/what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code/metadata.json",
    "content": "{\n  \"slug\": \"what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Security\"\n}\n"
  },
  {
    "path": "questions/what-are-some-tools-and-techniques-for-identifying-security-vulnerabilities-in-javascript-code/zh-CN.mdx",
    "content": "---\ntitle: 有哪些用于识别 JavaScript 代码中安全漏洞的工具和技术？\n---\n\n## TL;DR\n\n要识别 JavaScript 代码中的安全漏洞，您可以使用静态代码分析工具（如带有安全插件的 ESLint）、动态分析工具（如 OWASP ZAP）和依赖项检查器（如 npm audit）。此外，手动代码审查和遵守安全编码实践是必不可少的技术。\n\n***\n\n## 用于识别 JavaScript 代码中安全漏洞的工具和技术\n\n### 静态代码分析工具\n\n静态代码分析工具在不执行代码的情况下检查您的代码。它们可以通过分析代码结构和模式来识别潜在的安全漏洞。\n\n* **ESLint**：一个流行的 JavaScript 检查工具，可以使用安全插件（如 `eslint-plugin-security`）进行扩展，以捕获常见的安全问题。\n\n  ```bash\n  npm install eslint eslint-plugin-security --save-dev\n  ```\n\n  ```js\n  // .eslintrc.json\n  {\n    \"plugins\": [\"security\"],\n    \"extends\": [\"plugin:security/recommended\"]\n  }\n  ```\n\n* **SonarQube**：一个提供代码质量和安全漏洞持续检查的平台。它支持 JavaScript 并与各种 CI/CD 管道集成。\n\n### 动态分析工具\n\n动态分析工具在应用程序运行时对其进行测试，以识别安全漏洞。\n\n* **OWASP ZAP (Zed Attack Proxy)**：一个用于查找 Web 应用程序中安全漏洞的开源工具。它可用于执行自动化扫描和手动测试。\n\n  ```bash\n  zap.sh -daemon -port 8080 -config api.disablekey=true\n  ```\n\n* **Burp Suite**：一个用于 Web 应用程序安全测试的综合平台。它包括用于扫描、爬取和利用漏洞的工具。\n\n### 依赖项检查器\n\n依赖项检查器分析您的项目所依赖的第三方库和包，以识别已知的漏洞。\n\n* **npm audit**：npm 的一个内置工具，用于检查您的项目依赖项中的漏洞。\n\n  ```bash\n  npm audit\n  ```\n\n* **Snyk**：一个持续监控您的依赖项是否存在漏洞并提供修复的工具。\n  ```bash\n  snyk test\n  ```\n\n### 手动代码审查\n\n手动代码审查涉及开发人员检查彼此的代码以识别潜在的安全问题。这种技术是有效的，因为它利用了人类的直觉和经验。\n\n### 安全编码实践\n\n遵守安全编码实践可以帮助防止首先引入安全漏洞。\n\n* **输入验证**：始终验证和清理用户输入，以防止注入攻击。\n* **输出编码**：在呈现数据之前对其进行编码，以防止跨站点脚本 (XSS) 攻击。\n* **使用 HTTPS**：确保您的应用程序使用 HTTPS 对传输中的数据进行加密。\n* **最小权限原则**：向用户和服务授予最低限度的必要权限。\n\n## 延伸阅读\n\n* [OWASP Top Ten](https://owasp.org/www-project-top-ten/)\n* [ESLint](https://eslint.org/)\n* [SonarQube](https://www.sonarqube.org/)\n* [OWASP ZAP](https://www.zaproxy.org/)\n* [Burp Suite](https://portswigger.net/burp)\n* [npm audit](https://docs.npmjs.com/cli/v7/commands/npm-audit)\n* [Snyk](https://snyk.io/)\n"
  },
  {
    "path": "questions/what-are-some-tools-that-can-be-used-for-javascript-testing/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"5e1bc6e1\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"409132a7\",\n        \"2a7816d0\",\n        \"385dacab\",\n        \"20112cd5\",\n        \"c6b2b783\",\n        \"d4e58535\",\n        \"d41fa0ea\",\n        \"1bc867b8\",\n        \"4cefc826\",\n        \"f918f634\",\n        \"fc365ce0\",\n        \"4e61627f\",\n        \"fc79fa34\",\n        \"d6870afa\",\n        \"54e2cee1\",\n        \"6d7053a7\",\n        \"1763890f\",\n        \"394907e3\",\n        \"a07a2d68\",\n        \"9bcc86a9\",\n        \"13400b4c\",\n        \"18d0a397\",\n        \"184d2626\",\n        \"1f4770e5\",\n        \"577102ea\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"409132a7\",\n        \"2a7816d0\",\n        \"385dacab\",\n        \"20112cd5\",\n        \"c6b2b783\",\n        \"d4e58535\",\n        \"d41fa0ea\",\n        \"1bc867b8\",\n        \"4cefc826\",\n        \"f918f634\",\n        \"fc365ce0\",\n        \"4e61627f\",\n        \"fc79fa34\",\n        \"d6870afa\",\n        \"54e2cee1\",\n        \"6d7053a7\",\n        \"1763890f\",\n        \"394907e3\",\n        \"a07a2d68\",\n        \"9bcc86a9\",\n        \"13400b4c\",\n        \"18d0a397\",\n        \"184d2626\",\n        \"1f4770e5\",\n        \"577102ea\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-some-tools-that-can-be-used-for-javascript-testing/en-US.mdx",
    "content": "---\ntitle: What are some tools that can be used for JavaScript testing?\n---\n\n## TL;DR\n\nFor JavaScript testing, you can use tools like Jest, Mocha, Jasmine, and Cypress. Jest is popular for its ease of use and built-in features. Mocha is flexible and can be paired with other libraries. Jasmine is known for its simplicity and behavior-driven development (BDD) style. Cypress is great for end-to-end testing with a focus on real browser interactions.\n\n---\n\n## Tools for JavaScript testing\n\n### Jest\n\nJest is a popular testing framework developed by Facebook. It is widely used for testing JavaScript applications, especially those built with React.\n\n- **Ease of use**: Jest comes with a lot of built-in features, making it easy to set up and start testing.\n- **Snapshot testing**: Jest allows you to capture snapshots of your components and compare them during future test runs.\n- **Mocking**: Jest has powerful mocking capabilities, which makes it easy to mock functions, modules, and timers.\n- **Code coverage**: Jest provides built-in code coverage reports.\n\nExample of a simple test using Jest:\n\n```js\nconst sum = (a, b) => a + b;\n\ntest('adds 1 + 2 to equal 3', () => {\n  expect(sum(1, 2)).toBe(3);\n});\n```\n\n### Mocha\n\nMocha is a flexible testing framework that can be used with various assertion libraries and mocking tools.\n\n- **Flexibility**: Mocha allows you to choose your own assertion library (e.g., Chai) and mocking tools (e.g., Sinon).\n- **Asynchronous testing**: Mocha has excellent support for asynchronous testing.\n- **Browser support**: Mocha can be run in both Node.js and the browser.\n\nExample of a simple test using Mocha and Chai:\n\n```js\nconst { expect } = require('chai');\n\ndescribe('Array', () => {\n  it('should return -1 when the value is not present', () => {\n    expect([1, 2, 3].indexOf(4)).to.equal(-1);\n  });\n});\n```\n\n### Jasmine\n\nJasmine is a behavior-driven development (BDD) framework for testing JavaScript code. It is known for its simplicity and ease of use.\n\n- **Simplicity**: Jasmine comes with everything you need to start testing, including an assertion library and mocking tools.\n- **BDD style**: Jasmine encourages writing tests in a BDD style, which can make your tests more readable.\n\nExample of a simple test using Jasmine:\n\n```js\ndescribe('A suite', () => {\n  it('contains a spec with an expectation', () => {\n    expect(true).toBe(true);\n  });\n});\n```\n\n### Cypress\n\nCypress is an end-to-end testing framework that focuses on real browser interactions.\n\n- **Real browser testing**: Cypress runs tests in the browser, providing a more accurate representation of user interactions.\n- **Time travel**: Cypress allows you to go back in time to see what happened at each step of your test.\n- **Automatic waiting**: Cypress automatically waits for elements to appear and actions to complete, reducing the need for manual waits.\n\nExample of a simple test using Cypress:\n\n```js\ndescribe('My First Test', () => {\n  it('Visits the Kitchen Sink', () => {\n    cy.visit('https://example.cypress.io');\n    cy.contains('type').click();\n    cy.url().should('include', '/commands/actions');\n    cy.get('.action-email')\n      .type('fake@email.com')\n      .should('have.value', 'fake@email.com');\n  });\n});\n```\n\n## Further reading\n\n- [Jest documentation](https://jestjs.io/docs/getting-started)\n- [Mocha documentation](https://mochajs.org/)\n- [Jasmine documentation](https://jasmine.github.io/)\n- [Cypress documentation](https://docs.cypress.io/guides/overview/why-cypress)\n"
  },
  {
    "path": "questions/what-are-some-tools-that-can-be-used-for-javascript-testing/metadata.json",
    "content": "{\n  \"slug\": \"what-are-some-tools-that-can-be-used-for-javascript-testing\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"testing\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Testing\"\n}\n"
  },
  {
    "path": "questions/what-are-some-tools-that-can-be-used-for-javascript-testing/zh-CN.mdx",
    "content": "---\ntitle: 有哪些可用于 JavaScript 测试的工具？\n---\n\n## TL;DR\n\n对于 JavaScript 测试，您可以使用 Jest、Mocha、Jasmine 和 Cypress 等工具。 Jest 因其易用性和内置功能而广受欢迎。 Mocha 具有灵活性，可以与其他库配对。 Jasmine 以其简单性和行为驱动开发 (BDD) 风格而闻名。 Cypress 非常适合端到端测试，侧重于真实的浏览器交互。\n\n***\n\n## JavaScript 测试工具\n\n### Jest\n\nJest 是 Facebook 开发的一个流行的测试框架。 它被广泛用于测试 JavaScript 应用程序，尤其是那些使用 React 构建的应用程序。\n\n* **易于使用**：Jest 带有许多内置功能，使其易于设置和开始测试。\n* **快照测试**：Jest 允许您捕获组件的快照并在将来的测试运行期间进行比较。\n* **Mocking**：Jest 具有强大的模拟功能，这使得模拟函数、模块和计时器变得容易。\n* **代码覆盖率**：Jest 提供内置的代码覆盖率报告。\n\n使用 Jest 的简单测试示例：\n\n```js\nconst sum = (a, b) => a + b;\n\ntest('adds 1 + 2 to equal 3', () => {\n  expect(sum(1, 2)).toBe(3);\n});\n```\n\n### Mocha\n\nMocha 是一个灵活的测试框架，可以与各种断言库和模拟工具一起使用。\n\n* **灵活性**：Mocha 允许您选择自己的断言库（例如，Chai）和模拟工具（例如，Sinon）。\n* **异步测试**：Mocha 具有出色的异步测试支持。\n* **浏览器支持**：Mocha 可以在 Node.js 和浏览器中运行。\n\n使用 Mocha 和 Chai 的简单测试示例：\n\n```js\nconst { expect } = require('chai');\n\ndescribe('Array', () => {\n  it('should return -1 when the value is not present', () => {\n    expect([1, 2, 3].indexOf(4)).to.equal(-1);\n  });\n});\n```\n\n### Jasmine\n\nJasmine 是一个用于测试 JavaScript 代码的行为驱动开发 (BDD) 框架。 它以其简单性和易用性而闻名。\n\n* **简单性**：Jasmine 附带了您开始测试所需的一切，包括断言库和模拟工具。\n* **BDD 风格**：Jasmine 鼓励以 BDD 风格编写测试，这可以使您的测试更具可读性。\n\n使用 Jasmine 的简单测试示例：\n\n```js\ndescribe('A suite', () => {\n  it('contains a spec with an expectation', () => {\n    expect(true).toBe(true);\n  });\n});\n```\n\n### Cypress\n\nCypress 是一个端到端测试框架，专注于真实的浏览器交互。\n\n* **真实浏览器测试**：Cypress 在浏览器中运行测试，提供更准确的用户交互表示。\n* **时间旅行**：Cypress 允许您回溯时间，查看测试的每个步骤发生了什么。\n* **自动等待**：Cypress 自动等待元素出现和操作完成，减少了手动等待的需要。\n\n使用 Cypress 的简单测试示例：\n\n```js\ndescribe('My First Test', () => {\n  it('Visits the Kitchen Sink', () => {\n    cy.visit('https://example.cypress.io');\n    cy.contains('type').click();\n    cy.url().should('include', '/commands/actions');\n    cy.get('.action-email')\n      .type('fake@email.com')\n      .should('have.value', 'fake@email.com');\n  });\n});\n```\n\n## 延伸阅读\n\n* [Jest documentation](https://jestjs.io/docs/getting-started)\n* [Mocha documentation](https://mochajs.org/)\n* [Jasmine documentation](https://jasmine.github.io/)\n* [Cypress documentation](https://docs.cypress.io/guides/overview/why-cypress)\n"
  },
  {
    "path": "questions/what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"23216d82\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"26122f94\",\n        \"2a7816d0\",\n        \"3c560570\",\n        \"9691800c\",\n        \"7e4068da\",\n        \"c44c1f6b\",\n        \"f2b84a2a\",\n        \"3d77f92\",\n        \"91e6f82e\",\n        \"a312a3f7\",\n        \"d3e03e76\",\n        \"acfcd3ce\",\n        \"d2365e35\",\n        \"af0fce2\",\n        \"92c2140\",\n        \"1f4770e5\",\n        \"146b3afc\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"26122f94\",\n        \"2a7816d0\",\n        \"3c560570\",\n        \"9691800c\",\n        \"7e4068da\",\n        \"c44c1f6b\",\n        \"f2b84a2a\",\n        \"3d77f92\",\n        \"91e6f82e\",\n        \"a312a3f7\",\n        \"d3e03e76\",\n        \"acfcd3ce\",\n        \"d2365e35\",\n        \"af0fce2\",\n        \"92c2140\",\n        \"1f4770e5\",\n        \"146b3afc\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance/en-US.mdx",
    "content": "---\ntitle: What are some tools that can be used to measure and analyze JavaScript performance?\n---\n\n## TL;DR\n\nTo measure and analyze JavaScript performance, you can use tools like Chrome DevTools, Lighthouse, WebPageTest, and JSPerf. Chrome DevTools provides a Performance panel for profiling, Lighthouse offers audits for performance metrics, WebPageTest allows for detailed performance testing, and JSPerf helps in comparing the performance of different JavaScript snippets.\n\n---\n\n## Tools to measure and analyze JavaScript performance\n\n### Chrome DevTools\n\nChrome DevTools is a set of web developer tools built directly into the Google Chrome browser. It provides a Performance panel that allows you to record and analyze the runtime performance of your web application.\n\n- Open Chrome DevTools by pressing `F12` or `Ctrl+Shift+I`\n- Navigate to the Performance panel\n- Click the \"Record\" button to start profiling\n- Interact with your web application to capture performance data\n- Click the \"Stop\" button to end profiling and analyze the results\n\n### Lighthouse\n\nLighthouse is an open-source, automated tool for improving the quality of web pages. It provides audits for performance, accessibility, progressive web apps, SEO, and more.\n\n- Open Chrome DevTools\n- Navigate to the Lighthouse panel\n- Select the categories you want to audit (e.g., Performance)\n- Click the \"Generate report\" button\n- Review the generated report for performance insights and recommendations\n\n### WebPageTest\n\nWebPageTest is a free online tool that provides detailed performance testing of web pages. It allows you to run tests from multiple locations around the world using real browsers.\n\n- Go to [WebPageTest](https://www.webpagetest.org/)\n- Enter the URL of the web page you want to test\n- Select the test location and browser\n- Click the \"Start Test\" button\n- Review the detailed performance report, including metrics like load time, time to first byte, and more\n\n### JSPerf\n\nJSPerf is a tool for comparing the performance of different JavaScript snippets. It allows you to create and run benchmarks to see which code performs better.\n\n- Go to [JSPerf](https://jsperf.com/)\n- Create a new test case by entering different JavaScript snippets\n- Run the benchmark to compare the performance of the snippets\n- Review the results to see which snippet performs better\n\n## Further reading\n\n- [Chrome DevTools Performance Panel](https://developer.chrome.com/docs/devtools/evaluate-performance/)\n- [Lighthouse](https://developers.google.com/web/tools/lighthouse)\n- [WebPageTest](https://www.webpagetest.org/)\n- [JSPerf](https://jsperf.com/)\n"
  },
  {
    "path": "questions/what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance/metadata.json",
    "content": "{\n  \"slug\": \"what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"advanced\",\n  \"topics\": [\"javascript\", \"performance\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Performance Optimization\"\n}\n"
  },
  {
    "path": "questions/what-are-some-tools-that-can-be-used-to-measure-and-analyze-javascript-performance/zh-CN.mdx",
    "content": "---\ntitle: 有哪些可以用来衡量和分析 JavaScript 性能的工具？\n---\n\n## TL;DR\n\n要衡量和分析 JavaScript 性能，可以使用 Chrome DevTools、Lighthouse、WebPageTest 和 JSPerf 等工具。Chrome DevTools 提供了一个用于分析的 Performance 面板，Lighthouse 提供性能指标的审核，WebPageTest 允许进行详细的性能测试，而 JSPerf 有助于比较不同 JavaScript 代码段的性能。\n\n***\n\n## 用于衡量和分析 JavaScript 性能的工具\n\n### Chrome DevTools\n\nChrome DevTools 是一组直接内置于 Google Chrome 浏览器中的 Web 开发者工具。它提供了一个 Performance 面板，允许您录制和分析 Web 应用程序的运行时性能。\n\n* 通过按 `F12` 或 `Ctrl+Shift+I` 打开 Chrome DevTools\n* 导航到 Performance 面板\n* 单击“Record”按钮开始分析\n* 与您的 Web 应用程序交互以捕获性能数据\n* 单击“Stop”按钮结束分析并分析结果\n\n### Lighthouse\n\nLighthouse 是一个开源的自动化工具，用于提高网页质量。它提供了对性能、可访问性、渐进式 Web 应用程序、SEO 等方面的审核。\n\n* 打开 Chrome DevTools\n* 导航到 Lighthouse 面板\n* 选择您要审核的类别（例如，性能）\n* 单击“Generate report”按钮\n* 查看生成的报告以获取性能见解和建议\n\n### WebPageTest\n\nWebPageTest 是一个免费的在线工具，提供对网页的详细性能测试。它允许您使用真实的浏览器从世界各地运行测试。\n\n* 访问 [WebPageTest](https://www.webpagetest.org/)\n* 输入您要测试的网页的 URL\n* 选择测试位置和浏览器\n* 单击“Start Test”按钮\n* 查看详细的性能报告，包括加载时间、首次字节时间等指标\n\n### JSPerf\n\nJSPerf 是一个用于比较不同 JavaScript 代码段性能的工具。它允许您创建和运行基准测试，以查看哪个代码的性能更好。\n\n* 访问 [JSPerf](https://jsperf.com/)\n* 通过输入不同的 JavaScript 代码段来创建新的测试用例\n* 运行基准测试以比较代码段的性能\n* 查看结果以了解哪个代码段的性能更好\n\n## 延伸阅读\n\n* [Chrome DevTools Performance Panel](https://developer.chrome.com/docs/devtools/evaluate-performance/)\n* [Lighthouse](https://developers.google.com/web/tools/lighthouse)\n* [WebPageTest](https://www.webpagetest.org/)\n* [JSPerf](https://jsperf.com/)\n"
  },
  {
    "path": "questions/what-are-symbols-used-for/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"9ececef0\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"52803f22\",\n        \"f2202eff\",\n        \"1234dd14\",\n        \"2a7816d0\",\n        \"e08d3ab8\",\n        \"29b6d840\",\n        \"9d9b7893\",\n        \"3d9b9578\",\n        \"63b8b4fc\",\n        \"b6ddc2d\",\n        \"24e3b828\",\n        \"5ae25d8b\",\n        \"d7ff0f80\",\n        \"2e223bf6\",\n        \"2bc773de\",\n        \"97959393\",\n        \"48aa66cc\",\n        \"6dd1724b\",\n        \"ba710b5a\",\n        \"7b441dab\",\n        \"1c759058\",\n        \"35ff3ba1\",\n        \"e56f796a\",\n        \"6fe8770b\",\n        \"c936499e\",\n        \"fef1f85c\",\n        \"33182f07\",\n        \"90368954\",\n        \"67a1d4f3\",\n        \"4f19066f\",\n        \"1f4770e5\",\n        \"34fcd156\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"52803f22\",\n        \"f2202eff\",\n        \"1234dd14\",\n        \"2a7816d0\",\n        \"e08d3ab8\",\n        \"29b6d840\",\n        \"9d9b7893\",\n        \"3d9b9578\",\n        \"63b8b4fc\",\n        \"b6ddc2d\",\n        \"24e3b828\",\n        \"5ae25d8b\",\n        \"d7ff0f80\",\n        \"2e223bf6\",\n        \"2bc773de\",\n        \"97959393\",\n        \"48aa66cc\",\n        \"6dd1724b\",\n        \"ba710b5a\",\n        \"7b441dab\",\n        \"1c759058\",\n        \"35ff3ba1\",\n        \"e56f796a\",\n        \"6fe8770b\",\n        \"c936499e\",\n        \"fef1f85c\",\n        \"33182f07\",\n        \"90368954\",\n        \"67a1d4f3\",\n        \"4f19066f\",\n        \"1f4770e5\",\n        \"34fcd156\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-symbols-used-for/en-US.mdx",
    "content": "---\ntitle: What are `Symbol`s used for in JavaScript?\n---\n\n## TL;DR\n\n`Symbol`s in JavaScript are a new primitive data type introduced in ES6 (ECMAScript 2015). They are unique and immutable identifiers that is primarily for object property keys to avoid name collisions. These values can be created using `Symbol(...)` function, and each `Symbol` value is guaranteed to be unique, even if they have the same key/description. `Symbol` properties are not enumerable in `for...in` loops or `Object.keys()`, making them suitable for creating private/internal object state.\n\n```js live\nlet sym1 = Symbol();\nlet sym2 = Symbol('myKey');\n\nconsole.log(typeof sym1); // \"symbol\"\nconsole.log(sym1 === sym2); // false, because each symbol is unique\n\nlet obj = {};\nlet sym = Symbol('uniqueKey');\n\nobj[sym] = 'value';\nconsole.log(obj[sym]); // \"value\"\n```\n\n**Note**: The `Symbol()` function must be called without the `new` keyword. It is not exactly a constructor because it can only be called as a function instead of with `new Symbol()`.\n\n---\n\n## `Symbol`s in JavaScript\n\nSymbols in JavaScript are a unique and immutable data type used primarily for object property keys to avoid name collisions.\n\n## Key characteristics\n\n- **Uniqueness**: Each Symbol value is unique, even if they have the same description.\n- **Immutability**: Symbol values are immutable, meaning their value cannot be changed.\n- **Non-enumerable**: Symbol properties are not included in for...in loops or Object.keys().\n\n## Creating `Symbol`s\n\n`Symbol`s can be created using the `Symbol()` function:\n\n```js live\nconst sym1 = Symbol();\nconst sym2 = Symbol('uniqueKey');\n\nconsole.log(typeof sym1); // \"symbol\"\nconsole.log(sym1 === sym2); // false, because each symbol is unique\n```\n\n> The `Symbol(..)` function must be called without the `new` keyword.\n\n## Using `Symbol`s as `object` property keys\n\n`Symbol`s can be used to add properties to an object without risk of name collision:\n\n```js live\nconst obj = {};\nconst sym = Symbol('uniqueKey');\n\nobj[sym] = 'value';\nconsole.log(obj[sym]); // \"value\"\n```\n\n## `Symbol`s are not enumerable\n\n- `Symbol` properties are not included in `for...in` loops or` Object.keys()`.\n- This makes them suitable for creating private/internal object state.\n- Use` Object.getOwnPropertySymbols(obj)` to get all symbol properties on an object.\n\n```js live\nconst mySymbol = Symbol('privateProperty');\nconst obj = {\n  name: 'John',\n  [mySymbol]: 42,\n};\n\nconsole.log(Object.keys(obj)); // Output: ['name']\nconsole.log(obj[mySymbol]); // Output: 42\n```\n\n### Global `Symbol` registry\n\nYou can create global `Symbol`s using `Symbol.for('key')`, which creates a new `Symbol` in the global registry if it doesn't exist, or returns the existing one. This allows you to reuse `Symbol`s across different parts of your code base or even across different code bases.\n\n```js live\nconst globalSym1 = Symbol.for('globalKey');\nconst globalSym2 = Symbol.for('globalKey');\n\nconsole.log(globalSym1 === globalSym2); // true\n\nconst key = Symbol.keyFor(globalSym1);\nconsole.log(key); // \"globalKey\"\n```\n\n## Well-known `Symbol`\n\nJavaScript includes several built-in `Symbol`s, referred as well-known `Symbol`s.\n\n- **`Symbol.iterator`**: Defines the default `iterator` for an object.\n- **`Symbol.toStringTag`**: Used to create a string description for an object.\n- **`Symbol.hasInstance`**: Used to determine if an object is an instance of a constructor.\n\n### `Symbol.iterator`\n\n```js live\nlet iterable = {\n  [Symbol.iterator]() {\n    let step = 0;\n    return {\n      next() {\n        step++;\n        if (step <= 5) {\n          return { value: step, done: false };\n        }\n        return { done: true };\n      },\n    };\n  },\n};\n\nfor (let value of iterable) {\n  console.log(value); // 1, 2, 3, 4, 5\n}\n```\n\n### `Symbol.toStringTag`\n\n```js live\nlet myObj = {\n  [Symbol.toStringTag]: 'MyCustomObject',\n};\n\nconsole.log(Object.prototype.toString.call(myObj)); // \"[object MyCustomObject]\"\n```\n\n## Summary\n\nSymbols are a powerful feature in JavaScript, especially useful for creating unique object properties and customizing object behavior. They provide a means to create hidden properties, preventing accidental access or modification, which is particularly beneficial in large-scale applications and libraries.\n\n## Further reading\n\n- [Symbol - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)\n- [Symbol type](https://javascript.info/symbol)\n- [A quick overview of JavaScript symbols](https://www.freecodecamp.org/news/how-did-i-miss-javascript-symbols-c1f1c0e1874a/)\n- [Symbol Values - You Don't Know JS Yet](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/types-grammar/ch1.md#symbol-values)\n"
  },
  {
    "path": "questions/what-are-symbols-used-for/metadata.json",
    "content": "{\n  \"slug\": \"what-are-symbols-used-for\",\n  \"languages\": [],\n  \"companies\": [\"bytedance\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 430,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-symbols-used-for/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中 `Symbol` 的用途是什么？\n---\n\n## 总结\n\nJavaScript 中的 `Symbol` 是 ES6 (ECMAScript 2015) 中引入的一种新的原始数据类型。它们是唯一的、不可变的标识符，主要用于对象属性键，以避免名称冲突。这些值可以使用 `Symbol(...)` 函数创建，并且每个 `Symbol` 值都保证是唯一的，即使它们具有相同的键/描述。`Symbol` 属性在 `for...in` 循环或 `Object.keys()` 中不可枚举，这使得它们适合创建私有/内部对象状态。\n\n```js live\nlet sym1 = Symbol();\nlet sym2 = Symbol('myKey');\n\nconsole.log(typeof sym1); // \"symbol\"\nconsole.log(sym1 === sym2); // false, because each symbol is unique\n\nlet obj = {};\nlet sym = Symbol('uniqueKey');\n\nobj[sym] = 'value';\nconsole.log(obj[sym]); // \"value\"\n```\n\n**注意**：`Symbol()` 函数必须在没有 `new` 关键字的情况下调用。它并不完全是一个构造函数，因为它只能作为函数调用，而不是使用 `new Symbol()`。\n\n***\n\n## JavaScript 中的 `Symbol`\n\nJavaScript 中的 Symbols 是一种独特且不可变的数据类型，主要用于对象属性键，以避免名称冲突。\n\n## 关键特征\n\n* **唯一性**：每个 Symbol 值都是唯一的，即使它们具有相同的描述。\n* **不可变性**：Symbol 值是不可变的，这意味着它们的值不能被更改。\n* **不可枚举性**：Symbol 属性不包含在 for...in 循环或 Object.keys() 中。\n\n## 创建 `Symbol`\n\n`Symbol` 可以使用 `Symbol()` 函数创建：\n\n```js live\nconst sym1 = Symbol();\nconst sym2 = Symbol('uniqueKey');\n\nconsole.log(typeof sym1); // \"symbol\"\nconsole.log(sym1 === sym2); // false, because each symbol is unique\n```\n\n> 必须在没有 `new` 关键字的情况下调用 `Symbol(..)` 函数。\n\n## 将 `Symbol` 用作 `object` 属性键\n\n`Symbol` 可用于将属性添加到对象，而不会有名称冲突的风险：\n\n```js live\nconst obj = {};\nconst sym = Symbol('uniqueKey');\n\nobj[sym] = 'value';\nconsole.log(obj[sym]); // \"value\"\n```\n\n## `Symbol` 不可枚举\n\n* `Symbol` 属性不包含在 `for...in` 循环或 `Object.keys()` 中。\n* 这使得它们适合创建私有/内部对象状态。\n* 使用 `Object.getOwnPropertySymbols(obj)` 获取对象上的所有 symbol 属性。\n\n```js live\nconst mySymbol = Symbol('privateProperty');\nconst obj = {\n  name: 'John',\n  [mySymbol]: 42,\n};\n\nconsole.log(Object.keys(obj)); // Output: ['name']\nconsole.log(obj[mySymbol]); // Output: 42\n```\n\n### 全局 `Symbol` 注册表\n\n您可以使用 `Symbol.for('key')` 创建全局 `Symbol`，如果全局注册表中不存在，则创建一个新的 `Symbol`，或者返回现有的 `Symbol`。这允许您在代码库的不同部分甚至不同的代码库之间重用 `Symbol`。\n\n```js live\nconst globalSym1 = Symbol.for('globalKey');\nconst globalSym2 = Symbol.for('globalKey');\n\nconsole.log(globalSym1 === globalSym2); // true\n\nconst key = Symbol.keyFor(globalSym1);\nconsole.log(key); // \"globalKey\"\n```\n\n## 众所周知的 `Symbol`\n\nJavaScript 包含几个内置的 `Symbol`，称为众所周知的 `Symbol`。\n\n* **`Symbol.iterator`**：定义对象的默认 `iterator`。\n* **`Symbol.toStringTag`**：用于创建对象的字符串描述。\n* **`Symbol.hasInstance`**：用于确定对象是否是构造函数的实例。\n\n### `Symbol.iterator`\n\n```js live\nlet iterable = {\n  [Symbol.iterator]() {\n    let step = 0;\n    return {\n      next() {\n        step++;\n        if (step <= 5) {\n          return { value: step, done: false };\n        }\n        return { done: true };\n      },\n    };\n  },\n};\n\nfor (let value of iterable) {\n  console.log(value); // 1, 2, 3, 4, 5\n}\n```\n\n### `Symbol.toStringTag`\n\n```js live\nlet myObj = {\n  [Symbol.toStringTag]: 'MyCustomObject',\n};\n\nconsole.log(Object.prototype.toString.call(myObj)); // \"[object MyCustomObject]\"\n```\n\n## 总结\n\nSymbol 是 JavaScript 中一项强大的功能，尤其适用于创建唯一的对象属性和自定义对象行为。它们提供了一种创建隐藏属性的方法，防止意外访问或修改，这在大型应用程序和库中特别有益。\n\n## 延伸阅读\n\n* [Symbol - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol)\n* [Symbol type](https://javascript.info/symbol)\n* [A quick overview of JavaScript symbols](https://www.freecodecamp.org/news/how-did-i-miss-javascript-symbols-c1f1c0e1874a/)\n* [Symbol Values - You Don't Know JS Yet](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/types-grammar/ch1.md#symbol-values)\n"
  },
  {
    "path": "questions/what-are-template-literals-and-how-are-they-used/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"af22901\",\n        \"e76b9a8\",\n        \"9ed51b7a\",\n        \"2a7816d0\",\n        \"525b39dd\",\n        \"560ae1bb\",\n        \"aec5d635\",\n        \"eea083fa\",\n        \"4ae016ea\",\n        \"34865eda\",\n        \"b007ea35\",\n        \"e76b9a8\",\n        \"5e51808f\",\n        \"bc788ade\",\n        \"d2711399\",\n        \"e76b9a8\",\n        \"e1b25c22\",\n        \"f5ffe889\",\n        \"289bb623\",\n        \"e76b9a8\",\n        \"f23627e0\",\n        \"fde57cf1\",\n        \"95c9e077\",\n        \"e76b9a8\",\n        \"deef4b72\",\n        \"1f4770e5\",\n        \"4725cb97\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"af22901\",\n        \"e76b9a8\",\n        \"9ed51b7a\",\n        \"2a7816d0\",\n        \"525b39dd\",\n        \"560ae1bb\",\n        \"aec5d635\",\n        \"eea083fa\",\n        \"4ae016ea\",\n        \"34865eda\",\n        \"b007ea35\",\n        \"e76b9a8\",\n        \"5e51808f\",\n        \"bc788ade\",\n        \"d2711399\",\n        \"e76b9a8\",\n        \"e1b25c22\",\n        \"f5ffe889\",\n        \"289bb623\",\n        \"e76b9a8\",\n        \"f23627e0\",\n        \"fde57cf1\",\n        \"95c9e077\",\n        \"e76b9a8\",\n        \"deef4b72\",\n        \"1f4770e5\",\n        \"4725cb97\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"1c06c8ed\"\n  }\n}\n"
  },
  {
    "path": "questions/what-are-template-literals-and-how-are-they-used/en-US.mdx",
    "content": "---\ntitle: What are template literals and how are they used?\n---\n\n## TL;DR\n\nTemplate literals are a feature in JavaScript that allow for easier string interpolation and multi-line strings. They are enclosed by backticks (`` ` ``) instead of single or double quotes. You can embed expressions within template literals using `${expression}` syntax.\n\nExample:\n\n```js live\nconst myName = 'John';\nconst greeting = `Hello, ${myName}!`;\nconsole.log(greeting); // Output: Hello, John!\n```\n\n---\n\n## What are template literals and how are they used?\n\n### Introduction to template literals\n\nTemplate literals are a feature introduced in ES6 (ECMAScript 2015) that provide an easier and more readable way to work with strings in JavaScript. They allow for string interpolation, multi-line strings, and embedded expressions.\n\n### Syntax\n\nTemplate literals are enclosed by backticks (`` ` ``) instead of single or double quotes. This allows for more flexible string formatting.\n\n### String interpolation\n\nOne of the most powerful features of template literals is string interpolation. You can embed expressions within a string using `${expression}` syntax.\n\nExample:\n\n```js live\nconst myName = 'John';\nconst age = 30;\nconst greeting = `Hello, my name is ${myName} and I am ${age} years old.`;\nconsole.log(greeting); // Output: Hello, my name is John and I am 30 years old.\n```\n\n### Multi-line strings\n\nTemplate literals make it easy to create multi-line strings without the need for escape characters.\n\nExample:\n\n```js live\nconst multiLineString = `This is a string\nthat spans multiple\nlines.`;\nconsole.log(multiLineString);\n// Output:\n// This is a string\n// that spans multiple\n// lines.\n```\n\n### Tagged templates\n\nTagged templates allow you to parse template literals with a function. The function can then manipulate the template literal's content before it is output.\n\nExample:\n\n```js live\nfunction tag(strings, ...values) {\n  console.log(strings); // Array of string literals: [\"Hello, \", \"!\"]\n  console.log(values); // Array of values: [\"John\"]\n  return 'Custom tagged template result';\n}\n\nconst myName = 'John';\nconst result = tag`Hello, ${myName}!`;\nconsole.log(result); // Output: Custom tagged template result\n```\n\n### Nesting template literals\n\nYou can nest template literals within each other for more complex string constructions.\n\nExample:\n\n```js live\nconst myName = 'John';\nconst age = 30;\nconst nestedTemplate = `Name: ${myName}, Age: ${age}, Info: ${`Name: ${myName}, Age: ${age}`}`;\nconsole.log(nestedTemplate);\n// Output: Name: John, Age: 30, Info: Name: John, Age: 30\n```\n\n## Further reading\n\n- [MDN Web Docs: Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)\n- [Qwirey.com: Template literals](https://qwirey.com/technology/es6-features.html#qwp-fold-templateliterals)\n"
  },
  {
    "path": "questions/what-are-template-literals-and-how-are-they-used/metadata.json",
    "content": "{\n  \"slug\": \"what-are-template-literals-and-how-are-they-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Data Types & Variables\"\n}\n"
  },
  {
    "path": "questions/what-are-template-literals-and-how-are-they-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是模板字面量以及如何使用它们？\n---\n\n## TL;DR\n\n模板字面量是 JavaScript 中的一个特性，它允许更轻松的字符串插值和多行字符串。它们用反引号 (`` ` ``) 而不是单引号或双引号括起来。您可以使用 `${expression}` 语法在模板字面量中嵌入表达式。\n\n示例：\n\n```js live\nconst myName = 'John';\nconst greeting = `Hello, ${myName}!`;\nconsole.log(greeting); // Output: Hello, John!\n```\n\n***\n\n## 什么是模板字面量以及如何使用它们？\n\n### 模板字面量简介\n\n模板字面量是 ES6 (ECMAScript 2015) 中引入的一个特性，它提供了一种更简单、更易读的方式来处理 JavaScript 中的字符串。它们允许字符串插值、多行字符串和嵌入表达式。\n\n### 语法\n\n模板字面量用反引号 (`` ` ``) 而不是单引号或双引号括起来。这允许更灵活的字符串格式化。\n\n### 字符串插值\n\n模板字面量最强大的功能之一是字符串插值。您可以使用 `${expression}` 语法在字符串中嵌入表达式。\n\n示例：\n\n```js live\nconst myName = 'John';\nconst age = 30;\nconst greeting = `Hello, my name is ${myName} and I am ${age} years old.`;\nconsole.log(greeting); // Output: Hello, my name is John and I am 30 years old.\n```\n\n### 多行字符串\n\n模板字面量可以轻松创建多行字符串，而无需转义字符。\n\n示例：\n\n```js live\nconst multiLineString = `This is a string\nthat spans multiple\nlines.`;\nconsole.log(multiLineString);\n// Output:\n// This is a string\n// that spans multiple\n// lines.\n```\n\n### 标记模板\n\n标记模板允许您使用函数解析模板字面量。然后，该函数可以在输出模板字面量的内容之前对其进行操作。\n\n示例：\n\n```js live\nfunction tag(strings, ...values) {\n  console.log(strings); // Array of string literals: [\"Hello, \", \"!\"]\n  console.log(values); // Array of values: [\"John\"]\n  return 'Custom tagged template result';\n}\n\nconst myName = 'John';\nconst result = tag`Hello, ${myName}!`;\nconsole.log(result); // Output: Custom tagged template result\n```\n\n### 嵌套模板字面量\n\n您可以在彼此之间嵌套模板字面量，以构建更复杂的字符串。\n\n示例：\n\n```js live\nconst myName = 'John';\nconst age = 30;\nconst nestedTemplate = `Name: ${myName}, Age: ${age}, Info: ${`Name: ${myName}, Age: ${age}`}`;\nconsole.log(nestedTemplate);\n// Output: Name: John, Age: 30, Info: Name: John, Age: 30\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)\n* [Qwirey.com: Template literals](https://qwirey.com/technology/es6-features.html#qwp-fold-templateliterals)\n"
  },
  {
    "path": "questions/what-are-the-advantages-and-disadvantages-of-using-ajax/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"19d259f4\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"593e1e8d\",\n        \"87deb665\",\n        \"52fe02c3\",\n        \"d37b5b85\",\n        \"a76b56e3\",\n        \"2a7816d0\",\n        \"cf7256bd\",\n        \"8dc822d1\",\n        \"c9f6d324\",\n        \"852195c\",\n        \"3a134047\",\n        \"82c3077\",\n        \"d758718c\",\n        \"8437ff7b\",\n        \"1f4770e5\",\n        \"d884c1e2\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"593e1e8d\",\n        \"87deb665\",\n        \"52fe02c3\",\n        \"d37b5b85\",\n        \"a76b56e3\",\n        \"2a7816d0\",\n        \"cf7256bd\",\n        \"8dc822d1\",\n        \"c9f6d324\",\n        \"852195c\",\n        \"3a134047\",\n        \"82c3077\",\n        \"d758718c\",\n        \"8437ff7b\",\n        \"1f4770e5\",\n        \"d884c1e2\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-advantages-and-disadvantages-of-using-ajax/en-US.mdx",
    "content": "---\ntitle: What are the advantages and disadvantages of using AJAX?\n---\n\n## TL;DR\n\nAJAX (Asynchronous JavaScript and XML) is a technique in JavaScript that allows web pages to send and retrieve data asynchronously from servers without refreshing or reloading the entire page.\n\n**Advantages**\n\n- **Smoother user experience**: Updates happen without full page reloads, like in mail and chat applications.\n- **Lighter server Load**: Only necessary data is fetched via AJAX, reducing server load and improving perceived performance of webpages.\n- **Maintains client state**: User interactions and any client states are persisted within the page.\n\n**Disadvantages**\n\n- **Reliance on JavaScript**: If disabled, Ajax functionality breaks.\n- **Bookmarking issues**: Dynamic content makes bookmarking specific page states difficult.\n- **SEO Challenges**: Search engines may struggle to index dynamic content.\n- **Performance Concerns**: Processing Ajax data on low-end devices can be slow.\n\n---\n\n## AJAX (Asynchronous JavaScript and XML)\n\nAJAX (Asynchronous JavaScript and XML) is a technique in JavaScript that allows web pages to send and retrieve data asynchronously from servers without refreshing or reloading the entire page. When it was first created, it revolutionized web development and resulted in a smoother and more responsive user experience. AJAX is explained in detail in [this question](/questions/quiz/explain-ajax-in-as-much-detail-as-possible).\n\nHere's a breakdown of AJAX's pros and cons:\n\n### Advantages\n\n- **Enhanced user experience**: AJAX allows for partial page updates without full reloads. This creates a smoother and more responsive feel for users, as they don't have to wait for the entire page to refresh for every interaction.\n- **Reduced server load and bandwidth usage**: By exchanging only specific data with the server, AJAX minimizes the amount of data transferred. This leads to faster loading times and reduced server strain, especially for frequently updated content.\n- **Improved performance**: Faster data exchange and partial page updates contribute to a quicker web application overall. Users perceive the application as more responsive and efficient.\n- **Dynamic content updates, preserving client-only state**: AJAX enables real-time data updates without full page reloads, preserving client-only state like form inputs and scroll positions. This is ideal for features like live chat, stock tickers, or collaborative editing.\n- **Form validation**: AJAX can be used for client-side form validation that requires back end interactions (e.g. checking for duplicate usernames), providing immediate feedback to users without requiring a form submission request. This improves the user experience and avoids unnecessary full page reloads for invalid submissions.\n\n### Disadvantages\n\n- **Increased complexity**: Developing AJAX-powered applications can be more complex compared to traditional web development. It requires handling asynchronous communication and potential race conditions between requests and responses. Since pages are not reloaded, parts of the page can be outdated overtime and can be confusing.\n- **Dependency on JavaScript**: AJAX relies on JavaScript to function. Users with JavaScript disabled or unsupported browsers won't experience the full functionality of the application. A fallback mechanism (graceful degradation) is necessary to ensure basic functionality for these users.\n- **Security concerns**: AJAX introduces new security considerations like Cross-Site Scripting (XSS) vulnerabilities (if servers return directly HTML markup) if not implemented carefully. Proper data validation and sanitization are crucial to prevent security risks.\n- **Browser support**: Older browsers might not fully support AJAX features. Developers need to consider compatibility when building with AJAX to ensure a good user experience across different browsers.\n- **SEO challenges**: Search engines might have difficulty indexing content dynamically loaded through AJAX. Developers need to employ techniques like server-side rendering or proper content embedding to ensure search engine visibility.\n- **Navigation problems**: AJAX can interfere with the browser's back and forward navigation buttons, as well as bookmarking, since the URL may not change with asynchronous updates.\n- **State management**: Maintaining the application state and ensuring proper navigation can be challenging with AJAX, requiring additional techniques such as the History API or URL hash fragments.\n\nWhile AJAX offers significant advantages in terms of user experience, performance, and functionality, it also introduces complexities and potential drawbacks related to development, SEO, browser compatibility, security, and navigation.\n\n## Further reading\n\n- [Ajax | MDN](https://developer.mozilla.org/en-US/docs/Glossary/AJAX)\n- [Fetching data from the server | MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data)\n"
  },
  {
    "path": "questions/what-are-the-advantages-and-disadvantages-of-using-ajax/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-advantages-and-disadvantages-of-using-ajax\",\n  \"languages\": [],\n  \"companies\": [\"google\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"networking\"],\n  \"importance\": \"medium\",\n  \"ranking\": 280,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/what-are-the-advantages-and-disadvantages-of-using-ajax/pt-BR.mdx",
    "content": "---\ntitle: Quais são as vantagens e desvantagens de usar o Ajax?\n---\n\n## Vantagens\n\n- Melhor interatividade. O novo conteúdo do servidor pode ser alterado dinamicamente sem a necessidade de recarregar a página inteira.\n- Reduzir conexões para o servidor, pois scripts e folhas de estilo só precisam ser solicitados uma vez.\n- O State pode ser mantido em uma página. As variáveis do JavaScript e o estado do DOM persistirão porque a página principal do contêiner não foi recarregada.\n- Basicamente, a maioria das vantagens de um SPA.\n\n## Desvantagens\n\n- Páginas dinâmicas da web são mais difíceis de favoritar.\n- Não funciona se o JavaScript foi desativado no navegador.\n- Alguns rastreadores web não executam JavaScript e não veem o conteúdo que foi carregado pelo JavaScript.\n- Páginas web que usam Ajax para buscar dados provavelmente terão que combinar os dados remotos com modelos do lado cliente para atualizar o DOM. Para que isso aconteça, o JavaScript terá que ser analisado e executado no navegador, e dispositivos móveis de baixo custo podem ter problemas com isso.\n- Basicamente, a maioria das vantagens de um SPA.\n"
  },
  {
    "path": "questions/what-are-the-advantages-and-disadvantages-of-using-ajax/zh-CN.mdx",
    "content": "---\ntitle: 使用 AJAX 的优缺点是什么？\n---\n\n## TL;DR\n\nAJAX（异步 JavaScript 和 XML）是 JavaScript 中的一种技术，它允许网页从服务器异步发送和检索数据，而无需刷新或重新加载整个页面。\n\n**优点**\n\n* **更流畅的用户体验**：更新发生在没有完全页面重新加载的情况下，就像在邮件和聊天应用程序中一样。\n\n**缺点**\n\n* **依赖于 JavaScript**：如果禁用，Ajax 功能会中断。\n\n***\n\n## AJAX（异步 JavaScript 和 XML）\n\nAJAX（异步 JavaScript 和 XML）是 JavaScript 中的一种技术，它允许网页从服务器异步发送和检索数据，而无需刷新或重新加载整个页面。 当它最初创建时，它彻底改变了 Web 开发，并带来了更流畅、响应更快的用户体验。 AJAX 在[这个问题](/questions/quiz/explain-ajax-in-as-much-detail-as-possible)中进行了详细解释。\n\n以下是 AJAX 优缺点的细分：\n\n### 优点\n\n* **增强的用户体验**：AJAX 允许部分页面更新，而无需完全重新加载。 这为用户创造了更流畅、更灵敏的感觉，因为他们不必等待整个页面在每次交互时刷新。\n\n### 缺点\n\n* **增加复杂性**：与传统的 Web 开发相比，开发支持 AJAX 的应用程序可能更复杂。 它需要处理异步通信以及请求和响应之间的潜在竞争条件。 由于页面没有重新加载，页面的一部分可能会随着时间的推移而过时，并且可能会造成混淆。\n\n虽然 AJAX 在用户体验、性能和功能方面具有显着的优势，但它也带来了与开发、SEO、浏览器兼容性、安全性和导航相关的复杂性和潜在的缺点。\n\n## 延伸阅读\n\n* [Ajax | MDN](https://developer.mozilla.org/en-US/docs/Glossary/AJAX)\n"
  },
  {
    "path": "questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"40474880\",\n        \"dd28d831\",\n        \"2a7816d0\",\n        \"6afe7b2f\",\n        \"d9a9e73d\",\n        \"6a751511\",\n        \"a0a667a8\",\n        \"eb7b89ee\",\n        \"d73656\",\n        \"f50b1d69\",\n        \"614db4aa\",\n        \"a9349d3\",\n        \"f73a1989\",\n        \"24ff9a8b\",\n        \"205e02a6\",\n        \"e32c4143\",\n        \"5d31c1dc\",\n        \"8c5c60a6\",\n        \"430c6d7f\",\n        \"33557289\",\n        \"7fa4abb1\",\n        \"ae1df12c\",\n        \"354cd757\",\n        \"2c7fba4d\",\n        \"1f4770e5\",\n        \"61ad4258\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"40474880\",\n        \"dd28d831\",\n        \"2a7816d0\",\n        \"6afe7b2f\",\n        \"d9a9e73d\",\n        \"6a751511\",\n        \"a0a667a8\",\n        \"eb7b89ee\",\n        \"d73656\",\n        \"f50b1d69\",\n        \"614db4aa\",\n        \"a9349d3\",\n        \"f73a1989\",\n        \"24ff9a8b\",\n        \"205e02a6\",\n        \"e32c4143\",\n        \"5d31c1dc\",\n        \"8c5c60a6\",\n        \"430c6d7f\",\n        \"33557289\",\n        \"7fa4abb1\",\n        \"ae1df12c\",\n        \"354cd757\",\n        \"2c7fba4d\",\n        \"1f4770e5\",\n        \"61ad4258\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"c7d07a0b\"\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/en-US.mdx",
    "content": "---\ntitle: What are the advantages of using the spread operator with arrays and objects?\n---\n\n## TL;DR\n\nThe spread operator (`...`) in JavaScript allows you to easily copy arrays and objects, merge them, and add new elements or properties. It simplifies syntax and improves readability. For arrays, it can be used to concatenate or clone arrays. For objects, it can be used to merge objects or add new properties.\n\n```js live\n// Arrays\nconst arr1 = [1, 2, 3];\nconst arr2 = [...arr1, 4, 5];\nconsole.log(arr2); // [1, 2, 3, 4, 5]\n\n// Objects\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { ...obj1, c: 3 };\nconsole.log(obj2); // { a: 1, b: 2, c: 3 }\n```\n\n---\n\n## Advantages of using the spread operator with arrays and objects\n\n### Arrays\n\n#### Cloning arrays\n\nThe spread operator allows you to create a shallow copy of an array easily.\n\n```js live\nconst originalArray = [1, 2, 3];\nconst clonedArray = [...originalArray];\nconsole.log(clonedArray); // [1, 2, 3]\n```\n\n#### Merging arrays\n\nYou can concatenate multiple arrays into one.\n\n```js live\nconst array1 = [1, 2];\nconst array2 = [3, 4];\nconst mergedArray = [...array1, ...array2];\nconsole.log(mergedArray); // [1, 2, 3, 4]\n```\n\n#### Adding elements\n\nYou can add new elements to an array without mutating the original array.\n\n```js live\nconst array = [1, 2, 3];\nconst newArray = [...array, 4, 5];\nconsole.log(newArray); // [1, 2, 3, 4, 5]\n```\n\n### Objects\n\n#### Cloning objects\n\nThe spread operator allows you to create a shallow copy of an object.\n\n```js live\nconst originalObject = { a: 1, b: 2 };\nconst clonedObject = { ...originalObject };\nconsole.log(clonedObject); // { a: 1, b: 2 }\n```\n\n#### Merging objects\n\nYou can merge multiple objects into one.\n\n```js live\nconst object1 = { a: 1 };\nconst object2 = { b: 2 };\nconst mergedObject = { ...object1, ...object2 };\nconsole.log(mergedObject); // { a: 1, b: 2 }\n```\n\n#### Adding properties\n\nYou can add new properties to an object without mutating the original object.\n\n```js live\nconst object = { a: 1, b: 2 };\nconst newObject = { ...object, c: 3 };\nconsole.log(newObject); // { a: 1, b: 2, c: 3 }\n```\n\n## Further reading\n\n- [MDN Web Docs: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n- [JavaScript.info: Spread operator](https://javascript.info/rest-parameters-spread#spread-operator)\n- [FreeCodeCamp: JavaScript Spread and Rest Operators](https://www.freecodecamp.org/news/javascript-spread-and-rest-operators/)\n"
  },
  {
    "path": "questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/what-are-the-advantages-of-using-the-spread-operator-with-arrays-and-objects/zh-CN.mdx",
    "content": "---\ntitle: 使用扩展运算符处理数组和对象的优势是什么？\n---\n\n## TL;DR\n\nJavaScript 中的扩展运算符 (`...`) 允许您轻松复制数组和对象、合并它们以及添加新元素或属性。它简化了语法并提高了可读性。对于数组，它可用于连接或克隆数组。对于对象，它可用于合并对象或添加新属性。\n\n```js live\n// Arrays\nconst arr1 = [1, 2, 3];\nconst arr2 = [...arr1, 4, 5];\nconsole.log(arr2); // [1, 2, 3, 4, 5]\n\n// Objects\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { ...obj1, c: 3 };\nconsole.log(obj2); // { a: 1, b: 2, c: 3 }\n```\n\n***\n\n## 使用扩展运算符处理数组和对象的优势\n\n### 数组\n\n#### 克隆数组\n\n扩展运算符允许您轻松创建数组的浅拷贝。\n\n```js live\nconst originalArray = [1, 2, 3];\nconst clonedArray = [...originalArray];\nconsole.log(clonedArray); // [1, 2, 3]\n```\n\n#### 合并数组\n\n您可以将多个数组连接成一个。\n\n```js live\nconst array1 = [1, 2];\nconst array2 = [3, 4];\nconst mergedArray = [...array1, ...array2];\nconsole.log(mergedArray); // [1, 2, 3, 4]\n```\n\n#### 添加元素\n\n您可以在不改变原始数组的情况下向数组添加新元素。\n\n```js live\nconst array = [1, 2, 3];\nconst newArray = [...array, 4, 5];\nconsole.log(newArray); // [1, 2, 3, 4, 5]\n```\n\n### 对象\n\n#### 克隆对象\n\n扩展运算符允许您创建对象的浅拷贝。\n\n```js live\nconst originalObject = { a: 1, b: 2 };\nconst clonedObject = { ...originalObject };\nconsole.log(clonedObject); // { a: 1, b: 2 }\n```\n\n#### 合并对象\n\n您可以将多个对象合并成一个。\n\n```js live\nconst object1 = { a: 1 };\nconst object2 = { b: 2 };\nconst mergedObject = { ...object1, ...object2 };\nconsole.log(mergedObject); // { a: 1, b: 2 }\n```\n\n#### 添加属性\n\n您可以在不改变原始对象的情况下向对象添加新属性。\n\n```js live\nconst object = { a: 1, b: 2 };\nconst newObject = { ...object, c: 3 };\nconsole.log(newObject); // { a: 1, b: 2, c: 3 }\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n* [JavaScript.info: Spread operator](https://javascript.info/rest-parameters-spread#spread-operator)\n* [FreeCodeCamp: JavaScript Spread and Rest Operators](https://www.freecodecamp.org/news/javascript-spread-and-rest-operators/)\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-a-module-bundler/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"a1416a7f\",\n        \"2a7816d0\",\n        \"7d8acf2f\",\n        \"b0df54c6\",\n        \"4744f9ce\",\n        \"fbbfa5e5\",\n        \"3e9bdbb1\",\n        \"aaa56865\",\n        \"fd92fabc\",\n        \"f25df59d\",\n        \"de208217\",\n        \"cf2a3f0b\",\n        \"abb5b127\",\n        \"b642cfb8\",\n        \"b1d69617\",\n        \"2b8fd4f4\",\n        \"8124fa34\",\n        \"8de91377\",\n        \"34a15c6\",\n        \"7057de18\",\n        \"1f4770e5\",\n        \"fdbb2fd0\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"a1416a7f\",\n        \"2a7816d0\",\n        \"7d8acf2f\",\n        \"b0df54c6\",\n        \"4744f9ce\",\n        \"fbbfa5e5\",\n        \"3e9bdbb1\",\n        \"aaa56865\",\n        \"fd92fabc\",\n        \"f25df59d\",\n        \"de208217\",\n        \"cf2a3f0b\",\n        \"abb5b127\",\n        \"b642cfb8\",\n        \"b1d69617\",\n        \"2b8fd4f4\",\n        \"8124fa34\",\n        \"8de91377\",\n        \"34a15c6\",\n        \"7057de18\",\n        \"1f4770e5\",\n        \"fdbb2fd0\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"6a0d5cae\"\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-a-module-bundler/en-US.mdx",
    "content": "---\ntitle: What are the benefits of using a module bundler?\n---\n\n## TL;DR\n\nUsing a module bundler like Webpack, Rollup, or Parcel helps manage dependencies, optimize performance, and improve the development workflow. It combines multiple JavaScript files into a single file or a few files, which reduces the number of HTTP requests and can include features like code splitting, tree shaking, and hot module replacement.\n\n---\n\n## Benefits of using a module bundler\n\n### Dependency management\n\nA module bundler helps manage dependencies by allowing you to import and export modules in a clean and organized manner. This makes it easier to maintain and understand the codebase.\n\n```js\n// Importing a module\nimport { myFunction } from './myModule.js';\n\n// Using the imported function\nmyFunction();\n```\n\n### Performance optimization\n\nModule bundlers can optimize performance by reducing the number of HTTP requests. They combine multiple JavaScript files into a single file or a few files, which can significantly improve load times.\n\n### Code splitting\n\nCode splitting allows you to split your code into smaller chunks that can be loaded on demand. This can improve the initial load time of your application by only loading the necessary code.\n\n```js\n// Example of dynamic import for code splitting\nimport('./myModule.js').then((module) => {\n  module.myFunction();\n});\n```\n\n### Tree shaking\n\nTree shaking is a feature that removes unused code from the final bundle. This helps reduce the bundle size and improve performance.\n\n```js\n// Only the used function will be included in the final bundle\nimport { usedFunction } from './myModule.js';\nusedFunction();\n```\n\n### Hot module replacement\n\nHot module replacement (HMR) allows you to update modules in real-time without refreshing the entire page. This can significantly speed up the development process by providing instant feedback.\n\n```js\nif (module.hot) {\n  module.hot.accept('./myModule.js', function () {\n    // Handle the updated module\n    const updatedModule = require('./myModule.js');\n    updatedModule.myFunction();\n  });\n}\n```\n\n### Asset management\n\nModule bundlers can also handle other assets like CSS, images, and fonts. This allows you to import these assets directly into your JavaScript files, making it easier to manage and optimize them.\n\n```js\n// Importing a CSS file\nimport './styles.css';\n\n// Importing an image\nimport myImage from './image.png';\n```\n\n## Further reading\n\n- [Webpack documentation](https://webpack.js.org/concepts/)\n- [Rollup documentation](https://rollupjs.org/guide/en/)\n- [Parcel documentation](https://parceljs.org/getting-started/webapp/)\n- [MDN Web Docs: JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-a-module-bundler/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-benefits-of-using-a-module-bundler\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Modules\"\n}\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-a-module-bundler/zh-CN.mdx",
    "content": "---\ntitle: 使用模块打包器的好处是什么？\n---\n\n## TL;DR\n\n使用 Webpack、Rollup 或 Parcel 等模块打包器有助于管理依赖关系、优化性能并改进开发工作流程。它将多个 JavaScript 文件合并成一个或几个文件，从而减少 HTTP 请求的数量，并且可以包含代码拆分、tree shaking 和热模块替换等功能。\n\n***\n\n## 使用模块打包器的优点\n\n### 依赖管理\n\n模块打包器通过允许您以清晰和有组织的方式导入和导出模块来帮助管理依赖关系。这使得维护和理解代码库更容易。\n\n```js\n// Importing a module\nimport { myFunction } from './myModule.js';\n\n// Using the imported function\nmyFunction();\n```\n\n### 性能优化\n\n模块打包器可以通过减少 HTTP 请求的数量来优化性能。它们将多个 JavaScript 文件合并成一个或几个文件，这可以显著提高加载时间。\n\n### 代码拆分\n\n代码拆分允许您将代码拆分成更小的块，这些块可以按需加载。这可以通过仅加载必要的代码来改善应用程序的初始加载时间。\n\n```js\n// Example of dynamic import for code splitting\nimport('./myModule.js').then((module) => {\n  module.myFunction();\n});\n```\n\n### Tree shaking\n\nTree shaking 是一项从最终 bundle 中删除未使用的代码的功能。这有助于减小 bundle 大小并提高性能。\n\n```js\n// Only the used function will be included in the final bundle\nimport { usedFunction } from './myModule.js';\nusedFunction();\n```\n\n### 热模块替换\n\n热模块替换 (HMR) 允许您实时更新模块，而无需刷新整个页面。这可以通过提供即时反馈来显着加快开发过程。\n\n```js\nif (module.hot) {\n  module.hot.accept('./myModule.js', function () {\n    // Handle the updated module\n    const updatedModule = require('./myModule.js');\n    updatedModule.myFunction();\n  });\n}\n```\n\n### 资源管理\n\n模块打包器还可以处理 CSS、图像和字体等其他资源。这允许您将这些资源直接导入到 JavaScript 文件中，从而更易于管理和优化它们。\n\n```js\n// Importing a CSS file\nimport './styles.css';\n\n// Importing an image\nimport myImage from './image.png';\n```\n\n## 延伸阅读\n\n* [Webpack documentation](https://webpack.js.org/concepts/)\n* [Rollup documentation](https://rollupjs.org/guide/en/)\n* [Parcel documentation](https://parceljs.org/getting-started/webapp/)\n* [MDN Web Docs: JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-currying-and-partial-application/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"7525721e\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"29e76d6b\",\n        \"2a7816d0\",\n        \"287ee5dc\",\n        \"1743fc64\",\n        \"be81b126\",\n        \"6fb11d1f\",\n        \"a040305\",\n        \"748ffe75\",\n        \"fba98502\",\n        \"5fd903ca\",\n        \"391c5082\",\n        \"6fb11d1f\",\n        \"9e8ad82d\",\n        \"748ffe75\",\n        \"213b2408\",\n        \"1f4770e5\",\n        \"f8b92363\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"29e76d6b\",\n        \"2a7816d0\",\n        \"287ee5dc\",\n        \"1743fc64\",\n        \"be81b126\",\n        \"6fb11d1f\",\n        \"a040305\",\n        \"748ffe75\",\n        \"fba98502\",\n        \"5fd903ca\",\n        \"391c5082\",\n        \"6fb11d1f\",\n        \"9e8ad82d\",\n        \"748ffe75\",\n        \"213b2408\",\n        \"1f4770e5\",\n        \"f8b92363\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-currying-and-partial-application/en-US.mdx",
    "content": "---\ntitle: What are the benefits of using currying and partial application?\n---\n\n## TL;DR\n\nCurrying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. This allows for more flexible and reusable code. Partial application, on the other hand, allows you to fix a few arguments of a function and generate a new function. Both techniques help in creating more modular and maintainable code.\n\n---\n\n## Benefits of using currying and partial application\n\n### Currying\n\nCurrying is a technique where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument. This can lead to more flexible and reusable code.\n\n#### Benefits\n\n- **Function reusability**: Currying allows you to create specialized functions from general ones by fixing some arguments.\n- **Code readability**: It can make the code more readable and expressive by breaking down complex functions into simpler ones.\n- **Functional programming**: Currying is a core concept in functional programming, which can lead to more predictable and testable code.\n\n#### Example\n\n```js live\nfunction add(a) {\n  return function (b) {\n    return a + b;\n  };\n}\n\nconst addFive = add(5);\nconsole.log(addFive(3)); // Output: 8\n```\n\n### Partial application\n\nPartial application is a technique where you fix a few arguments of a function and generate a new function. This can be useful for creating more specific functions from general ones.\n\n#### Benefits\n\n- **Code reuse**: Like currying, partial application allows you to create specialized functions from general ones.\n- **Improved readability**: It can make the code more readable by reducing the number of arguments needed when calling a function.\n- **Simplified function calls**: By pre-filling some arguments, you can simplify the function calls in your code.\n\n#### Example\n\n```js live\nfunction multiply(a, b) {\n  return a * b;\n}\n\nconst double = multiply.bind(null, 2);\nconsole.log(double(5)); // Output: 10\n```\n\n## Further reading\n\n- [Currying in JavaScript](https://javascript.info/currying-partials)\n- [Partial application in JavaScript](https://medium.com/javascript-scene/curry-and-function-composition-2c208d774983)\n- [Functional programming concepts](https://www.freecodecamp.org/news/functional-programming-in-js-with-practical-examples-part-1-87c2b0dbc276/)\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-currying-and-partial-application/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-benefits-of-using-currying-and-partial-application\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"closure\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Currying & Partial Application\"\n}\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-currying-and-partial-application/zh-CN.mdx",
    "content": "---\ntitle: 使用柯里化和部分应用的益处是什么？\n---\n\n## 总结\n\n柯里化将具有多个参数的函数转换为一系列函数，每个函数只接受一个参数。这使得代码更灵活、更可重用。另一方面，部分应用允许你固定函数的几个参数并生成一个新函数。这两种技术都有助于创建更模块化和可维护的代码。\n\n***\n\n## 使用柯里化和部分应用的益处\n\n### 柯里化\n\n柯里化是一种将具有多个参数的函数转换为一系列函数的技术，每个函数只接受一个参数。这可以使代码更灵活、更可重用。\n\n#### 优点\n\n* **函数可重用性**：柯里化允许你通过固定一些参数来从通用函数创建专用函数。\n* **代码可读性**：它可以通过将复杂函数分解为更简单的函数来使代码更具可读性和表现力。\n* **函数式编程**：柯里化是函数式编程的核心概念，这可以使代码更可预测和可测试。\n\n#### 示例\n\n```js live\nfunction add(a) {\n  return function (b) {\n    return a + b;\n  };\n}\n\nconst addFive = add(5);\nconsole.log(addFive(3)); // Output: 8\n```\n\n### 部分应用\n\n部分应用是一种固定函数的几个参数并生成一个新函数的技术。这对于从通用函数创建更具体的函数很有用。\n\n#### 优点\n\n* **代码重用**：与柯里化一样，部分应用允许你从通用函数创建专用函数。\n* **提高可读性**：通过减少调用函数时所需的参数数量，可以使代码更具可读性。\n* **简化函数调用**：通过预先填充一些参数，你可以简化代码中的函数调用。\n\n#### 示例\n\n```js live\nfunction multiply(a, b) {\n  return a * b;\n}\n\nconst double = multiply.bind(null, 2);\nconsole.log(double(5)); // Output: 10\n```\n\n## 延伸阅读\n\n* [JavaScript 中的柯里化](https://javascript.info/currying-partials)\n* [JavaScript 中的部分应用](https://medium.com/javascript-scene/curry-and-function-composition-2c208d774983)\n* [函数式编程概念](https://www.freecodecamp.org/news/functional-programming-in-js-with-practical-examples-part-1-87c2b0dbc276/)\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"7a249fd\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"d03c0acc\",\n        \"3e05b35d\",\n        \"8522ffad\",\n        \"624f4ed0\",\n        \"2a7816d0\",\n        \"e2d11b63\",\n        \"688c7858\",\n        \"89a01056\",\n        \"839e2fa6\",\n        \"48273238\",\n        \"e5536829\",\n        \"a4bb832d\",\n        \"6d26b995\",\n        \"e5e5f5a2\",\n        \"fefcfbf2\",\n        \"6cc2bb6d\",\n        \"59e7ef1b\",\n        \"13e24ce2\",\n        \"771a4fc5\",\n        \"8ba9f8b9\",\n        \"abcbfc61\",\n        \"d328bba9\",\n        \"fbf393c9\",\n        \"523b8f46\",\n        \"e34cf1b4\",\n        \"1205369c\",\n        \"7de054db\",\n        \"6ab03e6d\",\n        \"76e77f54\",\n        \"ecd1760a\",\n        \"2993b77e\",\n        \"ee39f737\",\n        \"a8e0d79\",\n        \"2f477587\",\n        \"60999da7\",\n        \"3d54fd1b\",\n        \"ac6a2075\",\n        \"ee9c1eea\",\n        \"976520fa\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d03c0acc\",\n        \"3e05b35d\",\n        \"8522ffad\",\n        \"624f4ed0\",\n        \"2a7816d0\",\n        \"e2d11b63\",\n        \"688c7858\",\n        \"89a01056\",\n        \"839e2fa6\",\n        \"48273238\",\n        \"e5536829\",\n        \"a4bb832d\",\n        \"6d26b995\",\n        \"e5e5f5a2\",\n        \"fefcfbf2\",\n        \"6cc2bb6d\",\n        \"59e7ef1b\",\n        \"13e24ce2\",\n        \"771a4fc5\",\n        \"8ba9f8b9\",\n        \"abcbfc61\",\n        \"d328bba9\",\n        \"fbf393c9\",\n        \"523b8f46\",\n        \"e34cf1b4\",\n        \"1205369c\",\n        \"7de054db\",\n        \"6ab03e6d\",\n        \"76e77f54\",\n        \"ecd1760a\",\n        \"2993b77e\",\n        \"ee39f737\",\n        \"a8e0d79\",\n        \"2f477587\",\n        \"60999da7\",\n        \"3d54fd1b\",\n        \"ac6a2075\",\n        \"ee9c1eea\",\n        \"976520fa\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/en-US.mdx",
    "content": "---\ntitle: What are the benefits of using spread syntax in JavaScript and how is it different from rest syntax?\n---\n\n## TL;DR\n\n**Spread syntax** (`...`) allows an iterable (like an array or string) to be expanded into individual elements. This is often used as a convenient and modern way to create new arrays or objects by combining existing ones.\n\n| Operation      | Traditional                     | Spread                 |\n| -------------- | ------------------------------- | ---------------------- |\n| Array cloning  | `arr.slice()`                   | `[...arr]`             |\n| Array merging  | `arr1.concat(arr2)`             | `[...arr1, ...arr2]`   |\n| Object cloning | `Object.assign({}, obj)`        | `{ ...obj }`           |\n| Object merging | `Object.assign({}, obj1, obj2)` | `{ ...obj1, ...obj2 }` |\n\n**Rest syntax** is the opposite of what spread syntax does. It collects a variable number of arguments into an array. This is often used in function parameters to handle a dynamic number of arguments.\n\n```js live\n// Using rest syntax in a function\nfunction sum(...numbers) {\n  return numbers.reduce((total, num) => total + num, 0);\n}\n\nconsole.log(sum(1, 2, 3)); // Output: 6\n```\n\n---\n\n## Spread syntax\n\nES2015's spread syntax is very useful when coding in a functional paradigm as we can easily create copies of / merge arrays or objects without resorting to `Object.create`, `Object.assign`, `Array.prototype.slice`, or a library function. This language feature is used often in Redux and RxJS projects.\n\n### Copying arrays/objects\n\nThe spread syntax provides a concise way to create copies of arrays or objects without modifying the originals. This is useful for creating immutable data structures. However do note that arrays copied via the spread operator are shallowly-copied.\n\n```js live\n// Copying arrays\nconst array = [1, 2, 3];\nconst newArray = [...array];\nconsole.log(newArray); // Output: [1, 2, 3]\n\n// Copying objects\nconst person = { name: 'John', age: 30 };\nconst newObj = { ...person, city: 'New York' };\nconsole.log(newObj); // Output: { name: 'John', age: 30, city: 'New York' }\n```\n\n### Merging arrays/objects\n\nThe spread syntax allows you to merge arrays or objects by spreading their elements/properties into a new array or object.\n\n```js live\n// Merging arrays\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\nconst mergedArray = [...arr1, ...arr2];\nconsole.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]\n\n// Merging objects\nconst obj1 = {\n  foo: 'bar',\n};\n\nconst obj2 = {\n  qux: 'baz',\n};\n\nconst mergedObj = { ...obj1, ...obj2 };\nconsole.log(mergedObj); // Output: { foo: \"bar\", qux: \"baz\" }\n```\n\n### Passing arguments to functions\n\nUse the spread syntax to pass an array of values as individual arguments to a function, avoiding the need for `apply()`.\n\n```js live\nconst numbers = [1, 2, 3];\nconst max = Math.max(...numbers); // Same as Math.max(1, 2, 3)\nconsole.log(max); // Output: 3\n```\n\n### Array vs object spreads\n\nOnly iterable values like `Array`s and `String`s can be spread in an array. Trying to spread non-iterables will result in a `TypeError`.\n\nSpreading object into array:\n\n```js live\nconst person = {\n  name: 'Todd',\n  age: 29,\n};\nconst array = [...person]; // Error: Uncaught TypeError: person is not iterable\n```\n\nOn the other hand, arrays can be spread into objects.\n\n```js live\nconst array = [1, 2, 3];\nconst obj = { ...array };\nconsole.log(obj); // { 0: 1, 1: 2, 2: 3 }\n```\n\n## Rest syntax\n\nThe rest syntax (`...`) in JavaScript allows you to represent an indefinite number of elements as an array or object. It is like an inverse of the spread syntax, taking data and stuffing it into an array rather than unpacking an array of data, and it works in function arguments, as well as in array and object destructuring assignments.\n\n### Rest parameters in functions\n\nThe rest syntax can be used in function parameters to collect all remaining arguments into an array. This is particularly useful when you don't know how many arguments will be passed to the function.\n\n```js live\nfunction addFiveToABunchOfNumbers(...numbers) {\n  return numbers.map((x) => x + 5);\n}\n\nconst result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10);\nconsole.log(result); // Output: [9, 10, 11, 12, 13, 14, 15]\n```\n\nProvides a cleaner syntax than using the `arguments` object, which is unsupported for arrow functions and represents **all** arguments whereas the usage of the rest syntax below allows `remaining` to represent the 3rd argument and beyond.\n\n```js live\nconst [first, second, ...remaining] = [1, 2, 3, 4, 5];\nconsole.log(first); // Output: 1\nconsole.log(second); // Output: 2\nconsole.log(remaining); // Output: [3, 4, 5]\n```\n\nNote that the rest parameters must be at the end. The rest parameters gather all remaining arguments, so the following does not make sense and causes an error:\n\n```js live\nfunction addFiveToABunchOfNumbers(arg1, ...numbers, arg2) {\n  // Error: Rest parameter must be last formal parameter.\n}\n```\n\n### Array destructuring\n\nThe rest syntax can be used in array destructuring to collect the remaining elements into a new array.\n\n```js live\nconst [a, b, ...rest] = [1, 2, 3, 4];\nconsole.log(a); // Output: 1\nconsole.log(b); // Output: 2\nconsole.log(rest); // Output: [3, 4]\n```\n\n### Object destructuring\n\nThe rest syntax can be used in object destructuring to collect the remaining properties into a new object.\n\n```js live\nconst { e, f, ...others } = {\n  e: 1,\n  f: 2,\n  g: 3,\n  h: 4,\n};\nconsole.log(e); // Output: 1\nconsole.log(f); // Output: 2\nconsole.log(others); // Output: { g: 3, h: 4 }\n```\n\n## Further Reading\n\n- [Spread syntax | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n- [Rest parameters | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters)\n- [Rest parameters and spread syntax | JavaScript.info](https://javascript.info/rest-parameters-spread)\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 370,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/pt-BR.mdx",
    "content": "---\ntitle: Quais são os benefícios de usar a sintaxe de spread e como ela é diferente da sintaxe de rest?\n---\n\nA sintaxe spread do ES2015 é muito útil quando programando em um paradigma funcional, pois podemos facilmente criar cópias de arrays ou objetos sem recorrer a `Object.create`, `slice`, ou uma função de biblioteca. Esse recurso de linguagem é frequentemente utilizado em projetos Redux e RxJS.\n\n```js\nfunction putDookieInAnyArray(arr) {\n  return [...arr, 'dookie'];\n}\n\nconst result = putDookieInAnyArray(['I', 'really', \"don't\", 'like']); // [\"I\", \"really\", \"don't\", \"like\", \"dookie\"]\n\nconst person = {\n  name: 'Todd',\n  age: 29,\n};\n\nconst copyOfTodd = { ...person };\n```\n\nA sintaxe rest do ES2015 oferece uma maneira mais fácil de incluir um número arbitrário de argumentos para serem passados para uma função. É como uma inversão da sintaxe spread, pegando dados e colocando-os em um array em vez de desempacotar um array de dados, e funciona em argumentos de função, bem como em atribuições de desconstrução de arrays e objetos.\n\n```js\nfunction addFiveToABunchOfNumbers(...numbers) {\n  return numbers.map((x) => x + 5);\n}\n\nconst result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10); // [9, 10, 11, 12, 13, 14, 15]\n\nconst [a, b, ...rest] = [1, 2, 3, 4]; // a: 1, b: 2, rest: [3, 4]\n\nconst { e, f, ...others } = {\n  e: 1,\n  f: 2,\n  g: 3,\n  h: 4,\n}; // e: 1, f: 2, others: { g: 3, h: 4 }\n```\n"
  },
  {
    "path": "questions/what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中使用展开语法有什么好处？它与 rest 语法有何不同？\n---\n\n## TL;DR\n\n**展开语法** (`...`) 允许将可迭代对象（如数组或字符串）扩展为单个元素。这通常被用作一种方便且现代的方式，通过组合现有数组或对象来创建新的数组或对象。\n\n| 操作 | 传统方式 | 展开语法 |\n| -------------- | ------------------------------- | ---------------------- |\n| 数组克隆 | `arr.slice()` | `[...arr]` |\n| 数组合并 | `arr1.concat(arr2)` | `[...arr1, ...arr2]` |\n| 对象克隆 | `Object.assign({}, obj)` | `{ ...obj }` |\n| 对象合并 | `Object.assign({}, obj1, obj2)` | `{ ...obj1, ...obj2 }` |\n\n**Rest 语法**与展开语法的作用相反。它将可变数量的参数收集到一个数组中。这通常用于函数参数中，以处理动态数量的参数。\n\n```js live\n// Using rest syntax in a function\nfunction sum(...numbers) {\n  return numbers.reduce((total, num) => total + num, 0);\n}\n\nconsole.log(sum(1, 2, 3)); // Output: 6\n```\n\n***\n\n## 展开语法\n\nES2015 的展开语法在函数式编程范式中非常有用，因为我们可以轻松地创建数组或对象的副本/合并，而无需使用 `Object.create`、`Object.assign`、`Array.prototype.slice` 或库函数。此语言特性经常用于 Redux 和 RxJS 项目中。\n\n### 复制数组/对象\n\n展开语法提供了一种简洁的方式来创建数组或对象的副本，而无需修改原始数组或对象。这对于创建不可变数据结构很有用。但是请注意，通过展开运算符复制的数组是浅拷贝的。\n\n```js live\n// Copying arrays\nconst array = [1, 2, 3];\nconst newArray = [...array];\nconsole.log(newArray); // Output: [1, 2, 3]\n\n// Copying objects\nconst person = { name: 'John', age: 30 };\nconst newObj = { ...person, city: 'New York' };\nconsole.log(newObj); // Output: { name: 'John', age: 30, city: 'New York' }\n```\n\n### 合并数组/对象\n\n展开语法允许您通过将其元素/属性展开到新的数组或对象中来合并数组或对象。\n\n```js live\n// Merging arrays\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\nconst mergedArray = [...arr1, ...arr2];\nconsole.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]\n\n// Merging objects\nconst obj1 = {\n  foo: 'bar',\n};\n\nconst obj2 = {\n  qux: 'baz',\n};\n\nconst mergedObj = { ...obj1, ...obj2 };\nconsole.log(mergedObj); // Output: { foo: \"bar\", qux: \"baz\" }\n```\n\n### 将参数传递给函数\n\n使用展开语法将值数组作为单个参数传递给函数，避免了使用 `apply()` 的需要。\n\n```js live\nconst numbers = [1, 2, 3];\nconst max = Math.max(...numbers); // Same as Math.max(1, 2, 3)\nconsole.log(max); // Output: 3\n```\n\n### 数组与对象展开\n\n只有可迭代的值（如 `Array` 和 `String`）才可以在数组中展开。尝试展开不可迭代的值将导致 `TypeError`。\n\n将对象展开到数组中：\n\n```js live\nconst person = {\n  name: 'Todd',\n  age: 29,\n};\nconst array = [...person]; // Error: Uncaught TypeError: person is not iterable\n```\n\n另一方面，数组可以展开到对象中。\n\n```js live\nconst array = [1, 2, 3];\nconst obj = { ...array };\nconsole.log(obj); // { 0: 1, 1: 2, 2: 3 }\n```\n\n## Rest 语法\n\nJavaScript 中的 rest 语法 (`...`) 允许你将不定数量的元素表示为数组或对象。它就像展开语法的逆向操作，获取数据并将其放入数组中，而不是解包数组中的数据，它适用于函数参数以及数组和对象解构赋值。\n\n### 函数中的 Rest 参数\n\nRest 语法可用于函数参数中，将所有剩余的参数收集到一个数组中。当你不知道将向函数传递多少个参数时，这特别有用。\n\n```js live\nfunction addFiveToABunchOfNumbers(...numbers) {\n  return numbers.map((x) => x + 5);\n}\n\nconst result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10);\nconsole.log(result); // Output: [9, 10, 11, 12, 13, 14, 15]\n```\n\n与使用 `arguments` 对象相比，它提供了更简洁的语法，`arguments` 对象在箭头函数中不受支持，并且表示 **所有** 参数，而下面 rest 语法的用法允许 `remaining` 表示第三个参数及之后的参数。\n\n```js live\nconst [first, second, ...remaining] = [1, 2, 3, 4, 5];\nconsole.log(first); // Output: 1\nconsole.log(second); // Output: 2\nconsole.log(remaining); // Output: [3, 4, 5]\n```\n\n请注意，rest 参数必须位于末尾。rest 参数会收集所有剩余的参数，因此以下操作没有意义，并且会导致错误：\n\n```js live\nfunction addFiveToABunchOfNumbers(arg1, ...numbers, arg2) {\n  // Error: Rest parameter must be last formal parameter.\n}\n```\n\n### 数组解构\n\nRest 语法可用于数组解构，将剩余的元素收集到一个新数组中。\n\n```js live\nconst [a, b, ...rest] = [1, 2, 3, 4];\nconsole.log(a); // Output: 1\nconsole.log(b); // Output: 2\nconsole.log(rest); // Output: [3, 4]\n```\n\n### 对象解构\n\nRest 语法可用于对象解构，将剩余的属性收集到一个新对象中。\n\n```js live\nconst { e, f, ...others } = {\n  e: 1,\n  f: 2,\n  g: 3,\n  h: 4,\n};\nconsole.log(e); // Output: 1\nconsole.log(f); // Output: 2\nconsole.log(others); // Output: { g: 3, h: 4 }\n```\n\n## 延伸阅读\n\n* [展开语法 | MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n* [Rest 参数 | MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/rest_parameters)\n* [Rest 参数和展开语法 | JavaScript.info](https://zh.javascript.info/rest-parameters-spread)\n"
  },
  {
    "path": "questions/what-are-the-common-pitfalls-of-using-the-this-keyword/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"e4315140\",\n        \"2a7816d0\",\n        \"71f47a3\",\n        \"f118ed33\",\n        \"3052ef2d\",\n        \"5a9818a9\",\n        \"e146225d\",\n        \"91cf93fe\",\n        \"e2f67879\",\n        \"a91f3d72\",\n        \"610d6503\",\n        \"b4e2d4e\",\n        \"56eb56b7\",\n        \"af6b2bfc\",\n        \"366ce736\",\n        \"db9220f6\",\n        \"6bb7178a\",\n        \"477a54e8\",\n        \"bba4152b\",\n        \"e9e72c17\",\n        \"a0670e23\",\n        \"cff4876d\",\n        \"690b751\",\n        \"33fe2392\",\n        \"9b0bf70b\",\n        \"1f4770e5\",\n        \"f49c1a72\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"e4315140\",\n        \"2a7816d0\",\n        \"71f47a3\",\n        \"f118ed33\",\n        \"3052ef2d\",\n        \"5a9818a9\",\n        \"e146225d\",\n        \"91cf93fe\",\n        \"e2f67879\",\n        \"a91f3d72\",\n        \"610d6503\",\n        \"b4e2d4e\",\n        \"56eb56b7\",\n        \"af6b2bfc\",\n        \"366ce736\",\n        \"db9220f6\",\n        \"6bb7178a\",\n        \"477a54e8\",\n        \"bba4152b\",\n        \"e9e72c17\",\n        \"a0670e23\",\n        \"cff4876d\",\n        \"690b751\",\n        \"33fe2392\",\n        \"9b0bf70b\",\n        \"1f4770e5\",\n        \"f49c1a72\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"71e94b5\"\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-common-pitfalls-of-using-the-this-keyword/en-US.mdx",
    "content": "---\ntitle: What are the common pitfalls of using the `this` keyword?\n---\n\n## TL;DR\n\nThe `this` keyword in JavaScript can be tricky because its value depends on how a function is called. Common pitfalls include losing the context of `this` when passing methods as callbacks, using `this` in nested functions, and misunderstanding `this` in arrow functions. To avoid these issues, you can use `.bind()`, arrow functions, or store the context in a variable.\n\n---\n\n## Common pitfalls of using the `this` keyword\n\n### Losing context in callbacks\n\nWhen you pass a method as a callback, the context of `this` can be lost. For example:\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: function () {\n    return this.value;\n  },\n};\n\nconst getValue = obj.getValue;\nconsole.log(getValue()); // undefined\n```\n\nIn this case, `this` inside `getValue` is not bound to `obj`.\n\n### Using `this` in nested functions\n\nIn nested functions, `this` does not refer to the outer function's context:\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: function () {\n    function innerFunction() {\n      return this.value;\n    }\n    return innerFunction();\n  },\n};\n\nconsole.log(obj.getValue()); // undefined\n```\n\nHere, `this` inside `innerFunction` refers to the global object, not `obj`.\n\n### Misunderstanding `this` in arrow functions\n\nArrow functions do not have their own `this` context; they inherit it from the enclosing scope:\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: () => {\n    return this.value;\n  },\n};\n\nconsole.log(obj.getValue()); // undefined\n```\n\nIn this example, `this` inside the arrow function refers to the global object, not `obj`.\n\n### Solutions\n\n#### Using `.bind()`\n\nYou can use `.bind()` to explicitly set the context of `this`:\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: function () {\n    return this.value;\n  },\n};\n\nconst getValue = obj.getValue.bind(obj);\nconsole.log(getValue()); // 42\n```\n\n#### Using arrow functions\n\nArrow functions inherit `this` from the enclosing scope, which can be useful:\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: function () {\n    const innerFunction = () => {\n      return this.value;\n    };\n    return innerFunction();\n  },\n};\n\nconsole.log(obj.getValue()); // 42\n```\n\n#### Storing context in a variable\n\nYou can store the context in a variable to maintain it in nested functions:\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: function () {\n    const self = this;\n    function innerFunction() {\n      return self.value;\n    }\n    return innerFunction();\n  },\n};\n\nconsole.log(obj.getValue()); // 42\n```\n\n## Further reading\n\n- [MDN Web Docs: `this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)\n- [JavaScript.info: Object methods, \"this\"](https://javascript.info/object-methods)\n- [Eloquent JavaScript: `this`](https://eloquentjavascript.net/03_functions.html#h_jxlm9L8T4l)\n"
  },
  {
    "path": "questions/what-are-the-common-pitfalls-of-using-the-this-keyword/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-common-pitfalls-of-using-the-this-keyword\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"This Keyword\"\n}\n"
  },
  {
    "path": "questions/what-are-the-common-pitfalls-of-using-the-this-keyword/zh-CN.mdx",
    "content": "---\ntitle: 使用 `this` 关键字的常见陷阱是什么？\n---\n\n## TL;DR\n\nJavaScript 中的 `this` 关键字可能很棘手，因为它的值取决于函数的调用方式。常见的陷阱包括将方法作为回调传递时丢失 `this` 的上下文，在嵌套函数中使用 `this`，以及误解箭头函数中的 `this`。为了避免这些问题，您可以使用 `.bind()`、箭头函数或将上下文存储在变量中。\n\n***\n\n## 使用 `this` 关键字的常见陷阱\n\n### 在回调中丢失上下文\n\n当您将方法作为回调传递时，`this` 的上下文可能会丢失。例如：\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: function () {\n    return this.value;\n  },\n};\n\nconst getValue = obj.getValue;\nconsole.log(getValue()); // undefined\n```\n\n在这种情况下，`getValue` 内部的 `this` 没有绑定到 `obj`。\n\n### 在嵌套函数中使用 `this`\n\n在嵌套函数中，`this` 不指向外部函数的上下文：\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: function () {\n    function innerFunction() {\n      return this.value;\n    }\n    return innerFunction();\n  },\n};\n\nconsole.log(obj.getValue()); // undefined\n```\n\n在这里，`innerFunction` 内部的 `this` 指向全局对象，而不是 `obj`。\n\n### 误解箭头函数中的 `this`\n\n箭头函数没有自己的 `this` 上下文；它们从封闭的范围继承它：\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: () => {\n    return this.value;\n  },\n};\n\nconsole.log(obj.getValue()); // undefined\n```\n\n在这个例子中，箭头函数内部的 `this` 指向全局对象，而不是 `obj`。\n\n### 解决方案\n\n#### 使用 `.bind()`\n\n您可以使用 `.bind()` 显式设置 `this` 的上下文：\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: function () {\n    return this.value;\n  },\n};\n\nconst getValue = obj.getValue.bind(obj);\nconsole.log(getValue()); // 42\n```\n\n#### 使用箭头函数\n\n箭头函数从封闭的范围继承 `this`，这很有用：\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: function () {\n    const innerFunction = () => {\n      return this.value;\n    };\n    return innerFunction();\n  },\n};\n\nconsole.log(obj.getValue()); // 42\n```\n\n#### 将上下文存储在变量中\n\n您可以将上下文存储在变量中，以在嵌套函数中维护它：\n\n```js live\nconst obj = {\n  value: 42,\n  getValue: function () {\n    const self = this;\n    function innerFunction() {\n      return self.value;\n    }\n    return innerFunction();\n  },\n};\n\nconsole.log(obj.getValue()); // 42\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: `this`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this)\n* [JavaScript.info: Object methods, \"this\"](https://zh-cn.javascript.info/object-methods)\n* [Eloquent JavaScript: `this`](https://eloquentjavascript.net/03_functions.html#h_jxlm9L8T4l)\n"
  },
  {
    "path": "questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"f81c9361\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"95a6951c\",\n        \"281d57a3\",\n        \"797a0534\",\n        \"64b4e88c\",\n        \"2fea9e4b\",\n        \"bf96ba57\",\n        \"74770051\",\n        \"2a7816d0\",\n        \"9032ea75\",\n        \"ba3c5f84\",\n        \"44973fdf\",\n        \"53bc3236\",\n        \"d53971f4\",\n        \"58ee670a\",\n        \"ee80ee2e\",\n        \"f26b0b7a\",\n        \"9ffb161a\",\n        \"140088c7\",\n        \"516563ba\",\n        \"a2c43d1\",\n        \"dae7e089\",\n        \"2347bc75\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"95a6951c\",\n        \"281d57a3\",\n        \"797a0534\",\n        \"64b4e88c\",\n        \"2fea9e4b\",\n        \"bf96ba57\",\n        \"74770051\",\n        \"2a7816d0\",\n        \"9032ea75\",\n        \"ba3c5f84\",\n        \"44973fdf\",\n        \"53bc3236\",\n        \"d53971f4\",\n        \"58ee670a\",\n        \"ee80ee2e\",\n        \"f26b0b7a\",\n        \"9ffb161a\",\n        \"140088c7\",\n        \"516563ba\",\n        \"a2c43d1\",\n        \"dae7e089\",\n        \"2347bc75\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/en-US.mdx",
    "content": "---\ntitle: What are the differences between JavaScript ES2015 classes and ES5 function constructors?\n---\n\n## TL;DR\n\nES2015 introduces a new way of creating classes, which provides a more intuitive and concise way to define and work with objects and inheritance compared to the ES5 function constructor syntax. Here's an example of each:\n\n```js\n// ES5 function constructor\nfunction Person(name) {\n  this.name = name;\n}\n\n// ES2015 Class\nclass Person {\n  constructor(name) {\n    this.name = name;\n  }\n}\n```\n\nFor simple constructors, they look pretty similar. The main difference in the constructor comes when using inheritance. If we want to create a `Student` class that subclasses `Person` and add a `studentId` field, this is what we have to do.\n\n```js live\n// ES5 inheritance\n// Superclass\nfunction Person1(name) {\n  this.name = name;\n}\n\n// Subclass\nfunction Student1(name, studentId) {\n  // Call constructor of superclass to initialize superclass-derived members.\n  Person1.call(this, name);\n\n  // Initialize subclass's own members.\n  this.studentId = studentId;\n}\nStudent1.prototype = Object.create(Person1.prototype);\nStudent1.prototype.constructor = Student1;\n\nconst student1 = new Student1('John', 1234);\nconsole.log(student1.name, student1.studentId); // \"John\" 1234\n\n// ES2015 inheritance\n// Superclass\nclass Person2 {\n  constructor(name) {\n    this.name = name;\n  }\n}\n\n// Subclass\nclass Student2 extends Person2 {\n  constructor(name, studentId) {\n    super(name);\n    this.studentId = studentId;\n  }\n}\n\nconst student2 = new Student2('Alice', 5678);\nconsole.log(student2.name, student2.studentId); // \"Alice\" 5678\n```\n\nIt's much more verbose to use inheritance in ES5 and the ES2015 version is easier to understand and remember.\n\n**Comparison of ES5 function constructors vs ES2015 classes**\n\n| Feature | ES5 Function Constructor | ES2015 Class |\n| --- | --- | --- |\n| Syntax | Uses function constructors and prototypes | Uses `class` keyword |\n| Constructor | Function with properties assigned using `this` | `constructor` method inside the class |\n| Method Definition | Defined on the prototype | Defined inside the class body |\n| Static Methods | Added directly to the constructor function | Defined using the `static` keyword |\n| Inheritance | Uses `Object.create()` and manually sets prototype chain | Uses `extends` keyword and `super` function |\n| Readability | Less intuitive and more verbose | More concise and intuitive |\n\n---\n\n## ES5 function constructor vs ES2015 classes\n\nES5 function constructors and ES2015 classes are two different ways of defining classes in JavaScript. They both serve the same purpose, but they have different syntax and behavior.\n\n### ES5 function constructors\n\nIn ES5, you define a class-like structure using a function constructor and prototypes. Here's an example:\n\n```js live\n// ES5 function constructor\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\nPerson.prototype.greet = function () {\n  console.log(\n    'Hello, my name is ' + this.name + ' and I am ' + this.age + ' years old.',\n  );\n};\n\n// Creating an instance\nvar person1 = new Person('John', 30);\nperson1.greet(); // Hello, my name is John and I am 30 years old.\n```\n\n### ES2015 classes\n\nES2015 introduced the `class` syntax, which simplifies the definition of classes and supports more features such as static methods and subclassing. Here's the same example using ES2015:\n\n```js live\n// ES2015 Class\nclass Person {\n  constructor(name, age) {\n    this.name = name;\n    this.age = age;\n  }\n\n  greet() {\n    console.log(\n      `Hello, my name is ${this.name} and I am ${this.age} years old.`,\n    );\n  }\n}\n\n// Creating an instance\nconst person1 = new Person('John', 30);\nperson1.greet(); // Hello, my name is John and I am 30 years old.\n```\n\n### Key Differences\n\n1. **Syntax and Readability**:\n\n   - **ES5**: Uses function constructors and prototypes, which can be less intuitive and harder to read.\n   - **ES2015**: Uses the `class` keyword, making the code more concise and easier to understand.\n\n2. **Static Methods**:\n\n   - **ES5**: Static methods are added directly to the constructor function.\n   - **ES2015**: Static methods are defined within the class using the `static` keyword.\n\n   ```js live\n   // ES5\n   function Person1(name, age) {\n     this.name = name;\n     this.age = age;\n   }\n\n   Person1.sayHi = function () {\n     console.log('Hi from ES5!');\n   };\n\n   Person1.sayHi(); // Hi from ES5!\n\n   // ES2015\n   class Person2 {\n     static sayHi() {\n       console.log('Hi from ES2015!');\n     }\n   }\n   Person2.sayHi(); // Hi from ES2015!\n   ```\n\n3. **Inheritance**\n\n   - **ES5**: Inheritance is achieved using `Object.create()` and manually setting the prototype chain.\n   - **ES2015**: Inheritance is much simpler and more intuitive with the extends keyword.\n\n   ```js live\n   // ES5 Inheritance\n\n   // ES5 function constructor\n   function Person1(name, age) {\n     this.name = name;\n     this.age = age;\n   }\n\n   Person1.prototype.greet = function () {\n     console.log(\n       `Hello, my name is ${this.name} and I am ${this.age} years old.`,\n     );\n   };\n\n   function Student1(name, age, grade) {\n     Person1.call(this, name, age);\n     this.grade = grade;\n   }\n\n   Student1.prototype = Object.create(Person1.prototype);\n   Student1.prototype.constructor = Student1;\n\n   Student1.prototype.study = function () {\n     console.log(this.name + ' is studying.');\n   };\n\n   var student1 = new Student1('John', 22, 'B+');\n   student1.greet(); // Hello, my name is John and I am 22 years old.\n   student1.study(); // John is studying.\n\n   // ES2015 Inheritance\n\n   // ES2015 Class\n   class Person2 {\n     constructor(name, age) {\n       this.name = name;\n       this.age = age;\n     }\n\n     greet() {\n       console.log(\n         `Hello, my name is ${this.name} and I am ${this.age} years old.`,\n       );\n     }\n   }\n\n   class Student2 extends Person2 {\n     constructor(name, age, grade) {\n       super(name, age);\n       this.grade = grade;\n     }\n\n     study() {\n       console.log(`${this.name} is studying.`);\n     }\n   }\n\n   const student2 = new Student2('Alice', 20, 'A');\n   student2.greet(); // Hello, my name is Alice and I am 20 years old.\n   student2.study(); // Alice is studying.\n   ```\n\n4. `super` calls:\n\n   - **ES5**: Manually call the parent constructor function.\n   - **ES2015**: Use the `super` keyword to call the parent class's constructor and methods.\n\n### Conclusion\n\nWhile both ES5 and ES2015 approaches can achieve the same functionality, ES2015 classes provide a clearer and more concise way to define and work with object-oriented constructs in JavaScript, which makes the code easier to write, read, and maintain. If you are working with modern JavaScript, it is generally recommended to use ES2015 classes over ES5 function constructors.\n\n## Resources\n\n- [Classes - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n- [Inheritance- MDN ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#inheritance)\n- [The Secret Life Of Objects](https://eloquentjavascript.net/06_object.html)\n- [ES2015 vs ES5](https://www.educative.io/courses/learn-object-oriented-programming-in-javascript/es2015-vs-es5)\n"
  },
  {
    "path": "questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-differences-between-es6-class-and-es5-function-constructors\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"high\",\n  \"ranking\": 200,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/pt-BR.mdx",
    "content": "---\ntitle: Quais são as diferenças entre a classe ES2015 e os construtores de função ES5?\n---\n\nVamos primeiro olhar o exemplo de cada um deles:\n\n```js\n// Constructor de função ES5\nfunction Person(name) {\n  this.name = name;\n}\n\n// ES2015 Class\nclass Person {\n  constructor(name) {\n    this.name = name;\n  }\n}\n```\n\nPara construtores simples, eles parecem bem semelhantes.\n\nA principal diferença no construtor vem quando se usa herança. Se quisermos criar uma classe `Student` que seja uma subclasse de `Person` e adicionar um campo `studentId`, é isso que devemos fazer além do que foi mostrado acima.\n\n```js\n// Construtor de função ES5\nfunction Student(name, studentId) {\n  // Chamar o construtor da superclasse para inicializar membros derivados da superclasse.\n  Person.call(this, name);\n\n  // Inicializar os próprios membros da subclasse.\n  this.studentId = studentId;\n}\n\nStudent.prototype = Object.create(Person.prototype);\nStudent.prototype.constructor = Student;\n\n// Classe ES2015\nclass Student extends Person {\n  constructor(name, studentId) {\n    super(name);\n    this.studentId = studentId;\n  }\n}\n```\n\nÉ muito mais verboso usar a herança na ES5 e a versão ES2015 é mais fácil de entender e lembrar.\n"
  },
  {
    "path": "questions/what-are-the-differences-between-es6-class-and-es5-function-constructors/zh-CN.mdx",
    "content": "---\ntitle: JavaScript ES2015 类和 ES5 函数构造函数之间有什么区别？\n---\n\n## TL;DR\n\nES2015 引入了一种创建类的新方法，与 ES5 函数构造函数语法相比，它提供了一种更直观、更简洁的方式来定义和使用对象和继承。以下是每个的示例：\n\n```js\n// ES5 function constructor\nfunction Person(name) {\n  this.name = name;\n}\n\n// ES2015 Class\nclass Person {\n  constructor(name) {\n    this.name = name;\n  }\n}\n```\n\n对于简单的构造函数，它们看起来非常相似。构造函数的主要区别在于使用继承时。如果我们想创建一个 `Student` 类，该类是 `Person` 的子类，并添加一个 `studentId` 字段，这就是我们必须做的。\n\n```js live\n// ES5 inheritance\n// Superclass\nfunction Person1(name) {\n  this.name = name;\n}\n\n// Subclass\nfunction Student1(name, studentId) {\n  // Call constructor of superclass to initialize superclass-derived members.\n  Person1.call(this, name);\n\n  // Initialize subclass's own members.\n  this.studentId = studentId;\n}\nStudent1.prototype = Object.create(Person1.prototype);\nStudent1.prototype.constructor = Student1;\n\nconst student1 = new Student1('John', 1234);\nconsole.log(student1.name, student1.studentId); // \"John\" 1234\n\n// ES2015 inheritance\n// Superclass\nclass Person2 {\n  constructor(name) {\n    this.name = name;\n  }\n}\n\n// Subclass\nclass Student2 extends Person2 {\n  constructor(name, studentId) {\n    super(name);\n    this.studentId = studentId;\n  }\n}\n\nconst student2 = new Student2('Alice', 5678);\nconsole.log(student2.name, student2.studentId); // \"Alice\" 5678\n```\n\n在 ES5 中使用继承要冗长得多，而 ES2015 版本更容易理解和记忆。\n\n**ES5 函数构造函数与 ES2015 类的比较**\n\n| 特性 | ES5 函数构造函数 | ES2015 类 |\n| --- | --- | --- |\n| 语法 | 使用函数构造函数和原型 | 使用 `class` 关键字 |\n| 构造函数 | 使用 `this` 分配属性的函数 | 类中的 `constructor` 方法 |\n| 方法定义 | 在原型上定义 | 在类主体内定义 |\n| 静态方法 | 直接添加到构造函数 | 使用 `static` 关键字定义 |\n| 继承 | 使用 `Object.create()` 并手动设置原型链 | 使用 `extends` 关键字和 `super` 函数 |\n| 可读性 | 不太直观，更冗长 | 更简洁直观 |\n\n***\n\n## ES5 函数构造函数 vs ES2015 类\n\nES5 函数构造函数和 ES2015 类是 JavaScript 中定义类的两种不同方式。它们都服务于相同的目的，但它们具有不同的语法和行为。\n\n### ES5 函数构造函数\n\n在 ES5 中，您可以使用函数构造函数和原型定义类似类的结构。这是一个例子：\n\n```js live\n// ES5 function constructor\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n}\n\nPerson.prototype.greet = function () {\n  console.log(\n    'Hello, my name is ' + this.name + ' and I am ' + this.age + ' years old.',\n  );\n};\n\n// Creating an instance\nvar person1 = new Person('John', 30);\nperson1.greet(); // Hello, my name is John and I am 30 years old.\n```\n\n### ES2015 类\n\nES2015 引入了 `class` 语法，它简化了类的定义，并支持更多功能，例如静态方法和子类化。以下是使用 ES2015 的相同示例：\n\n```js live\n// ES2015 Class\nclass Person {\n  constructor(name, age) {\n    this.name = name;\n    this.age = age;\n  }\n\n  greet() {\n    console.log(\n      `Hello, my name is ${this.name} and I am ${this.age} years old.`,\n    );\n  }\n}\n\n// Creating an instance\nconst person1 = new Person('John', 30);\nperson1.greet(); // Hello, my name is John and I am 30 years old.\n```\n\n### 主要区别\n\n1. **语法和可读性**：\n\n   * **ES5**：使用函数构造函数和原型，这不太直观，也更难阅读。\n   * **ES2015**：使用 `class` 关键字，使代码更简洁，更容易理解。\n\n2. **静态方法**：\n\n   * **ES5**：静态方法直接添加到构造函数中。\n   * **ES2015**：静态方法使用 `static` 关键字在类中定义。\n\n   ```js live\n   // ES5\n   function Person1(name, age) {\n     this.name = name;\n     this.age = age;\n   }\n\n   Person1.sayHi = function () {\n     console.log('Hi from ES5!');\n   };\n\n   Person1.sayHi(); // Hi from ES5!\n\n   // ES2015\n   class Person2 {\n     static sayHi() {\n       console.log('Hi from ES2015!');\n     }\n   }\n   Person2.sayHi(); // Hi from ES2015!\n   ```\n\n3. **继承**\n\n   * **ES5**：继承是使用 `Object.create()` 并手动设置原型链来实现的。\n   * **ES2015**：使用 extends 关键字，继承更加简单直观。\n\n   ```js live\n   // ES5 Inheritance\n\n   // ES5 function constructor\n   function Person1(name, age) {\n     this.name = name;\n     this.age = age;\n   }\n\n   Person1.prototype.greet = function () {\n     console.log(\n       `Hello, my name is ${this.name} and I am ${this.age} years old.`,\n     );\n   };\n\n   function Student1(name, age, grade) {\n     Person1.call(this, name, age);\n     this.grade = grade;\n   }\n\n   Student1.prototype = Object.create(Person1.prototype);\n   Student1.prototype.constructor = Student1;\n\n   Student1.prototype.study = function () {\n     console.log(this.name + ' is studying.');\n   };\n\n   var student1 = new Student1('John', 22, 'B+');\n   student1.greet(); // Hello, my name is John and I am 22 years old.\n   student1.study(); // John is studying.\n\n   // ES2015 Inheritance\n\n   // ES2015 Class\n   class Person2 {\n     constructor(name, age) {\n       this.name = name;\n       this.age = age;\n     }\n\n     greet() {\n       console.log(\n         `Hello, my name is ${this.name} and I am ${this.age} years old.`,\n       );\n     }\n   }\n\n   class Student2 extends Person2 {\n     constructor(name, age, grade) {\n       super(name, age);\n       this.grade = grade;\n     }\n\n     study() {\n       console.log(`${this.name} is studying.`);\n     }\n   }\n\n   const student2 = new Student2('Alice', 20, 'A');\n   student2.greet(); // Hello, my name is Alice and I am 20 years old.\n   student2.study(); // Alice is studying.\n   ```\n\n4. `super` 调用：\n\n   * **ES5**：手动调用父构造函数。\n   * **ES2015**：使用 `super` 关键字调用父类的构造函数和方法。\n\n### 结论\n\n虽然 ES5 和 ES2015 方法都可以实现相同的功能，但 ES2015 类提供了一种更清晰、更简洁的方式来定义和使用 JavaScript 中的面向对象结构，这使得代码更容易编写、阅读和维护。 如果您正在使用现代 JavaScript，通常建议使用 ES2015 类而不是 ES5 函数构造函数。\n\n## 资源\n\n* [类 - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n* [继承 - MDN ](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#inheritance)\n* [对象的秘密生活](https://eloquentjavascript.net/06_object.html)\n* [ES2015 vs ES5](https://www.educative.io/courses/learn-object-oriented-programming-in-javascript/es2015-vs-es5)\n"
  },
  {
    "path": "questions/what-are-the-differences-between-map-set-and-weakmap-weakset/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"ce877cfc\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3c2d208a\",\n        \"a456d26e\",\n        \"3cf45eea\",\n        \"a441a125\",\n        \"e2c972f2\",\n        \"3ba2b5f2\",\n        \"89fb2a78\",\n        \"d6cfa9b2\",\n        \"5894272\",\n        \"fbd9ad72\",\n        \"b3156da3\",\n        \"e2211430\",\n        \"e12dbe45\",\n        \"2a7816d0\",\n        \"acdb035\",\n        \"ecb8f1ef\",\n        \"17cea45a\",\n        \"77c6a53e\",\n        \"bdc7d1d6\",\n        \"a714d2d2\",\n        \"3efa8595\",\n        \"d47d82bc\",\n        \"af9a8022\",\n        \"bb4449e4\",\n        \"3eb3598c\",\n        \"1f4770e5\",\n        \"42fc8234\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3c2d208a\",\n        \"a456d26e\",\n        \"3cf45eea\",\n        \"a441a125\",\n        \"e2c972f2\",\n        \"3ba2b5f2\",\n        \"89fb2a78\",\n        \"d6cfa9b2\",\n        \"5894272\",\n        \"fbd9ad72\",\n        \"b3156da3\",\n        \"e2211430\",\n        \"e12dbe45\",\n        \"2a7816d0\",\n        \"acdb035\",\n        \"ecb8f1ef\",\n        \"17cea45a\",\n        \"77c6a53e\",\n        \"bdc7d1d6\",\n        \"a714d2d2\",\n        \"3efa8595\",\n        \"d47d82bc\",\n        \"af9a8022\",\n        \"bb4449e4\",\n        \"3eb3598c\",\n        \"1f4770e5\",\n        \"42fc8234\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-differences-between-map-set-and-weakmap-weakset/en-US.mdx",
    "content": "---\ntitle: What are the differences between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript?\n---\n\n## TL;DR\n\nThe primary difference between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript lies in how they handle keys. Here's a breakdown:\n\n**`Map` vs. `WeakMap`**\n\n`Map`s allows any data type (strings, numbers, objects) as keys. The key-value pairs remain in memory as long as the `Map` object itself is referenced. Thus they are suitable for general-purpose key-value storage where you want to maintain references to both keys and values. Common use cases include storing user data, configuration settings, or relationships between objects.\n\n`WeakMap`s only allows objects as keys. However, these object keys are held weakly. This means the garbage collector can remove them from memory even if the `WeakMap` itself still exists, as long as there are no other references to those objects. `WeakMap`s are ideal for scenarios where you want to associate data with objects without preventing those objects from being garbage collected. This can be useful for things like:\n\n- Caching data based on objects without preventing garbage collection of the objects themselves.\n- Storing private data associated with DOM nodes without affecting their lifecycle.\n\n**`Set` vs. `WeakSet`**\n\nSimilar to `Map`, `Set`s allow any data type as keys. The elements within a `Set` must be unique. `Set`s are useful for storing unique values and checking for membership efficiently. Common use cases include removing duplicates from arrays or keeping track of completed tasks.\n\nOn the other hand, `WeakSet` only allows objects as elements, and these object elements are held weakly, similar to `WeakMap` keys. `WeakSet`s are less commonly used, but applicable when you want a collection of unique objects without affecting their garbage collection. This might be necessary for:\n\n- Tracking DOM nodes that have been interacted with without affecting their memory management.\n- Implementing custom object weak references for specific use cases.\n\n**Here's a table summarizing the key differences:**\n\n| Feature | Map | WeakMap | Set | WeakSet |\n| --- | --- | --- | --- | --- |\n| Key Types | Any data type | Objects (weak references) | Any data type (unique) | Objects (weak references, unique) |\n| Garbage Collection | Keys and values are not garbage collected | Keys can be garbage collected if not referenced elsewhere | Elements are not garbage collected | Elements can be garbage collected if not referenced elsewhere |\n| Use Cases | General-purpose key-value storage | Caching, private DOM node data | Removing duplicates, membership checks | Object weak references, custom use cases |\n\n**Choosing between them**\n\n- Use `Map` and `Set` for most scenarios where you need to store key-value pairs or unique elements and want to maintain references to both the keys/elements and the values.\n- Use `WeakMap` and `WeakSet` cautiously in specific situations where you want to associate data with objects without affecting their garbage collection. Be aware of the implications of weak references and potential memory leaks if not used correctly.\n\n---\n\n## `Map`/`Set` vs `WeakMap`/`WeakSet`\n\nThe key differences between `Map`/`Set` and `WeakMap`/`WeakSet` in JavaScript are:\n\n1. **Key types**: `Map` and `Set` can have keys of any type (objects, primitive values, etc.), while `WeakMap` and `WeakSet` can only have objects as keys. Primitive values like strings or numbers are not allowed as keys in `WeakMap` and `WeakSet`.\n2. **Memory management**: The main difference lies in how they handle memory. `Map` and `Set` have strong references to their keys and values, which means they will prevent garbage collection of those values. On the other hand, `WeakMap` and `WeakSet` have weak references to their keys (objects), allowing those objects to be garbage collected if there are no other strong references to them.\n3. **Key enumeration**: Keys in `Map` and `Set` are enumerable (can be iterated over), while keys in `WeakMap` and `WeakSet` are not enumerable. This means you cannot get a list of keys or values from a `WeakMap` or `WeakSet`.\n4. **`size` property**: `Map` and `Set` have a `size` property that returns the number of elements, while `WeakMap` and `WeakSet` do not have a `size` property because their size can change due to garbage collection.\n5. **Use cases**: `Map` and `Set` are useful for general-purpose data structures and caching, while `WeakMap` and `WeakSet` are primarily used for storing metadata or additional data related to objects, without preventing those objects from being garbage collected.\n\n`Map` and `Set` are regular data structures that maintain strong references to their keys and values, while `WeakMap` and `WeakSet` are designed for scenarios where you want to associate data with objects without preventing those objects from being garbage collected when they are no longer needed.\n\n## Use cases of `WeakMap` and `WeakSet`\n\n### Tracking active users\n\nIn a chat application, you might want to track which user objects are currently active without preventing garbage collection when the user logs out or the session expires. We use a `WeakSet` to track active user objects. When a user logs out or their session expires, the user object can be garbage-collected if there are no other references to it.\n\n```js live\nconst activeUsers = new WeakSet();\n\n// Function to mark a user as active\nfunction markUserActive(user) {\n  activeUsers.add(user);\n}\n\n// Function to check if a user is active\nfunction isUserActive(user) {\n  return activeUsers.has(user);\n}\n\n// Example usage\nlet user1 = { id: 1, name: 'Alice' };\nlet user2 = { id: 2, name: 'Bob' };\n\nmarkUserActive(user1);\nmarkUserActive(user2);\n\nconsole.log(isUserActive(user1)); // true\nconsole.log(isUserActive(user2)); // true\n\n// Simulate user logging out\nuser1 = null;\n\n// user1 is now eligible for garbage collection\nconsole.log(isUserActive(user1)); // false\n```\n\n### Detecting circular references\n\n`WeakSet` is provides a way of guarding against circular data structures by tracking which objects have already been processed.\n\n```js live\n// Create a WeakSet to track visited objects\nconst visited = new WeakSet();\n\n// Function to traverse an object recursively\nfunction traverse(obj) {\n  // Check if the object has already been visited\n  if (visited.has(obj)) {\n    return;\n  }\n\n  // Add the object to the visited set\n  visited.add(obj);\n\n  // Traverse the object's properties\n  for (let prop in obj) {\n    if (obj.hasOwnProperty(prop)) {\n      let value = obj[prop];\n      if (typeof value === 'object' && value !== null) {\n        traverse(value);\n      }\n    }\n  }\n\n  // Process the object\n  console.log(obj);\n}\n\n// Create an object with a circular reference\nconst obj = {\n  name: 'John',\n  age: 30,\n  friends: [\n    { name: 'Alice', age: 25 },\n    { name: 'Bob', age: 28 },\n  ],\n};\n\n// Create a circular reference\nobj.self = obj;\n\n// Traverse the object\ntraverse(obj);\n```\n\n## Further reading\n\n- [`Map` | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n- [`WeakMap` | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap)\n- [`Set` | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)\n- [`WeakSet` | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet)\n- [`Map` and `Set` | Javascript.info](https://javascript.info/map-set)\n- [`WeakMap` and `WeakSet` | Javascript.info](https://javascript.info/weakmap-weakset)\n"
  },
  {
    "path": "questions/what-are-the-differences-between-map-set-and-weakmap-weakset/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-differences-between-map-set-and-weakmap-weakset\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 410,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-the-differences-between-map-set-and-weakmap-weakset/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中 `Map`/`Set` 和 `WeakMap`/`WeakSet` 有什么区别？\n---\n\n## 总结\n\nJavaScript 中 `Map`/`Set` 和 `WeakMap`/`WeakSet` 的主要区别在于它们如何处理键。以下是细分：\n\n**`Map` vs. `WeakMap`**\n\n`Map` 允许任何数据类型（字符串、数字、对象）作为键。只要引用 `Map` 对象本身，键值对就会保留在内存中。因此，它们适用于通用键值存储，您希望维护对键和值的引用。常见用例包括存储用户数据、配置设置或对象之间的关系。\n\n`WeakMap` 仅允许对象作为键。但是，这些对象键被弱保存。这意味着垃圾收集器可以从内存中删除它们，即使 `WeakMap` 本身仍然存在，只要没有对这些对象的其他引用。`WeakMap` 非常适合您希望将数据与对象关联而不会阻止这些对象被垃圾回收的场景。这对于以下情况可能很有用：\n\n* 基于对象缓存数据，而不会阻止对象本身的垃圾回收。\n* 存储与 DOM 节点关联的私有数据，而不会影响其生命周期。\n\n**`Set` vs. `WeakSet`**\n\n与 `Map` 类似，`Set` 允许任何数据类型作为键。`Set` 中的元素必须是唯一的。`Set` 适用于存储唯一值并有效检查成员资格。常见用例包括从数组中删除重复项或跟踪已完成的任务。\n\n另一方面，`WeakSet` 仅允许对象作为元素，并且这些对象元素被弱保存，类似于 `WeakMap` 键。`WeakSet` 很少使用，但当您需要一组唯一对象而不影响其垃圾回收时适用。这可能对于以下情况是必要的：\n\n* 跟踪已交互的 DOM 节点，而不会影响其内存管理。\n* 为特定用例实现自定义对象弱引用。\n\n**以下是一个总结关键差异的表格：**\n\n| 特性 | Map | WeakMap | Set | WeakSet |\n| --- | --- | --- | --- | --- |\n| 键类型 | 任何数据类型 | 对象（弱引用） | 任何数据类型（唯一） | 对象（弱引用，唯一） |\n| 垃圾回收 | 键和值不会被垃圾回收 | 如果没有其他地方引用，键可以被垃圾回收 | 元素不会被垃圾回收 | 如果没有其他地方引用，元素可以被垃圾回收 |\n| 用例 | 通用键值存储 | 缓存、私有 DOM 节点数据 | 删除重复项、成员资格检查 | 对象弱引用、自定义用例 |\n\n**在它们之间进行选择**\n\n* 在大多数需要存储键值对或唯一元素并希望维护对键/元素和值的引用的情况下，使用 `Map` 和 `Set`。\n* 在特定情况下谨慎使用 `WeakMap` 和 `WeakSet`，您希望将数据与对象关联而不会影响其垃圾回收。如果使用不当，请注意弱引用的含义和潜在的内存泄漏。\n\n***\n\n## `Map`/`Set` vs `WeakMap`/`WeakSet`\n\nJavaScript 中 `Map`/`Set` 和 `WeakMap`/`WeakSet` 之间的主要区别在于：\n\n1. **键类型**：`Map` 和 `Set` 可以具有任何类型的键（对象、原始值等），而 `WeakMap` 和 `WeakSet` 只能将对象作为键。原始值（如字符串或数字）不允许作为 `WeakMap` 和 `WeakSet` 中的键。\n2. **内存管理**：主要区别在于它们如何处理内存。`Map` 和 `Set` 具有对其键和值的强引用，这意味着它们将阻止对这些值进行垃圾回收。另一方面，`WeakMap` 和 `WeakSet` 具有对其键（对象）的弱引用，如果对它们没有其他强引用，则允许对这些对象进行垃圾回收。\n3. **键枚举**：`Map` 和 `Set` 中的键是可枚举的（可以迭代），而 `WeakMap` 和 `WeakSet` 中的键不可枚举。这意味着您无法从 `WeakMap` 或 `WeakSet` 获取键或值的列表。\n4. **`size` 属性**：`Map` 和 `Set` 具有一个 `size` 属性，该属性返回元素的数量，而 `WeakMap` 和 `WeakSet` 没有 `size` 属性，因为它们的大小可能会因垃圾回收而改变。\n5. **用例**：`Map` 和 `Set` 适用于通用数据结构和缓存，而 `WeakMap` 和 `WeakSet` 主要用于存储与对象相关的元数据或其他数据，而不会阻止对这些对象进行垃圾回收。\n\n`Map` 和 `Set` 是维护对其键和值的强引用的常规数据结构，而 `WeakMap` 和 `WeakSet` 专为希望将数据与对象关联而设计的场景，而不会阻止在不再需要这些对象时对它们进行垃圾回收。\n\n## `WeakMap` 和 `WeakSet` 的用例\n\n### 跟踪活跃用户\n\n在聊天应用程序中，您可能希望跟踪当前处于活动状态的用户对象，而不会在用户注销或会话过期时阻止垃圾回收。我们使用 `WeakSet` 来跟踪活跃的用户对象。当用户注销或他们的会话过期时，如果没有对该用户的其他引用，则该用户对象可以被垃圾回收。\n\n```js live\nconst activeUsers = new WeakSet();\n\n// Function to mark a user as active\nfunction markUserActive(user) {\n  activeUsers.add(user);\n}\n\n// Function to check if a user is active\nfunction isUserActive(user) {\n  return activeUsers.has(user);\n}\n\n// Example usage\nlet user1 = { id: 1, name: 'Alice' };\nlet user2 = { id: 2, name: 'Bob' };\n\nmarkUserActive(user1);\nmarkUserActive(user2);\n\nconsole.log(isUserActive(user1)); // true\nconsole.log(isUserActive(user2)); // true\n\n// Simulate user logging out\nuser1 = null;\n\n// user1 is now eligible for garbage collection\nconsole.log(isUserActive(user1)); // false\n```\n\n### 检测循环引用\n\n`WeakSet` 提供了一种通过跟踪哪些对象已经被处理来防止循环数据结构的方法。\n\n```js live\n// Create a WeakSet to track visited objects\nconst visited = new WeakSet();\n\n// Function to traverse an object recursively\nfunction traverse(obj) {\n  // Check if the object has already been visited\n  if (visited.has(obj)) {\n    return;\n  }\n\n  // Add the object to the visited set\n  visited.add(obj);\n\n  // Traverse the object's properties\n  for (let prop in obj) {\n    if (obj.hasOwnProperty(prop)) {\n      let value = obj[prop];\n      if (typeof value === 'object' && value !== null) {\n        traverse(value);\n      }\n    }\n  }\n\n  // Process the object\n  console.log(obj);\n}\n\n// Create an object with a circular reference\nconst obj = {\n  name: 'John',\n  age: 30,\n  friends: [\n    { name: 'Alice', age: 25 },\n    { name: 'Bob', age: 28 },\n  ],\n};\n\n// Create a circular reference\nobj.self = obj;\n\n// Traverse the object\ntraverse(obj);\n```\n\n## 延伸阅读\n\n* [`Map` | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n* [`WeakMap` | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap)\n* [`Set` | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)\n* [`WeakSet` | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet)\n* [`Map` and `Set` | Javascript.info](https://javascript.info/map-set)\n* [`WeakMap` and `WeakSet` | Javascript.info](https://javascript.info/weakmap-weakset)\n"
  },
  {
    "path": "questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"aae4d062\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"24fa666\",\n        \"30dafcb\",\n        \"2a7816d0\",\n        \"a5a5095\",\n        \"ca73c2a2\",\n        \"811b0194\",\n        \"79a76be0\",\n        \"4010553e\",\n        \"9f2bcaf2\",\n        \"a54701f1\",\n        \"8b8a1185\",\n        \"cb05daeb\",\n        \"bd8fbd99\",\n        \"c5a997a5\",\n        \"68dadf9\",\n        \"4b37fb58\",\n        \"b4d0cbd5\",\n        \"a48acc3\",\n        \"d785bc36\",\n        \"f2d34bc5\",\n        \"fc92c388\",\n        \"1f56c1f8\",\n        \"add698fb\",\n        \"da72207b\",\n        \"1f4770e5\",\n        \"e246bb9a\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"24fa666\",\n        \"30dafcb\",\n        \"2a7816d0\",\n        \"a5a5095\",\n        \"ca73c2a2\",\n        \"811b0194\",\n        \"79a76be0\",\n        \"4010553e\",\n        \"9f2bcaf2\",\n        \"a54701f1\",\n        \"8b8a1185\",\n        \"cb05daeb\",\n        \"bd8fbd99\",\n        \"c5a997a5\",\n        \"68dadf9\",\n        \"4b37fb58\",\n        \"b4d0cbd5\",\n        \"a48acc3\",\n        \"d785bc36\",\n        \"f2d34bc5\",\n        \"fc92c388\",\n        \"1f56c1f8\",\n        \"add698fb\",\n        \"da72207b\",\n        \"1f4770e5\",\n        \"e246bb9a\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-differences-between-variables-created-using-let-var-or-const/en-US.mdx",
    "content": "---\ntitle: What are the differences between JavaScript variables created using `let`, `var` or `const`?\n---\n\n## TL;DR\n\nIn JavaScript, `let`, `var`, and `const` are all keywords used to declare variables, but they differ significantly in terms of scope, initialization rules, whether they can be redeclared or reassigned and the behavior when they are accessed before declaration:\n\n| Behavior | `var` | `let` | `const` |\n| --- | --- | --- | --- |\n| Scope | Function or Global | Block | Block |\n| Initialization | Optional | Optional | Required |\n| Redeclaration | Yes | No | No |\n| Reassignment | Yes | Yes | No |\n| Accessing before declaration | `undefined` | `ReferenceError` | `ReferenceError` |\n\n---\n\n## Differences in behavior\n\nLet's look at the difference in behavior between `var`, `let`, and `const`.\n\n### Scope\n\nVariables declared using the `var` keyword are scoped to the function in which they are created, or if created outside of any function, to the global object. `let` and `const` are _block scoped_, meaning they are only accessible within the nearest set of curly braces (function, if-else block, or for-loop).\n\n```js live\nfunction foo() {\n  // All variables are accessible within functions.\n  var bar = 1;\n  let baz = 2;\n  const qux = 3;\n\n  console.log(bar); // 1\n  console.log(baz); // 2\n  console.log(qux); // 3\n}\n\nfoo(); // Prints each variable successfully\nconsole.log(bar); // ReferenceError: bar is not defined\nconsole.log(baz); // ReferenceError: baz is not defined\nconsole.log(qux); // ReferenceError: qux is not defined\n```\n\nIn the following example, `bar` is accessible outside of the `if` block but `baz` and `quz` are not.\n\n```js live\nif (true) {\n  var bar = 1;\n  let baz = 2;\n  const qux = 3;\n}\n\n// var variables are accessible anywhere in the function scope.\nconsole.log(bar); // 1\n// let and const variables are not accessible outside of the block they were defined in.\nconsole.log(baz); // ReferenceError: baz is not defined\nconsole.log(qux); // ReferenceError: qux is not defined\n```\n\n### Initialization\n\n`var` and `let` variables can be initialized without a value but `const` declarations must be initialized.\n\n```js live\nvar foo; // Ok\nlet bar; // Ok\nconst baz; // SyntaxError: Missing initializer in const declaration\n```\n\n### Redeclaration\n\nRedeclaring a variable with `var` will not throw an error, but `let` and `const` will.\n\n```js live\nvar foo = 1;\nvar foo = 2; // Ok\nconsole.log(foo); // Should print 2, but SyntaxError from baz prevents the code executing.\n\nlet baz = 3;\nlet baz = 4; // Uncaught SyntaxError: Identifier 'baz' has already been declared\n```\n\n### Reassignment\n\n`let` and `const` differ in that `var` and `let` allow reassigning the variable's value while `const` does not.\n\n```js live\nvar foo = 1;\nfoo = 2; // This is fine.\n\nlet bar = 3;\nbar = 4; // This is fine.\n\nconst baz = 5;\nbaz = 6; // Uncaught TypeError: Assignment to constant variable.\n```\n\n### Accessing before declaration\n\n`var` ,`let` and `const` declared variables are all hoisted. `var` declared variables are auto-initialized with an `undefined` value. However, `let` and `const` variables are not initialized and accessing them before the declaration will result in a `ReferenceError` exception because they are in a \"temporal dead zone\" from the start of the block until the declaration is processed.\n\n```js live\nconsole.log(foo); // undefined\nvar foo = 'foo';\n\nconsole.log(baz); // ReferenceError: Cannot access 'baz' before initialization\nlet baz = 'baz';\n\nconsole.log(bar); // ReferenceError: Cannot access 'baz' before initialization\nconst bar = 'bar';\n```\n\n## Notes\n\n- In modern JavaScript, it's generally recommended to use `const` by default for variables that don't need to be reassigned. This promotes immutability and prevents accidental changes.\n- Use `let` when you need to reassign a variable within its scope.\n- Avoid using `var` due to its potential for scoping issues and hoisting behavior.\n- If you need to target older browsers, write your code using `let`/`const`, and use a transpiler like Babel compile your code to older syntax.\n\n## Further reading\n\n- [The Difference of \"var\" vs \"let\" vs \"const\" in Javascript](https://medium.com/swlh/the-difference-of-var-vs-let-vs-const-in-javascript-abe37e214d66)\n"
  },
  {
    "path": "questions/what-are-the-differences-between-variables-created-using-let-var-or-const/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-differences-between-variables-created-using-let-var-or-const\",\n  \"languages\": [],\n  \"companies\": [\"microsoft\", \"tiktok\", \"atlassian\", \"linkedin\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 20,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-the-differences-between-variables-created-using-let-var-or-const/pt-BR.mdx",
    "content": "---\ntitle: Quais são as diferenças entre as variáveis criadas usando `let`, `var` ou `const`?\n---\n\nVariáveis declaradas usando a palavra-chave `var` têm escopo à função na qual foram criadas, ou se criadas fora de qualquer função, ao objeto global. `let` and `const` são _block scoped_, o que significa que eles só são acessíveis dentro do conjunto mais próximo de chaves (função, bloco if-else ou for-loop).\n\n```js\nfunction foo() {\n  // Todas as variáveis são acessíveis dentro de funções.\n  var bar = 'bar';\n  let baz = 'baz';\n  const qux = 'qux';\n\n  console.log(bar); // bar\n  console.log(baz); // baz\n  console.log(qux); // qux\n}\n\nconsole.log(bar); // ReferenceError: bar não é o console\nconsole.log(baz); // ReferenceError: baz não é definido\nconsole.log(qux); // ReferenceError: qux não é definido\n```\n\n```js\nif (true) {\n  var bar = 'bar';\n  let baz = 'baz';\n  const qux = 'qux';\n}\n\n// var variáveis declaradas são acessíveis em qualquer lugar do escopo da função.\nconsole.log(bar); // bar\n// let e const defined variáveis não são acessíveis fora do bloco no qual eles foram definidos.\nconsole.log(baz); // Referência: baz não está definido\nconsole.log(qux); // Referência: qux não está definido\n```\n\n'var' permite que as variáveis sejam hoisted, o que significa que elas podem ser referenciadas no código antes de serem declaradas. 'let' e 'const' não permitirão isso, em vez disso, será lançado um erro.\n\n```js\nconsole.log(foo); // undefined\n\nvar foo = 'foo';\n\nconsole.log(baz); // ReferenceError: não pôde acessar o console da declaração léxico 'baz' antes da inicialização\n\nlet baz = 'baz';\n\nconsole.log(bar); // ReferenceError: não é possível acessar a declaração léxico 'bar' antes da inicialização\n\nconst bar = 'bar';\n```\n\nRedeclarar uma variável com `var` não causará um erro, mas `let` e `const` irá.\n\n```js\nvar foo = 'foo';\nvar foo = 'bar';\nconsole.log(foo); // \"bar\"\n\nlet baz = 'baz';\nlet baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz' já foi declarado\n```\n\n`let` e `const` diferem que `let` permite reatribuir o valor da variável enquanto `const` não.\n\n```js\n// Tudo bem.\nlet foo = 'foo';\nfoo = 'bar';\n\n// Isso causa uma exceção.\nconst baz = 'baz';\nbaz = 'qux';\n```\n\n## Notas\n\n- Como a maioria dos navegadores suportam `let` e `const` atualmente, usar `var` não é mais recomendado. Se você precisa dar suporte a navegadores mais antigos, escreva seu código usando `let` e use um transpiler como o Babel para compilar seu código para uma sintaxe mais antiga.\n"
  },
  {
    "path": "questions/what-are-the-differences-between-variables-created-using-let-var-or-const/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中使用 `let`、`var` 或 `const` 创建的变量有什么区别？\n---\n\n## TL;DR\n\n在 JavaScript 中，`let`、`var` 和 `const` 都是用于声明变量的关键字，但它们在作用域、初始化规则、是否可以重新声明或重新赋值以及在声明前访问时的行为方面存在显着差异：\n\n| 行为 | `var` | `let` | `const` |\n| --- | --- | --- | --- |\n| 作用域 | 函数或全局 | 块 | 块 |\n| 初始化 | 可选 | 可选 | 必需 |\n| 重新声明 | 是 | 否 | 否 |\n| 重新赋值 | 是 | 是 | 否 |\n| 声明前访问 | `undefined` | `ReferenceError` | `ReferenceError` |\n\n***\n\n## 行为差异\n\n让我们看看 `var`、`let` 和 `const` 之间的行为差异。\n\n### 作用域\n\n使用 `var` 关键字声明的变量的作用域限定于创建它们的函数，或者如果创建在任何函数之外，则限定于全局对象。`let` 和 `const` 是*块作用域*，这意味着它们只能在最近的一组花括号（函数、if-else 块或 for 循环）内访问。\n\n```js live\nfunction foo() {\n  // All variables are accessible within functions.\n  var bar = 1;\n  let baz = 2;\n  const qux = 3;\n\n  console.log(bar); // 1\n  console.log(baz); // 2\n  console.log(qux); // 3\n}\n\nfoo(); // Prints each variable successfully\nconsole.log(bar); // ReferenceError: bar is not defined\nconsole.log(baz); // ReferenceError: baz is not defined\nconsole.log(qux); // ReferenceError: qux is not defined\n```\n\n在下面的示例中，`bar` 可以在 `if` 块之外访问，但 `baz` 和 `quz` 则不能。\n\n```js live\nif (true) {\n  var bar = 1;\n  let baz = 2;\n  const qux = 3;\n}\n\n// var variables are accessible anywhere in the function scope.\nconsole.log(bar); // 1\n// let and const variables are not accessible outside of the block they were defined in.\nconsole.log(baz); // ReferenceError: baz is not defined\nconsole.log(qux); // ReferenceError: qux is not defined\n```\n\n### 初始化\n\n`var` 和 `let` 变量可以在没有值的情况下初始化，但 `const` 声明必须初始化。\n\n```js live\nvar foo; // Ok\nlet bar; // Ok\nconst baz; // SyntaxError: Missing initializer in const declaration\n```\n\n### 重新声明\n\n使用 `var` 重新声明变量不会抛出错误，但 `let` 和 `const` 会。\n\n```js live\nvar foo = 1;\nvar foo = 2; // Ok\nconsole.log(foo); // Should print 2, but SyntaxError from baz prevents the code executing.\n\nlet baz = 3;\nlet baz = 4; // Uncaught SyntaxError: Identifier 'baz' has already been declared\n```\n\n### 重新赋值\n\n`let` 和 `const` 的区别在于，`var` 和 `let` 允许重新分配变量的值，而 `const` 不允许。\n\n```js live\nvar foo = 1;\nfoo = 2; // This is fine.\n\nlet bar = 3;\nbar = 4; // This is fine.\n\nconst baz = 5;\nbaz = 6; // Uncaught TypeError: Assignment to constant variable.\n```\n\n### 声明前访问\n\n`var`、`let` 和 `const` 声明的变量都会被提升。`var` 声明的变量会自动初始化为 `undefined` 值。但是，`let` 和 `const` 变量不会被初始化，在声明之前访问它们将导致 `ReferenceError` 异常，因为它们处于从块的开始到声明被处理的“暂时性死区”。\n\n```js live\nconsole.log(foo); // undefined\nvar foo = 'foo';\n\nconsole.log(baz); // ReferenceError: Cannot access 'baz' before initialization\nlet baz = 'baz';\n\nconsole.log(bar); // ReferenceError: Cannot access 'baz' before initialization\nconst bar = 'bar';\n```\n\n## 笔记\n\n* 在现代 JavaScript 中，通常建议默认对不需要重新赋值的变量使用 `const`。这可以提高不变性并防止意外更改。\n* 当您需要在其范围内重新分配变量时，请使用 `let`。\n* 避免使用 `var`，因为它可能存在作用域问题和提升行为。\n* 如果您需要针对旧版浏览器，请使用 `let`/`const` 编写代码，并使用 Babel 等转译器将您的代码编译为旧语法。\n\n## 延伸阅读\n\n* [Javascript 中 \"var\" vs \"let\" vs \"const\" 的区别](https://medium.com/swlh/the-difference-of-var-vs-let-vs-const-in-javascript-abe37e214d66)\n"
  },
  {
    "path": "questions/what-are-the-differences-between-xmlhttprequest-and-fetch/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"f2214786\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3468354c\",\n        \"b804e1ae\",\n        \"24037d00\",\n        \"2a7816d0\",\n        \"2a4890b9\",\n        \"de7c4d81\",\n        \"5551839d\",\n        \"efe43a6b\",\n        \"5fe2025b\",\n        \"44666a07\",\n        \"d7e06034\",\n        \"f3d7c7d3\",\n        \"aefe3894\",\n        \"3e4c87f8\",\n        \"a6468de\",\n        \"1fbdaeb4\",\n        \"75a348\",\n        \"eb40f10c\",\n        \"5fec58ac\",\n        \"61e9c62e\",\n        \"24117866\",\n        \"95281ddc\",\n        \"7519ded0\",\n        \"d3e92efc\",\n        \"4cda4bac\",\n        \"3a119008\",\n        \"9f174f08\",\n        \"91fe7a77\",\n        \"4b099bfb\",\n        \"4b74ca9c\",\n        \"6421a62f\",\n        \"bcf46695\",\n        \"663d2369\",\n        \"128e8b9c\",\n        \"d0150874\",\n        \"dd887f26\",\n        \"307c3ed6\",\n        \"4351c2c2\",\n        \"2232a4c1\",\n        \"ec31fcc2\",\n        \"17840616\",\n        \"81595954\",\n        \"171b8f2e\",\n        \"649f79da\",\n        \"839de168\",\n        \"4a61620f\",\n        \"5c76b4eb\",\n        \"2f2aecf8\",\n        \"b9e94c15\",\n        \"81f2d0\",\n        \"d265256c\",\n        \"fa307855\",\n        \"1f4770e5\",\n        \"3754c7e9\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3468354c\",\n        \"b804e1ae\",\n        \"24037d00\",\n        \"2a7816d0\",\n        \"2a4890b9\",\n        \"de7c4d81\",\n        \"5551839d\",\n        \"efe43a6b\",\n        \"5fe2025b\",\n        \"44666a07\",\n        \"d7e06034\",\n        \"f3d7c7d3\",\n        \"aefe3894\",\n        \"3e4c87f8\",\n        \"a6468de\",\n        \"1fbdaeb4\",\n        \"75a348\",\n        \"eb40f10c\",\n        \"5fec58ac\",\n        \"61e9c62e\",\n        \"24117866\",\n        \"95281ddc\",\n        \"7519ded0\",\n        \"d3e92efc\",\n        \"4cda4bac\",\n        \"3a119008\",\n        \"9f174f08\",\n        \"91fe7a77\",\n        \"4b099bfb\",\n        \"4b74ca9c\",\n        \"6421a62f\",\n        \"bcf46695\",\n        \"663d2369\",\n        \"128e8b9c\",\n        \"d0150874\",\n        \"dd887f26\",\n        \"307c3ed6\",\n        \"4351c2c2\",\n        \"2232a4c1\",\n        \"ec31fcc2\",\n        \"17840616\",\n        \"81595954\",\n        \"171b8f2e\",\n        \"649f79da\",\n        \"839de168\",\n        \"4a61620f\",\n        \"5c76b4eb\",\n        \"2f2aecf8\",\n        \"b9e94c15\",\n        \"81f2d0\",\n        \"d265256c\",\n        \"fa307855\",\n        \"1f4770e5\",\n        \"3754c7e9\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-differences-between-xmlhttprequest-and-fetch/en-US.mdx",
    "content": "---\ntitle: What are the differences between `XMLHttpRequest` and `fetch()` in JavaScript and browsers?\n---\n\n## TL;DR\n\n`XMLHttpRequest` (XHR) and `fetch()` API are both used for asynchronous HTTP requests in JavaScript (AJAX). `fetch()` offers a cleaner syntax, promise-based approach, and more modern feature set compared to XHR. However, there are some differences:\n\n- `XMLHttpRequest` event callbacks, while `fetch()` utilizes promise chaining.\n- `fetch()` provides more flexibility in headers and request bodies.\n- `fetch()` support cleaner error handling with `catch()`.\n- Handling caching with `XMLHttpRequest` is difficult but caching is supported by `fetch()` by default in the `options.cache` object (`cache` value of second parameter) to `fetch()` or `Request()`.\n- `fetch()` requires an `AbortController` for cancelation, while for `XMLHttpRequest`, it provides `abort()` property.\n- `XMLHttpRequest` has good support for progress tracking, which `fetch()` lacks.\n- `XMLHttpRequest` is only available in the browser and not natively supported in Node.js environments. On the other hand `fetch()` is part of the JavaScript language and is supported on all modern JavaScript runtimes.\n\nThese days `fetch()` is preferred for its cleaner syntax and modern features.\n\n---\n\n## `XMLHttpRequest` vs `fetch()`\n\nBoth `XMLHttpRequest` (XHR) and `fetch()` are ways to make asynchronous HTTP requests in JavaScript. However, they differ significantly in syntax, promise handling, and feature set.\n\n## Syntax and usage\n\n`XMLHttpRequest` is event-driven and requires attaching event listeners to handle response/error states. The basic syntax for creating an `XMLHttpRequest` object and sending a request is as follows:\n\n```js live\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.responseType = 'json';\nxhr.onload = function () {\n  if (xhr.status === 200) {\n    console.log(xhr.response);\n  }\n};\nxhr.send();\n```\n\n`xhr` is an instance of the `XMLHttpRequest` class. The `open` method is used to specify the request method, URL, and whether the request should be asynchronous. The `onload` event is used to handle the response, and the `send` method is used to send the request.\n\n`fetch()` provides a more straightforward and intuitive way of making HTTP requests. It is `Promise`-based and returns a promise that resolves with the response or rejects with an error. The basic syntax for making a GET request using `fetch()` is as follows:\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.text())\n  .then((data) => console.log(data));\n```\n\n## Request headers\n\nBoth `XMLHttpRequest` and `fetch()` support setting request headers. However, `fetch()` provides more flexibility in terms of setting headers, as it supports custom headers and allows for more complex header configurations.\n\n`XMLHttpRequest` supports setting request headers using the `setRequestHeader` method:\n\n```js\nxhr.setRequestHeader('Content-Type', 'application/json');\nxhr.setRequestHeader('Authorization', 'Bearer YOUR_TOKEN');\n```\n\nFor `fetch()`, headers are passed as an object in the second argument to `fetch()`:\n\n```js\nfetch('https://jsonplaceholder.typicode.com/todos/1', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n    Authorization: 'Bearer YOUR_TOKEN',\n  },\n  body: JSON.stringify({\n    name: 'John Doe',\n    age: 30,\n  }),\n});\n```\n\n## Request body\n\nBoth `XMLHttpRequest` and `fetch()` support sending request bodies. However, `fetch()` provides more flexibility in terms of sending request bodies, as it supports sending JSON data, form data, and more.\n\n`XMLHttpRequest` supports sending request bodies using the `send` method:\n\n```js\nconst xhr = new XMLHttpRequest();\nxhr.open('POST', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.send(\n  JSON.stringify({\n    name: 'John Doe',\n    age: 30,\n  }),\n);\n```\n\n`fetch()` supports sending request bodies using the `body` property in the second argument to `fetch()`:\n\n```js\nfetch('https://jsonplaceholder.typicode.com/todos/1', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n  },\n  body: JSON.stringify({\n    name: 'John Doe',\n    age: 30,\n  }),\n});\n```\n\n## Response handling\n\n`XMLHttpRequest` provides a `responseType` property to set the response format that we are expecting. `responseType` is `'text'` by default but it support types likes `'text'`, `'arraybuffer'`, `'blob'`, `'document'` and `'json'`.\n\n```js live\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.responseType = 'json'; // or 'text', 'blob', 'arraybuffer'\nxhr.onload = function () {\n  if (xhr.status === 200) {\n    console.log(xhr.response);\n  }\n};\nxhr.send();\n```\n\nOn the other hand, `fetch()` provides a unified `Response` object with `then` method for accessing data.\n\n```js live\n// JSON data\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.json())\n  .then((data) => console.log(data));\n\n// Text data\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.text())\n  .then((data) => console.log(data));\n```\n\n## Error handling\n\nBoth support error handling but `fetch()` provides more flexibility in terms of error handling, as it supports handling errors using the `.catch()` method.\n\n`XMLHttpRequest` supports error handling using the `onerror` event:\n\n```js live\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://jsonplaceholder.typicod.com/todos/1', true); // Typo in URL\nxhr.responseType = 'json';\nxhr.onload = function () {\n  if (xhr.status === 200) {\n    console.log(xhr.response);\n  }\n};\nxhr.onerror = function () {\n  console.error('Error occurred');\n};\nxhr.send();\n```\n\n`fetch()` supports error handling using the `catch()` method on the returned `Promise`:\n\n```js live\nfetch('https://jsonplaceholder.typicod.com/todos/1') // Typo in URL\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error occurred: ' + error));\n```\n\n## Caching control\n\nHandling caching with `XMLHttpRequest` is difficult, and you might need to add a random value to the query string in order to get around the browser cache. Caching is supported by `fetch()` by default in the second parameter of the `options` object:\n\n```js\nconst res = await fetch('https://jsonplaceholder.typicode.com/todos/1', {\n  method: 'GET',\n  cache: 'default',\n});\n```\n\nOther values for the [`cache` option](https://developer.mozilla.org/en-US/docs/Web/API/Request/cache) include `default`, `no-store`, `reload`, `no-cache`, `force-cache`, and `only-if-cached`.\n\n## Cancelation\n\nIn-flight `XMLHttpRequest`s can be canceled by running the `XMLHttpRequest`'s `abort()` method. An `abort` handler can be attached by assigning to the `.onabort` property if necessary:\n\n```js live\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');\nxhr.send();\n// ...\nxhr.onabort = () => console.log('aborted');\nxhr.abort();\n```\n\nAborting a `fetch()` requires creating an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) object and passing it to as the `signal` property of the `options` object when calling `fetch()`.\n\n```js live\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nfetch('https://jsonplaceholder.typicode.com/todos/1', { signal })\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error occurred: ' + error));\n\n// Abort request.\ncontroller.abort();\n```\n\n## Progress support\n\n`XMLHttpRequest` supports tracking the progress of requests by attaching a handler to the `XMLHttpRequest` object's progress event. This is especially useful when uploading large files such as videos to track the progress of the upload.\n\n```js\nconst xhr = new XMLHttpRequest();\n\n// The callback is passed a `ProgressEvent`.\nxhr.upload.onprogress = (event) => {\n  console.log(Math.round((event.loaded / event.total) * 100) + '%');\n};\n```\n\nThe callback assigned to `onprogress` is passed a [`ProgressEvent`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/progress_event):\n\n- The `loaded` field on the `ProgressEvent` is a 64-bit integer indicating the amount of work already performed (bytes uploaded/downloaded) by the underlying process.\n- The `total` field on the `ProgressEvent` is a 64-bit integer representing the total amount of work that the underlying process is in the progress of performing. When downloading resources, this is the `Content-Length` value of the HTTP response.\n\nOn the other hand, the `fetch()` API does not offer any convenient way to track upload progress. It can be implemented by monitoring the `body` of the `Response` object as a fraction of the `Content-Length` header, but it's quite complicated.\n\n## Choosing between `XMLHttpRequest` and `fetch()`\n\nIn modern development scenarios, `fetch()` is the preferred choice due to its cleaner syntax, promise-based approach, and improved handling of features like error handling, headers, and CORS.\n\n## Further reading\n\n- [Fetch API | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)\n- [XMLHttpRequest | MDN](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)\n- [Request: cache property | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Request/cache)\n- [XMLHttpRequest | Javascript.info](https://javascript.info/xmlhttprequest)\n- [This API is so Fetching! - Mozilla Hacks](https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/)\n"
  },
  {
    "path": "questions/what-are-the-differences-between-xmlhttprequest-and-fetch/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-differences-between-xmlhttprequest-and-fetch\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"networking\"],\n  \"importance\": \"medium\",\n  \"ranking\": 290,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/what-are-the-differences-between-xmlhttprequest-and-fetch/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 和浏览器中 `XMLHttpRequest` 和 `fetch()` 之间有什么区别？\n---\n\n## TL;DR\n\n`XMLHttpRequest` (XHR) 和 `fetch()` API 都用于 JavaScript (AJAX) 中的异步 HTTP 请求。与 XHR 相比，`fetch()` 提供了更简洁的语法、基于 Promise 的方法和更现代的功能集。但是，存在一些差异：\n\n* `XMLHttpRequest` 事件回调，而 `fetch()` 使用 promise 链。\n* `fetch()` 在标头和请求体方面提供了更大的灵活性。\n* `fetch()` 通过 `catch()` 支持更简洁的错误处理。\n* 使用 `XMLHttpRequest` 处理缓存很困难，但 `fetch()` 默认在 `options.cache` 对象（第二个参数的 `cache` 值）中支持缓存到 `fetch()` 或 `Request()`。\n* `fetch()` 需要 `AbortController` 来取消，而对于 `XMLHttpRequest`，它提供了 `abort()` 属性。\n* `XMLHttpRequest` 对进度跟踪有很好的支持，而 `fetch()` 缺乏。\n* `XMLHttpRequest` 仅在浏览器中可用，并且在 Node.js 环境中不受原生支持。另一方面，`fetch()` 是 JavaScript 语言的一部分，并且在所有现代 JavaScript 运行时中都受支持。\n\n如今，由于其更简洁的语法和现代功能，更倾向于使用 `fetch()`。\n\n***\n\n## `XMLHttpRequest` vs `fetch()`\n\n`XMLHttpRequest` (XHR) 和 `fetch()` 都是在 JavaScript 中进行异步 HTTP 请求的方式。但是，它们在语法、promise 处理和功能集方面存在显着差异。\n\n## 语法和用法\n\n`XMLHttpRequest` 是事件驱动的，需要附加事件侦听器来处理响应/错误状态。创建 `XMLHttpRequest` 对象和发送请求的基本语法如下：\n\n```js live\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.responseType = 'json';\nxhr.onload = function () {\n  if (xhr.status === 200) {\n    console.log(xhr.response);\n  }\n};\nxhr.send();\n```\n\n`xhr` 是 `XMLHttpRequest` 类的实例。`open` 方法用于指定请求方法、URL 以及请求是否应为异步。`onload` 事件用于处理响应，`send` 方法用于发送请求。\n\n`fetch()` 提供了一种更直接、更直观的方式来发出 HTTP 请求。它是基于 `Promise` 的，并返回一个 promise，该 promise 使用响应进行解析或使用错误进行拒绝。使用 `fetch()` 发出 GET 请求的基本语法如下：\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.text())\n  .then((data) => console.log(data));\n```\n\n## 请求标头\n\n`XMLHttpRequest` 和 `fetch()` 都支持设置请求标头。但是，`fetch()` 在设置标头方面提供了更大的灵活性，因为它支持自定义标头并允许更复杂的标头配置。\n\n`XMLHttpRequest` 支持使用 `setRequestHeader` 方法设置请求标头：\n\n```js\nxhr.setRequestHeader('Content-Type', 'application/json');\nxhr.setRequestHeader('Authorization', 'Bearer YOUR_TOKEN');\n```\n\n对于 `fetch()`，标头作为对象传递给 `fetch()` 的第二个参数：\n\n```js\nfetch('https://jsonplaceholder.typicode.com/todos/1', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n    Authorization: 'Bearer YOUR_TOKEN',\n  },\n  body: JSON.stringify({\n    name: 'John Doe',\n    age: 30,\n  }),\n});\n```\n\n## 请求体\n\n`XMLHttpRequest` 和 `fetch()` 都支持发送请求体。但是，`fetch()` 在发送请求体方面提供了更大的灵活性，因为它支持发送 JSON 数据、表单数据等。\n\n`XMLHttpRequest` 支持使用 `send` 方法发送请求体：\n\n```js\nconst xhr = new XMLHttpRequest();\nxhr.open('POST', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.send(\n  JSON.stringify({\n    name: 'John Doe',\n    age: 30,\n  }),\n);\n```\n\n`fetch()` 支持使用 `fetch()` 的第二个参数中的 `body` 属性发送请求体：\n\n```js\nfetch('https://jsonplaceholder.typicode.com/todos/1', {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application/json',\n  },\n  body: JSON.stringify({\n    name: 'John Doe',\n    age: 30,\n  }),\n});\n```\n\n## 响应处理\n\n`XMLHttpRequest` 提供了一个 `responseType` 属性来设置我们期望的响应格式。`responseType` 默认为 `'text'`，但它支持 `'text'`、`'arraybuffer'`、`'blob'`、`'document'` 和 `'json'` 等类型。\n\n```js live\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.responseType = 'json'; // or 'text', 'blob', 'arraybuffer'\nxhr.onload = function () {\n  if (xhr.status === 200) {\n    console.log(xhr.response);\n  }\n};\nxhr.send();\n```\n\n另一方面，`fetch()` 提供了一个统一的 `Response` 对象，它具有用于访问数据的 `then` 方法。\n\n```js live\n// JSON data\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.json())\n  .then((data) => console.log(data));\n\n// Text data\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.text())\n  .then((data) => console.log(data));\n```\n\n## 错误处理\n\n两者都支持错误处理，但 `fetch()` 在错误处理方面提供了更大的灵活性，因为它支持使用 `.catch()` 方法处理错误。\n\n`XMLHttpRequest` 支持使用 `onerror` 事件进行错误处理：\n\n```js live\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://jsonplaceholder.typicod.com/todos/1', true); // Typo in URL\nxhr.responseType = 'json';\nxhr.onload = function () {\n  if (xhr.status === 200) {\n    console.log(xhr.response);\n  }\n};\nxhr.onerror = function () {\n  console.error('Error occurred');\n};\nxhr.send();\n```\n\n`fetch()` 支持使用返回的 `Promise` 上的 `catch()` 方法进行错误处理：\n\n```js live\nfetch('https://jsonplaceholder.typicod.com/todos/1') // Typo in URL\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error occurred: ' + error));\n```\n\n## 缓存控制\n\n使用 `XMLHttpRequest` 处理缓存很困难，您可能需要向查询字符串添加一个随机值才能绕过浏览器缓存。 默认情况下，`fetch()` 在 `options` 对象的第二个参数中支持缓存：\n\n```js\nconst res = await fetch('https://jsonplaceholder.typicode.com/todos/1', {\n  method: 'GET',\n  cache: 'default',\n});\n```\n\n[`cache` option](https://developer.mozilla.org/en-US/docs/Web/API/Request/cache) 的其他值包括 `default`、`no-store`、`reload`、`no-cache`、`force-cache` 和 `only-if-cached`。\n\n## 取消\n\n正在进行的 `XMLHttpRequest` 可以通过运行 `XMLHttpRequest` 的 `abort()` 方法来取消。如果需要，可以通过将 `.onabort` 属性赋值来附加一个 `abort` 处理程序：\n\n```js live\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');\nxhr.send();\n// ...\nxhr.onabort = () => console.log('aborted');\nxhr.abort();\n```\n\n中止 `fetch()` 需要创建一个 [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) 对象，并在调用 `fetch()` 时将其作为 `options` 对象的 `signal` 属性传递。\n\n```js live\nconst controller = new AbortController();\nconst signal = controller.signal;\n\nfetch('https://jsonplaceholder.typicode.com/todos/1', { signal })\n  .then((response) => response.json())\n  .then((data) => console.log(data))\n  .catch((error) => console.error('Error occurred: ' + error));\n\n// Abort request.\ncontroller.abort();\n```\n\n## 进度支持\n\n`XMLHttpRequest` 通过将处理程序附加到 `XMLHttpRequest` 对象的进度事件来支持跟踪请求的进度。 这在上传大文件（例如视频）以跟踪上传进度时特别有用。\n\n```js\nconst xhr = new XMLHttpRequest();\n\n// The callback is passed a `ProgressEvent`.\nxhr.upload.onprogress = (event) => {\n  console.log(Math.round((event.loaded / event.total) * 100) + '%');\n};\n```\n\n分配给 `onprogress` 的回调函数会传递一个 [`ProgressEvent`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/progress_event):\n\n* `ProgressEvent`上的`loaded`字段是一个64位整数，表示底层进程已经完成的工作量（已上传/下载的字节数）。\n* `ProgressEvent`上的`total`字段是一个64位整数，表示底层进程正在执行的总工作量。下载资源时，这是HTTP响应的`Content-Length`值。\n\n另一方面，`fetch()` API 并没有提供任何方便的方法来跟踪上传进度。 它可以实现为监视 `Response` 对象的 `body` 作为 `Content-Length` 标头的分数，但这非常复杂。\n\n## 在 `XMLHttpRequest` 和 `fetch()` 之间进行选择\n\n在现代开发场景中，由于其更简洁的语法、基于 promise 的方法以及改进的错误处理、标头和 CORS 等功能处理，`fetch()` 是首选。\n\n## 延伸阅读\n\n* [Fetch API | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)\n* [XMLHttpRequest | MDN](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)\n* [Request: cache property | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Request/cache)\n* [XMLHttpRequest | Javascript.info](https://javascript.info/xmlhttprequest)\n* [This API is so Fetching! - Mozilla Hacks](https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/)\n"
  },
  {
    "path": "questions/what-are-the-different-methods-for-iterating-over-an-array/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"1bcf4c3d\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"653b0f86\",\n        \"2a7816d0\",\n        \"3a044d63\",\n        \"c38781d3\",\n        \"2c3f9856\",\n        \"e0ce78b6\",\n        \"649b64c9\",\n        \"98e8da5b\",\n        \"37afb482\",\n        \"6a15397c\",\n        \"95a96c5a\",\n        \"2cf9914a\",\n        \"51acbeb5\",\n        \"fdaeaab4\",\n        \"c0f9fadd\",\n        \"71f321cc\",\n        \"4a045853\",\n        \"ef2cf30b\",\n        \"b672b5b9\",\n        \"c2dd4f2b\",\n        \"806077ef\",\n        \"1f4770e5\",\n        \"d18538e5\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"653b0f86\",\n        \"2a7816d0\",\n        \"3a044d63\",\n        \"c38781d3\",\n        \"2c3f9856\",\n        \"e0ce78b6\",\n        \"649b64c9\",\n        \"98e8da5b\",\n        \"37afb482\",\n        \"6a15397c\",\n        \"95a96c5a\",\n        \"2cf9914a\",\n        \"51acbeb5\",\n        \"fdaeaab4\",\n        \"c0f9fadd\",\n        \"71f321cc\",\n        \"4a045853\",\n        \"ef2cf30b\",\n        \"b672b5b9\",\n        \"c2dd4f2b\",\n        \"806077ef\",\n        \"1f4770e5\",\n        \"d18538e5\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-different-methods-for-iterating-over-an-array/en-US.mdx",
    "content": "---\ntitle: What are the different methods for iterating over an array?\n---\n\n## TL;DR\n\nThere are several methods to iterate over an array in JavaScript. The most common ones include `for` loops, `forEach`, `map`, `filter`, `reduce`, and `for...of`. Each method has its own use case. For example, `for` loops are versatile and can be used for any kind of iteration, while `forEach` is specifically for executing a function on each array element. `map` is used for transforming arrays, `filter` for filtering elements, `reduce` for accumulating values, and `for...of` for iterating over iterable objects.\n\n---\n\n## Different methods for iterating over an array\n\n### For loop\n\nThe `for` loop is one of the most basic and versatile ways to iterate over an array. It allows you to control the iteration process completely.\n\n```js live\nconst array = [1, 2, 3, 4, 5];\nfor (let i = 0; i < array.length; i++) {\n  console.log(array[i]);\n}\n```\n\n### For...of loop\n\nThe `for...of` loop is a more modern and readable way to iterate over arrays and other iterable objects.\n\n```js live\nconst array = [1, 2, 3, 4, 5];\nfor (const element of array) {\n  console.log(element);\n}\n```\n\n### forEach method\n\nThe `forEach` method executes a provided function once for each array element.\n\n```js live\nconst array = [1, 2, 3, 4, 5];\narray.forEach((element) => {\n  console.log(element);\n});\n```\n\n### Map method\n\nThe `map` method creates a new array populated with the results of calling a provided function on every element in the calling array.\n\n```js live\nconst array = [1, 2, 3, 4, 5];\nconst newArray = array.map((element) => element * 2);\nconsole.log(newArray); // [2, 4, 6, 8, 10]\n```\n\n### Filter method\n\nThe `filter` method creates a new array with all elements that pass the test implemented by the provided function.\n\n```js live\nconst array = [1, 2, 3, 4, 5];\nconst filteredArray = array.filter((element) => element > 2);\nconsole.log(filteredArray); // [3, 4, 5]\n```\n\n### Reduce method\n\nThe `reduce` method executes a reducer function on each element of the array, resulting in a single output value.\n\n```js live\nconst array = [1, 2, 3, 4, 5];\nconst sum = array.reduce(\n  (accumulator, currentValue) => accumulator + currentValue,\n  0,\n);\nconsole.log(sum); // 15\n```\n\n## Further reading\n\n- [MDN Web Docs: Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)\n- [MDN Web Docs: forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)\n- [MDN Web Docs: map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)\n- [MDN Web Docs: filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)\n- [MDN Web Docs: reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)\n- [MDN Web Docs: for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n"
  },
  {
    "path": "questions/what-are-the-different-methods-for-iterating-over-an-array/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-different-methods-for-iterating-over-an-array\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/what-are-the-different-methods-for-iterating-over-an-array/zh-CN.mdx",
    "content": "---\ntitle: 有哪些不同的遍历数组的方法？\n---\n\n## TL;DR\n\n在 JavaScript 中，有几种遍历数组的方法。最常见的方法包括 `for` 循环、`forEach`、`map`、`filter`、`reduce` 和 `for...of`。每种方法都有其自身的用例。例如，`for` 循环用途广泛，可用于任何类型的迭代，而 `forEach` 专门用于对每个数组元素执行一个函数。`map` 用于转换数组，`filter` 用于过滤元素，`reduce` 用于累加值，而 `for...of` 用于遍历可迭代对象。\n\n***\n\n## 遍历数组的不同方法\n\n### For 循环\n\n`for` 循环是遍历数组的最基本和最通用的方法之一。它允许你完全控制迭代过程。\n\n```js live\nconst array = [1, 2, 3, 4, 5];\nfor (let i = 0; i < array.length; i++) {\n  console.log(array[i]);\n}\n```\n\n### For...of 循环\n\n`for...of` 循环是一种更现代、更易读的遍历数组和其他可迭代对象的方法。\n\n```js live\nconst array = [1, 2, 3, 4, 5];\nfor (const element of array) {\n  console.log(element);\n}\n```\n\n### forEach 方法\n\n`forEach` 方法为每个数组元素执行提供的函数一次。\n\n```js live\nconst array = [1, 2, 3, 4, 5];\narray.forEach((element) => {\n  console.log(element);\n});\n```\n\n### Map 方法\n\n`map` 方法创建一个新数组，其中填充了在调用数组中的每个元素上调用提供的函数的结果。\n\n```js live\nconst array = [1, 2, 3, 4, 5];\nconst newArray = array.map((element) => element * 2);\nconsole.log(newArray); // [2, 4, 6, 8, 10]\n```\n\n### Filter 方法\n\n`filter` 方法创建一个新数组，其中包含通过提供的函数实现的测试的所有元素。\n\n```js live\nconst array = [1, 2, 3, 4, 5];\nconst filteredArray = array.filter((element) => element > 2);\nconsole.log(filteredArray); // [3, 4, 5]\n```\n\n### Reduce 方法\n\n`reduce` 方法对数组的每个元素执行一个 reducer 函数，最终得到一个单一的输出值。\n\n```js live\nconst array = [1, 2, 3, 4, 5];\nconst sum = array.reduce(\n  (accumulator, currentValue) => accumulator + currentValue,\n  0,\n);\nconsole.log(sum); // 15\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n"
  },
  {
    "path": "questions/what-are-the-different-types-of-errors-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"ecc5300e\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"da558578\",\n        \"2a7816d0\",\n        \"ead217b1\",\n        \"e48cd3cd\",\n        \"3b2a5368\",\n        \"748ffe75\",\n        \"f0e5c7b3\",\n        \"60c218f1\",\n        \"1664b20a\",\n        \"748ffe75\",\n        \"9a16a150\",\n        \"1882c98e\",\n        \"c1661bc3\",\n        \"748ffe75\",\n        \"817d76ba\",\n        \"1f4770e5\",\n        \"a0d8e7b0\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"da558578\",\n        \"2a7816d0\",\n        \"ead217b1\",\n        \"e48cd3cd\",\n        \"3b2a5368\",\n        \"748ffe75\",\n        \"f0e5c7b3\",\n        \"60c218f1\",\n        \"1664b20a\",\n        \"748ffe75\",\n        \"9a16a150\",\n        \"1882c98e\",\n        \"c1661bc3\",\n        \"748ffe75\",\n        \"817d76ba\",\n        \"1f4770e5\",\n        \"a0d8e7b0\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-different-types-of-errors-in-javascript/en-US.mdx",
    "content": "---\ntitle: What are the different types of errors in JavaScript?\n---\n\n## TL;DR\n\nIn JavaScript, there are three main types of errors: syntax errors, runtime errors, and logical errors. Syntax errors occur when the code violates the language's grammar rules, such as missing a parenthesis. Runtime errors happen during code execution, like trying to access a property of `undefined`. Logical errors are mistakes in the code's logic that lead to incorrect results but don't throw an error.\n\n---\n\n## Different types of errors in JavaScript\n\n### Syntax errors\n\nSyntax errors occur when the code does not follow the rules of the JavaScript language. These errors are detected by the JavaScript engine during the parsing stage before the code is executed.\n\n#### Example\n\n```js live\nconsole.log(\"Hello, world!; // Missing closing quote and parenthesis\n```\n\n### Runtime errors\n\nRuntime errors, also known as exceptions, occur during the execution of the code. These errors happen when the code is syntactically correct but encounters an issue that prevents it from completing its task.\n\n#### Example\n\n```js live\nlet obj = null;\nconsole.log(obj.property); // TypeError: Cannot read properties of null (reading 'property')\n```\n\n### Logical errors\n\nLogical errors are mistakes in the code's logic that lead to incorrect results. These errors do not throw exceptions and are often the hardest to debug because the code runs without any issues but produces the wrong output.\n\n#### Example\n\n```js live\nlet isAdmin = false;\n\nif ((isAdmin = true)) {\n  // Wrong: Assignment instead of comparison\n  console.log('Access granted'); // Access granted even though isAdmin was falsy\n} else {\n  console.log('Access denied');\n}\n```\n\n## Further reading\n\n- [MDN Web Docs: Errors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)\n- [JavaScript.info: Error handling](https://javascript.info/error-handling)\n- [W3Schools: JavaScript Errors](https://www.w3schools.com/js/js_errors.asp)\n"
  },
  {
    "path": "questions/what-are-the-different-types-of-errors-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-different-types-of-errors-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Error Handling\"\n}\n"
  },
  {
    "path": "questions/what-are-the-different-types-of-errors-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中有哪些不同类型的错误？\n---\n\n## TL;DR\n\n在 JavaScript 中，主要有三种类型的错误：语法错误、运行时错误和逻辑错误。当代码违反语言的语法规则时，例如缺少括号，就会发生语法错误。运行时错误发生在代码执行期间，例如尝试访问 `undefined` 的属性。逻辑错误是代码逻辑中的错误，导致结果不正确，但不会抛出错误。\n\n***\n\n## JavaScript 中不同类型的错误\n\n### 语法错误\n\n当代码不遵循 JavaScript 语言的规则时，就会发生语法错误。这些错误由 JavaScript 引擎在代码执行之前的解析阶段检测到。\n\n#### 示例\n\n```js live\nconsole.log(\"Hello, world!; // Missing closing quote and parenthesis\n```\n\n### 运行时错误\n\n运行时错误，也称为异常，发生在代码执行期间。当代码在语法上正确但遇到阻止其完成任务的问题时，就会发生这些错误。\n\n#### 示例\n\n```js live\nlet obj = null;\nconsole.log(obj.property); // TypeError: Cannot read properties of null (reading 'property')\n```\n\n### 逻辑错误\n\n逻辑错误是代码逻辑中的错误，导致结果不正确。这些错误不会抛出异常，而且通常是最难调试的，因为代码在没有任何问题的情况下运行，但会产生错误的输出。\n\n#### 示例\n\n```js live\nlet isAdmin = false;\n\nif ((isAdmin = true)) {\n  // Wrong: Assignment instead of comparison\n  console.log('Access granted'); // Access granted even though isAdmin was falsy\n} else {\n  console.log('Access denied');\n}\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Errors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)\n* [JavaScript.info: Error handling](https://javascript.info/error-handling)\n* [W3Schools: JavaScript Errors](https://www.w3schools.com/js/js_errors.asp)\n"
  },
  {
    "path": "questions/what-are-the-different-types-of-testing-in-software-development/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"96013da7\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"425c17a0\",\n        \"2a7816d0\",\n        \"120357d1\",\n        \"7c737123\",\n        \"9c8c89ac\",\n        \"5a670f69\",\n        \"ca7a8d03\",\n        \"6b219c29\",\n        \"278eecd1\",\n        \"67a428c7\",\n        \"58be317a\",\n        \"a3404d5c\",\n        \"a629f7e5\",\n        \"1f4770e5\",\n        \"13cbf083\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"425c17a0\",\n        \"2a7816d0\",\n        \"120357d1\",\n        \"7c737123\",\n        \"9c8c89ac\",\n        \"5a670f69\",\n        \"ca7a8d03\",\n        \"6b219c29\",\n        \"278eecd1\",\n        \"67a428c7\",\n        \"58be317a\",\n        \"a3404d5c\",\n        \"a629f7e5\",\n        \"1f4770e5\",\n        \"13cbf083\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-different-types-of-testing-in-software-development/en-US.mdx",
    "content": "---\ntitle: What are the different types of testing in software development?\n---\n\n## TL;DR\n\nIn software development, there are several types of testing to ensure the quality and functionality of the application. These include unit testing, integration testing, system testing, and acceptance testing. Unit testing focuses on individual components, integration testing checks the interaction between components, system testing evaluates the entire system, and acceptance testing ensures the software meets user requirements.\n\n---\n\n## Different types of testing in software development\n\n### Unit testing\n\nUnit testing involves testing individual components or functions of the software to ensure they work as expected. This type of testing is usually automated and written by developers.\n\n```js\n// Example of a unit test using Jest\nfunction add(a, b) {\n  return a + b;\n}\n\ntest('adds 1 + 2 to equal 3', () => {\n  expect(add(1, 2)).toBe(3);\n});\n```\n\n### Integration testing\n\nIntegration testing focuses on the interaction between different components or modules of the software. It ensures that combined parts of the application work together as intended.\n\n```js\n// Example of an integration test using Jest and Supertest\nconst request = require('supertest');\nconst app = require('./app'); // Your Express app\n\ntest('GET /users returns a list of users', async () => {\n  const response = await request(app).get('/users');\n  expect(response.status).toBe(200);\n  expect(response.body).toEqual(\n    expect.arrayContaining([\n      expect.objectContaining({ id: expect.any(Number) }),\n    ]),\n  );\n});\n```\n\n### System testing\n\nSystem testing evaluates the complete and integrated software system to verify that it meets the specified requirements. This type of testing is usually performed by QA teams.\n\n### Acceptance testing\n\nAcceptance testing, also known as user acceptance testing (UAT), is conducted to determine whether the software is ready for release. It ensures that the software meets the business requirements and is acceptable to the end-users.\n\n## Further reading\n\n- [Unit Testing - Wikipedia](https://en.wikipedia.org/wiki/Unit_testing)\n- [Integration Testing - Wikipedia](https://en.wikipedia.org/wiki/Integration_testing)\n- [System Testing - Wikipedia](https://en.wikipedia.org/wiki/System_testing)\n- [Acceptance Testing - Wikipedia](https://en.wikipedia.org/wiki/Acceptance_testing)\n"
  },
  {
    "path": "questions/what-are-the-different-types-of-testing-in-software-development/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-different-types-of-testing-in-software-development\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"testing\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Testing\"\n}\n"
  },
  {
    "path": "questions/what-are-the-different-types-of-testing-in-software-development/zh-CN.mdx",
    "content": "---\ntitle: 软件开发中不同类型的测试是什么？\n---\n\n## TL;DR\n\n在软件开发中，有几种类型的测试可以确保应用程序的质量和功能。这些包括单元测试、集成测试、系统测试和验收测试。单元测试侧重于单个组件，集成测试检查组件之间的交互，系统测试评估整个系统，验收测试确保软件满足用户需求。\n\n***\n\n## 软件开发中不同类型的测试\n\n### 单元测试\n\n单元测试涉及测试软件的单个组件或功能，以确保它们按预期工作。这种类型的测试通常是自动化的，由开发人员编写。\n\n```js\n// Example of a unit test using Jest\nfunction add(a, b) {\n  return a + b;\n}\n\ntest('adds 1 + 2 to equal 3', () => {\n  expect(add(1, 2)).toBe(3);\n});\n```\n\n### 集成测试\n\n集成测试侧重于软件的不同组件或模块之间的交互。它确保应用程序的组合部分按预期一起工作。\n\n```js\n// Example of an integration test using Jest and Supertest\nconst request = require('supertest');\nconst app = require('./app'); // Your Express app\n\ntest('GET /users returns a list of users', async () => {\n  const response = await request(app).get('/users');\n  expect(response.status).toBe(200);\n  expect(response.body).toEqual(\n    expect.arrayContaining([\n      expect.objectContaining({ id: expect.any(Number) }),\n    ]),\n  );\n});\n```\n\n### 系统测试\n\n系统测试评估完整且集成的软件系统，以验证它是否满足指定的需求。这种类型的测试通常由质量保证团队执行。\n\n### 验收测试\n\n验收测试，也称为用户验收测试 (UAT)，用于确定软件是否已准备好发布。它确保软件满足业务需求并被最终用户接受。\n\n## 延伸阅读\n\n* [单元测试 - 维基百科](https://en.wikipedia.org/wiki/Unit_testing)\n* [集成测试 - 维基百科](https://en.wikipedia.org/wiki/Integration_testing)\n* [系统测试 - 维基百科](https://en.wikipedia.org/wiki/System_testing)\n* [验收测试 - 维基百科](https://en.wikipedia.org/wiki/Acceptance_testing)\n"
  },
  {
    "path": "questions/what-are-the-different-ways-to-copy-an-object-or-an-array/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"7ffe2ceb\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"b764f942\",\n        \"b36751e4\",\n        \"2a7816d0\",\n        \"d7b3a8fa\",\n        \"7cbd2fa0\",\n        \"bddef431\",\n        \"56a145ef\",\n        \"7ed9237a\",\n        \"84a68ef4\",\n        \"b5d2df91\",\n        \"2fbc8059\",\n        \"4ee204dd\",\n        \"76489c99\",\n        \"2e3bff19\",\n        \"e4b0a65c\",\n        \"fc6ec995\",\n        \"7acc1178\",\n        \"ac5214a2\",\n        \"2155f1fd\",\n        \"e3abd0f4\",\n        \"b76d3176\",\n        \"c3d6d14f\",\n        \"1f4770e5\",\n        \"aba85142\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"b764f942\",\n        \"b36751e4\",\n        \"2a7816d0\",\n        \"d7b3a8fa\",\n        \"7cbd2fa0\",\n        \"bddef431\",\n        \"56a145ef\",\n        \"7ed9237a\",\n        \"84a68ef4\",\n        \"b5d2df91\",\n        \"2fbc8059\",\n        \"4ee204dd\",\n        \"76489c99\",\n        \"2e3bff19\",\n        \"e4b0a65c\",\n        \"fc6ec995\",\n        \"7acc1178\",\n        \"ac5214a2\",\n        \"2155f1fd\",\n        \"e3abd0f4\",\n        \"b76d3176\",\n        \"c3d6d14f\",\n        \"1f4770e5\",\n        \"aba85142\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-different-ways-to-copy-an-object-or-an-array/en-US.mdx",
    "content": "---\ntitle: What are the different ways to copy an object or an array?\n---\n\n## TL;DR\n\nTo copy an object or an array in JavaScript, you can use several methods. For shallow copies, you can use the spread operator (`...`) or `Object.assign()`. For deep copies, you can use `JSON.parse(JSON.stringify())` or libraries like Lodash's `_.cloneDeep()`.\n\n```js live\n// Shallow copy of an array\nconst originalArray = [1, 2, 3];\nconst shallowCopyArray = [...originalArray];\nconsole.log(shallowCopyArray); // [1, 2, 3]\n\n// Shallow copy of an object\nconst originalObject = { a: 1, b: 2 };\nconst shallowCopyObject = { ...originalObject };\nconsole.log(shallowCopyObject); // { a: 1, b: 2 };\n\n// Deep copy using JSON methods\nconst deepCopyObject = JSON.parse(JSON.stringify(originalObject));\nconsole.log(deepCopyObject); // { a: 1, b: 2 };\n```\n\n---\n\n## Different ways to copy an object or an array\n\n### Shallow copy\n\n#### Using the spread operator\n\nThe spread operator (`...`) is a concise way to create a shallow copy of an array or an object.\n\n```js live\n// Shallow copy of an array\nconst originalArray = [1, 2, 3];\nconst shallowCopyArray = [...originalArray];\nconsole.log(shallowCopyArray); // [1, 2, 3]\n\n// Shallow copy of an object\nconst originalObject = { a: 1, b: 2 };\nconst shallowCopyObject = { ...originalObject };\nconsole.log(shallowCopyObject); // { a: 1, b: 2 };\n```\n\n#### Using `Object.assign()`\n\n`Object.assign()` can also be used to create a shallow copy of an object.\n\n```js live\nconst originalObject = { a: 1, b: 2 };\nconst shallowCopyObject = Object.assign({}, originalObject);\nconsole.log(shallowCopyObject); // { a: 1, b: 2 };\n```\n\n### Deep copy\n\n#### Using `JSON.parse(JSON.stringify())`\n\nThis method is a simple way to create a deep copy of an object or an array. However, it has limitations, such as not handling functions, `undefined`, or circular references.\n\n```js live\nconst originalObject = { a: 1, b: { c: 2 } };\nconst deepCopyObject = JSON.parse(JSON.stringify(originalObject));\nconsole.log(deepCopyObject); // { a: 1, b: { c: 2 } }\n```\n\n#### Using Lodash's `_.cloneDeep()`\n\nLodash is a popular utility library that provides a `_.cloneDeep()` method for deep copying objects and arrays.\n\n```js\nconst _ = require('lodash');\nconst originalObject = { a: 1, b: { c: 2 } };\nconst deepCopyObject = _.cloneDeep(originalObject); // { a: 1, b: { c: 2 } }\n```\n\n### Other methods\n\n#### Using recursion\n\nFor custom deep copy logic, you can implement a recursive function.\n\n```js live\nfunction deepCopy(obj) {\n  if (obj === null || typeof obj !== 'object') {\n    return obj;\n  }\n\n  if (Array.isArray(obj)) {\n    return obj.map((item) => deepCopy(item));\n  }\n\n  const copy = {};\n  for (const key in obj) {\n    if (obj.hasOwnProperty(key)) {\n      copy[key] = deepCopy(obj[key]);\n    }\n  }\n  return copy;\n}\n\nconst originalObject = { a: 1, b: { c: 2 } };\nconst deepCopyObject = deepCopy(originalObject);\nconsole.log(deepCopyObject); // { a: 1, b: { c: 2 } }\n```\n\n## Further reading\n\n- [MDN Web Docs: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n- [MDN Web Docs: Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)\n- [Lodash documentation: \\_.cloneDeep](https://lodash.com/docs/4.17.15#cloneDeep)\n- [MDN Web Docs: JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)\n- [MDN Web Docs: JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)\n"
  },
  {
    "path": "questions/what-are-the-different-ways-to-copy-an-object-or-an-array/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-different-ways-to-copy-an-object-or-an-array\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/what-are-the-different-ways-to-copy-an-object-or-an-array/zh-CN.mdx",
    "content": "---\ntitle: 复制对象或数组的不同方法是什么？\n---\n\n## TL;DR\n\n在 JavaScript 中复制对象或数组，可以使用多种方法。对于浅拷贝，可以使用扩展运算符（`...`）或 `Object.assign()`。对于深拷贝，可以使用 `JSON.parse(JSON.stringify())` 或像 Lodash 的 `_.cloneDeep()` 这样的库。\n\n```js live\n// Shallow copy of an array\nconst originalArray = [1, 2, 3];\nconst shallowCopyArray = [...originalArray];\nconsole.log(shallowCopyArray); // [1, 2, 3]\n\n// Shallow copy of an object\nconst originalObject = { a: 1, b: 2 };\nconst shallowCopyObject = { ...originalObject };\nconsole.log(shallowCopyObject); // { a: 1, b: 2 };\n\n// Deep copy using JSON methods\nconst deepCopyObject = JSON.parse(JSON.stringify(originalObject));\nconsole.log(deepCopyObject); // { a: 1, b: 2 };\n```\n\n***\n\n## 复制对象或数组的不同方法\n\n### 浅拷贝\n\n#### 使用扩展运算符\n\n扩展运算符（`...`）是一种创建数组或对象浅拷贝的简洁方法。\n\n```js live\n// Shallow copy of an array\nconst originalArray = [1, 2, 3];\nconst shallowCopyArray = [...originalArray];\nconsole.log(shallowCopyArray); // [1, 2, 3]\n\n// Shallow copy of an object\nconst originalObject = { a: 1, b: 2 };\nconst shallowCopyObject = { ...originalObject };\nconsole.log(shallowCopyObject); // { a: 1, b: 2 };\n```\n\n#### 使用 `Object.assign()`\n\n`Object.assign()` 也可以用来创建对象的浅拷贝。\n\n```js live\nconst originalObject = { a: 1, b: 2 };\nconst shallowCopyObject = Object.assign({}, originalObject);\nconsole.log(shallowCopyObject); // { a: 1, b: 2 };\n```\n\n### 深拷贝\n\n#### 使用 `JSON.parse(JSON.stringify())`\n\n这种方法是一种创建对象或数组深拷贝的简单方法。但是，它也有局限性，例如无法处理函数、`undefined` 或循环引用。\n\n```js live\nconst originalObject = { a: 1, b: { c: 2 } };\nconst deepCopyObject = JSON.parse(JSON.stringify(originalObject));\nconsole.log(deepCopyObject); // { a: 1, b: { c: 2 } }\n```\n\n#### 使用 Lodash 的 `_.cloneDeep()`\n\nLodash 是一个流行的实用程序库，它提供了一个 `_.cloneDeep()` 方法，用于深拷贝对象和数组。\n\n```js\nconst _ = require('lodash');\nconst originalObject = { a: 1, b: { c: 2 } };\nconst deepCopyObject = _.cloneDeep(originalObject); // { a: 1, b: { c: 2 } }\n```\n\n### 其他方法\n\n#### 使用递归\n\n对于自定义深拷贝逻辑，您可以实现一个递归函数。\n\n```js live\nfunction deepCopy(obj) {\n  if (obj === null || typeof obj !== 'object') {\n    return obj;\n  }\n\n  if (Array.isArray(obj)) {\n    return obj.map((item) => deepCopy(item));\n  }\n\n  const copy = {};\n  for (const key in obj) {\n    if (obj.hasOwnProperty(key)) {\n      copy[key] = deepCopy(obj[key]);\n    }\n  }\n  return copy;\n}\n\nconst originalObject = { a: 1, b: { c: 2 } };\nconst deepCopyObject = deepCopy(originalObject);\nconsole.log(deepCopyObject); // { a: 1, b: { c: 2 } }\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n* [MDN Web Docs: Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)\n* [Lodash documentation: \\_.cloneDeep](https://lodash.com/docs/4.17.15#cloneDeep)\n* [MDN Web Docs: JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)\n* [MDN Web Docs: JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)\n"
  },
  {
    "path": "questions/what-are-the-different-ways-to-make-an-api-call-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"a05c5632\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"77bbf8c8\",\n        \"2a7816d0\",\n        \"56b6caef\",\n        \"da1990b\",\n        \"3765a30e\",\n        \"f6bb3f87\",\n        \"118a82b\",\n        \"41664e6e\",\n        \"5d1cfa00\",\n        \"b77c82f6\",\n        \"2ec369ec\",\n        \"8c7251c6\",\n        \"a0112883\",\n        \"27e0b7c\",\n        \"fd692c3a\",\n        \"1f4770e5\",\n        \"33dd52e4\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"77bbf8c8\",\n        \"2a7816d0\",\n        \"56b6caef\",\n        \"da1990b\",\n        \"3765a30e\",\n        \"f6bb3f87\",\n        \"118a82b\",\n        \"41664e6e\",\n        \"5d1cfa00\",\n        \"b77c82f6\",\n        \"2ec369ec\",\n        \"8c7251c6\",\n        \"a0112883\",\n        \"27e0b7c\",\n        \"fd692c3a\",\n        \"1f4770e5\",\n        \"33dd52e4\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-different-ways-to-make-an-api-call-in-javascript/en-US.mdx",
    "content": "---\ntitle: What are the different ways to make an API call in JavaScript?\n---\n\n## TL;DR\n\nIn JavaScript, you can make API calls using several methods. The most common ones are `XMLHttpRequest`, `fetch`, and third-party libraries like `Axios`. `XMLHttpRequest` is the traditional way but is more verbose. `fetch` is modern and returns promises, making it easier to work with. `Axios` is a popular third-party library that simplifies API calls and provides additional features.\n\n---\n\n## Different ways to make an API call in JavaScript\n\n### XMLHttpRequest\n\n`XMLHttpRequest` is the traditional way to make API calls in JavaScript. It is more verbose and requires more code compared to modern methods.\n\n```js live\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.onreadystatechange = function () {\n  if (xhr.readyState === 4 && xhr.status === 200) {\n    console.log(JSON.parse(xhr.responseText));\n  }\n};\nxhr.send();\n```\n\n### Fetch API\n\n`fetch` is a modern and more convenient way to make API calls. It returns a promise, making it easier to handle asynchronous operations.\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) =>\n    console.error('There was a problem with the fetch operation:', error),\n  );\n```\n\n### Axios\n\n`Axios` is a popular third-party library that simplifies making API calls. It provides additional features like interceptors, automatic JSON transformation, and more.\n\n```js\naxios\n  .get('https://api.example.com/data')\n  .then((response) => console.log(response.data))\n  .catch((error) =>\n    console.error('There was a problem with the Axios request:', error),\n  );\n```\n\n### jQuery AJAX\n\n`jQuery` also provides an `ajax` method to make API calls. This method is less common in modern development but still used in some legacy projects.\n\n```js\n$.ajax({\n  url: 'https://api.example.com/data',\n  method: 'GET',\n  success: function (data) {\n    console.log(data);\n  },\n  error: function (error) {\n    console.error('There was a problem with the jQuery AJAX request:', error);\n  },\n});\n```\n\n## Further reading\n\n- [MDN Web Docs: XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)\n- [MDN Web Docs: Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)\n- [Axios GitHub Repository](https://github.com/axios/axios)\n- [jQuery AJAX Documentation](https://api.jquery.com/jquery.ajax/)\n- [Practice 190+ JavaScript interview questions on GitHub](https://github.com/greatfrontend/top-javascript-interview-questions)\n"
  },
  {
    "path": "questions/what-are-the-different-ways-to-make-an-api-call-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-different-ways-to-make-an-api-call-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"networking\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Asynchronous JavaScript\"\n}\n"
  },
  {
    "path": "questions/what-are-the-different-ways-to-make-an-api-call-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中调用 API 的不同方法是什么？\n---\n\n## TL;DR\n\n在 JavaScript 中，您可以使用多种方法调用 API。最常见的方法是 `XMLHttpRequest`、`fetch` 和第三方库，如 `Axios`。`XMLHttpRequest` 是传统方法，但更冗长。`fetch` 是现代方法，返回 promise，使其更易于使用。`Axios` 是一个流行的第三方库，它简化了 API 调用并提供了附加功能。\n\n***\n\n## JavaScript 中调用 API 的不同方法\n\n### XMLHttpRequest\n\n`XMLHttpRequest` 是在 JavaScript 中调用 API 的传统方法。与现代方法相比，它更冗长，需要更多代码。\n\n```js live\nconst xhr = new XMLHttpRequest();\nxhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);\nxhr.onreadystatechange = function () {\n  if (xhr.readyState === 4 && xhr.status === 200) {\n    console.log(JSON.parse(xhr.responseText));\n  }\n};\nxhr.send();\n```\n\n### Fetch API\n\n`fetch` 是一种现代且更方便的调用 API 的方法。它返回一个 promise，使处理异步操作更容易。\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => {\n    if (!response.ok) {\n      throw new Error('Network response was not ok');\n    }\n    return response.json();\n  })\n  .then((data) => console.log(data))\n  .catch((error) =>\n    console.error('There was a problem with the fetch operation:', error),\n  );\n```\n\n### Axios\n\n`Axios` 是一个流行的第三方库，它简化了 API 调用。它提供了额外的功能，如拦截器、自动 JSON 转换等。\n\n```js\naxios\n  .get('https://api.example.com/data')\n  .then((response) => console.log(response.data))\n  .catch((error) =>\n    console.error('There was a problem with the Axios request:', error),\n  );\n```\n\n### jQuery AJAX\n\n`jQuery` 还提供了一个 `ajax` 方法来调用 API。这种方法在现代开发中不太常见，但在一些遗留项目中仍然使用。\n\n```js\n$.ajax({\n  url: 'https://api.example.com/data',\n  method: 'GET',\n  success: function (data) {\n    console.log(data);\n  },\n  error: function (error) {\n    console.error('There was a problem with the jQuery AJAX request:', error);\n  },\n});\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)\n* [MDN Web Docs: Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)\n* [Axios GitHub Repository](https://github.com/axios/axios)\n* [jQuery AJAX Documentation](https://api.jquery.com/jquery.ajax/)\n* [Practice 190+ JavaScript interview questions on GitHub](https://github.com/greatfrontend/top-javascript-interview-questions)\n"
  },
  {
    "path": "questions/what-are-the-metadata-fields-of-a-module/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"9150f443\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"eae06dbd\",\n        \"bf98a805\",\n        \"2a7816d0\",\n        \"f2aaa36a\",\n        \"6fba9db2\",\n        \"41885298\",\n        \"eb8b3f1f\",\n        \"a39b56a6\",\n        \"b964b7a2\",\n        \"1d8132b1\",\n        \"b35a5ee2\",\n        \"1d3a7ba9\",\n        \"994caf2b\",\n        \"2757be5\",\n        \"91c7b9c\",\n        \"dd3a8fda\",\n        \"bb46c920\",\n        \"584c6c35\",\n        \"7fc3a535\",\n        \"297eeaa9\",\n        \"4e7e8b9d\",\n        \"e9c9a201\",\n        \"81aff852\",\n        \"da0bbdf9\",\n        \"721352e\",\n        \"caffbaf1\",\n        \"1a25257c\",\n        \"7c108e1d\",\n        \"975f7ded\",\n        \"6efb263b\",\n        \"8222ceab\",\n        \"4f35942e\",\n        \"92e4c278\",\n        \"bf410d7d\",\n        \"361556d3\",\n        \"3e5d0c86\",\n        \"fbf8b106\",\n        \"8c82c5a1\",\n        \"24172596\",\n        \"1b6fa4f7\",\n        \"1f4770e5\",\n        \"5bf1555e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"eae06dbd\",\n        \"bf98a805\",\n        \"2a7816d0\",\n        \"f2aaa36a\",\n        \"6fba9db2\",\n        \"41885298\",\n        \"eb8b3f1f\",\n        \"a39b56a6\",\n        \"b964b7a2\",\n        \"1d8132b1\",\n        \"b35a5ee2\",\n        \"1d3a7ba9\",\n        \"994caf2b\",\n        \"2757be5\",\n        \"91c7b9c\",\n        \"dd3a8fda\",\n        \"bb46c920\",\n        \"584c6c35\",\n        \"7fc3a535\",\n        \"297eeaa9\",\n        \"4e7e8b9d\",\n        \"e9c9a201\",\n        \"81aff852\",\n        \"da0bbdf9\",\n        \"721352e\",\n        \"caffbaf1\",\n        \"1a25257c\",\n        \"7c108e1d\",\n        \"975f7ded\",\n        \"6efb263b\",\n        \"8222ceab\",\n        \"4f35942e\",\n        \"92e4c278\",\n        \"bf410d7d\",\n        \"361556d3\",\n        \"3e5d0c86\",\n        \"fbf8b106\",\n        \"8c82c5a1\",\n        \"24172596\",\n        \"1b6fa4f7\",\n        \"1f4770e5\",\n        \"5bf1555e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-metadata-fields-of-a-module/en-US.mdx",
    "content": "---\ntitle: What are the metadata fields of a module?\n---\n\n## TL;DR\n\nMetadata fields of a module typically include information such as the module's name, version, description, author, license, and dependencies. These fields are often found in a `package.json` file in JavaScript projects. For example:\n\n```json\n{\n  \"name\": \"my-module\",\n  \"version\": \"1.0.0\",\n  \"description\": \"A sample module\",\n  \"author\": \"John Doe\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"express\": \"^4.17.1\"\n  }\n}\n```\n\n---\n\n## Metadata fields of a module\n\n### Name\n\nThe `name` field specifies the name of the module. It is used to identify the module in the package registry and when it is installed as a dependency.\n\n```json\n{\n  \"name\": \"my-module\"\n}\n```\n\n### Version\n\nThe `version` field indicates the current version of the module. It follows semantic versioning (semver) guidelines.\n\n```json\n{\n  \"version\": \"1.0.0\"\n}\n```\n\n### Description\n\nThe `description` field provides a brief summary of what the module does. This is useful for users browsing the package registry.\n\n```json\n{\n  \"description\": \"A sample module\"\n}\n```\n\n### Author\n\nThe `author` field specifies the name and contact information of the module's author.\n\n```json\n{\n  \"author\": \"John Doe\"\n}\n```\n\n### License\n\nThe `license` field indicates the licensing terms under which the module can be used. Common licenses include MIT, Apache-2.0, and GPL-3.0.\n\n```json\n{\n  \"license\": \"MIT\"\n}\n```\n\n### Dependencies\n\nThe `dependencies` field lists other modules that the current module depends on to work correctly. Each dependency is specified with its name and version range.\n\n```json\n{\n  \"dependencies\": {\n    \"express\": \"^4.17.1\"\n  }\n}\n```\n\n### DevDependencies\n\nThe `devDependencies` field lists modules that are only needed for development and testing, not for production.\n\n```json\n{\n  \"devDependencies\": {\n    \"jest\": \"^26.6.3\"\n  }\n}\n```\n\n### Scripts\n\nThe `scripts` field allows you to define script commands that can be run using `npm run <script-name>`.\n\n```json\n{\n  \"scripts\": {\n    \"start\": \"node index.js\",\n    \"test\": \"jest\"\n  }\n}\n```\n\n### Keywords\n\nThe `keywords` field is an array of strings that help users find the module when searching in the package registry.\n\n```json\n{\n  \"keywords\": [\"sample\", \"module\", \"example\"]\n}\n```\n\n### Repository\n\nThe `repository` field provides information about the source code repository for the module.\n\n```json\n{\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/username/my-module.git\"\n  }\n}\n```\n\n### Bugs\n\nThe `bugs` field provides information on where to report issues with the module.\n\n```json\n{\n  \"bugs\": {\n    \"url\": \"https://github.com/username/my-module/issues\"\n  }\n}\n```\n\n### Homepage\n\nThe `homepage` field specifies the URL of the module's homepage.\n\n```json\n{\n  \"homepage\": \"https://github.com/username/my-module#readme\"\n}\n```\n\n## Further reading\n\n- [npm package.json documentation](https://docs.npmjs.com/cli/v7/configuring-npm/package-json)\n- [Semantic Versioning](https://semver.org/)\n- [CommonJS Modules](https://nodejs.org/docs/latest/api/modules.html)\n"
  },
  {
    "path": "questions/what-are-the-metadata-fields-of-a-module/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-metadata-fields-of-a-module\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Modules\"\n}\n"
  },
  {
    "path": "questions/what-are-the-metadata-fields-of-a-module/zh-CN.mdx",
    "content": "---\ntitle: 模块的元数据字段是什么？\n---\n\n## TL;DR\n\n模块的元数据字段通常包括模块的名称、版本、描述、作者、许可证和依赖项等信息。这些字段通常在 JavaScript 项目的 `package.json` 文件中找到。例如：\n\n```json\n{\n  \"name\": \"my-module\",\n  \"version\": \"1.0.0\",\n  \"description\": \"A sample module\",\n  \"author\": \"John Doe\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"express\": \"^4.17.1\"\n  }\n}\n```\n\n***\n\n## 模块的元数据字段\n\n### 名称\n\n``name`` 字段指定模块的名称。它用于在包注册表中标识模块，以及将其作为依赖项安装时。\n\n```json\n{\n  \"name\": \"my-module\"\n}\n```\n\n### 版本\n\n``version`` 字段指示模块的当前版本。它遵循语义版本控制 (semver) 指导方针。\n\n```json\n{\n  \"version\": \"1.0.0\"\n}\n```\n\n### 描述\n\n``description`` 字段简要概述了模块的功能。这对于浏览包注册表的用户很有用。\n\n```json\n{\n  \"description\": \"A sample module\"\n}\n```\n\n### 作者\n\n``author`` 字段指定模块作者的姓名和联系信息。\n\n```json\n{\n  \"author\": \"John Doe\"\n}\n```\n\n### 许可证\n\n`license` 字段指示可以使用该模块的许可条款。 常见的许可证包括 MIT、Apache-2.0 和 GPL-3.0。\n\n```json\n{\n  \"license\": \"MIT\"\n}\n```\n\n### 依赖项\n\n`dependencies` 字段列出了当前模块正常工作所依赖的其他模块。 每个依赖项都使用其名称和版本范围指定。\n\n```json\n{\n  \"dependencies\": {\n    \"express\": \"^4.17.1\"\n  }\n}\n```\n\n### DevDependencies\n\n`devDependencies` 字段列出了仅用于开发和测试的模块，而不是用于生产环境。\n\n```json\n{\n  \"devDependencies\": {\n    \"jest\": \"^26.6.3\"\n  }\n}\n```\n\n### 脚本\n\n`scripts` 字段允许您定义可以使用 `npm run <script-name>` 运行的脚本命令。\n\n```json\n{\n  \"scripts\": {\n    \"start\": \"node index.js\",\n    \"test\": \"jest\"\n  }\n}\n```\n\n### 关键词\n\n`keywords` 字段是一个字符串数组，可帮助用户在包注册表中搜索时找到该模块。\n\n```json\n{\n  \"keywords\": [\"sample\", \"module\", \"example\"]\n}\n```\n\n### 存储库\n\n`repository` 字段提供有关模块源代码存储库的信息。\n\n```json\n{\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/username/my-module.git\"\n  }\n}\n```\n\n### Bugs\n\n`bugs` 字段提供有关在哪里报告模块问题的相关信息。\n\n```json\n{\n  \"bugs\": {\n    \"url\": \"https://github.com/username/my-module/issues\"\n  }\n}\n```\n\n### 主页\n\n``homepage`` 字段指定模块主页的 URL。\n\n```json\n{\n  \"homepage\": \"https://github.com/username/my-module#readme\"\n}\n```\n\n## 延伸阅读\n\n* [npm package.json documentation](https://docs.npmjs.com/cli/v7/configuring-npm/package-json)\n* [Semantic Versioning](https://semver.org/)\n* [CommonJS Modules](https://nodejs.org/docs/latest/api/modules.html)\n"
  },
  {
    "path": "questions/what-are-the-potential-issues-caused-by-hoisting/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"6eba2a9b\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"31974a8d\",\n        \"4a7ee626\",\n        \"2a7816d0\",\n        \"ea5986\",\n        \"a68d98f3\",\n        \"c0348e7d\",\n        \"76160559\",\n        \"99ce9069\",\n        \"73ce0b88\",\n        \"3fbbfd7\",\n        \"88f06e97\",\n        \"57c7cb7d\",\n        \"8b4c4ae9\",\n        \"9ade64f2\",\n        \"ff201ac3\",\n        \"3b467292\",\n        \"1f4770e5\",\n        \"4a6a1cdc\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"31974a8d\",\n        \"4a7ee626\",\n        \"2a7816d0\",\n        \"ea5986\",\n        \"a68d98f3\",\n        \"c0348e7d\",\n        \"76160559\",\n        \"99ce9069\",\n        \"73ce0b88\",\n        \"3fbbfd7\",\n        \"88f06e97\",\n        \"57c7cb7d\",\n        \"8b4c4ae9\",\n        \"9ade64f2\",\n        \"ff201ac3\",\n        \"3b467292\",\n        \"1f4770e5\",\n        \"4a6a1cdc\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-potential-issues-caused-by-hoisting/en-US.mdx",
    "content": "---\ntitle: What are the potential issues caused by hoisting?\n---\n\n## TL;DR\n\nHoisting can lead to unexpected behavior in JavaScript because variable and function declarations are moved to the top of their containing scope during the compilation phase. This can result in `undefined` values for variables if they are used before their declaration and can cause confusion with function declarations and expressions. For example:\n\n```js live\nconsole.log(a); // undefined\nvar a = 5;\n\nconsole.log(b); // ReferenceError: Cannot access 'b' before initialization\nlet b = 10;\n```\n\n---\n\n## Potential issues caused by hoisting\n\n### Variables being `undefined`\n\nWhen using `var`, the variable is hoisted to the top of its scope but not initialized. This means you can reference the variable before its declaration, but it will be `undefined` until the assignment is executed.\n\n```js live\nconsole.log(a); // undefined\nvar a = 5;\n```\n\n### Temporal dead zone with `let` and `const`\n\nVariables declared with `let` and `const` are also hoisted, but they are not initialized. Accessing them before their declaration results in a `ReferenceError` due to the temporal dead zone.\n\n```js live\nconsole.log(b); // ReferenceError: Cannot access 'b' before initialization\nlet b = 10;\n```\n\n### Function declarations vs. function expressions\n\nFunction declarations are hoisted entirely, meaning you can call the function before its declaration. However, function expressions are not hoisted in the same way, leading to potential `TypeError` if called before they are defined.\n\n```js live\nfoo(); // Works fine\nfunction foo() {\n  console.log('Hello');\n}\n\nbar(); // TypeError: bar is not a function\nvar bar = function () {\n  console.log('Hello');\n};\n```\n\n### Redeclaration issues with `var`\n\nUsing `var` can lead to unintentional redeclarations, which can cause bugs that are hard to track down.\n\n```js live\nvar x = 1;\nif (true) {\n  var x = 2; // Same variable as above\n}\nconsole.log(x); // 2\n```\n\n## Further reading\n\n- [MDN Web Docs on Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)\n- [JavaScript.info on Hoisting](https://javascript.info/var)\n- [Understanding the Temporal Dead Zone](https://medium.com/@rajeshnaroth/understanding-temporal-dead-zone-in-javascript-let-and-const-5c3d2f8e0e68)\n"
  },
  {
    "path": "questions/what-are-the-potential-issues-caused-by-hoisting/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-potential-issues-caused-by-hoisting\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Hoisting\"\n}\n"
  },
  {
    "path": "questions/what-are-the-potential-issues-caused-by-hoisting/zh-CN.mdx",
    "content": "---\ntitle: Hoisting 带来的潜在问题是什么？\n---\n\n## TL;DR\n\nHoisting 可能会导致 JavaScript 中出现意外行为，因为变量和函数声明在编译阶段被移至其包含范围的顶部。如果变量在其声明之前被使用，这可能导致变量值为 `undefined`，并且可能导致函数声明和表达式的混淆。例如：\n\n```js live\nconsole.log(a); // undefined\nvar a = 5;\n\nconsole.log(b); // ReferenceError: Cannot access 'b' before initialization\nlet b = 10;\n```\n\n***\n\n## Hoisting 带来的潜在问题\n\n### 变量为 `undefined`\n\n使用 `var` 时，变量会被提升到其作用域的顶部，但未被初始化。这意味着您可以在变量声明之前引用该变量，但在赋值执行之前，它将是 `undefined`。\n\n```js live\nconsole.log(a); // undefined\nvar a = 5;\n```\n\n### `let` 和 `const` 的暂时性死区\n\n使用 `let` 和 `const` 声明的变量也会被提升，但它们没有被初始化。在声明之前访问它们会导致 `ReferenceError`，这是由于暂时性死区造成的。\n\n```js live\nconsole.log(b); // ReferenceError: Cannot access 'b' before initialization\nlet b = 10;\n```\n\n### 函数声明 vs. 函数表达式\n\n函数声明被完全提升，这意味着您可以在函数声明之前调用该函数。但是，函数表达式不会以相同的方式被提升，如果在定义之前调用它们，则会导致潜在的 `TypeError`。\n\n```js live\nfoo(); // Works fine\nfunction foo() {\n  console.log('Hello');\n}\n\nbar(); // TypeError: bar is not a function\nvar bar = function () {\n  console.log('Hello');\n};\n```\n\n### `var` 的重新声明问题\n\n使用 `var` 可能会导致意外的重新声明，这可能会导致难以追踪的错误。\n\n```js live\nvar x = 1;\nif (true) {\n  var x = 2; // Same variable as above\n}\nconsole.log(x); // 2\n```\n\n## 延伸阅读\n\n* [MDN Web Docs on Hoisting](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting)\n* [JavaScript.info on Hoisting](https://javascript.info/var)\n* [Understanding the Temporal Dead Zone](https://medium.com/@rajeshnaroth/understanding-temporal-dead-zone-in-javascript-let-and-const-5c3d2f8e0e68)\n"
  },
  {
    "path": "questions/what-are-the-potential-pitfalls-of-using-closures/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"faddceb\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"1827d0a8\",\n        \"2a7816d0\",\n        \"45e5f525\",\n        \"ad0dfb4f\",\n        \"2b4a7ad2\",\n        \"eb6c5021\",\n        \"622ca716\",\n        \"b8dedcfd\",\n        \"43a37ead\",\n        \"cd5858c6\",\n        \"6dce026f\",\n        \"3fa1cf80\",\n        \"79dd11db\",\n        \"637ec0f5\",\n        \"8a9872d4\",\n        \"84ab4ec7\",\n        \"405a3f3b\",\n        \"1f4770e5\",\n        \"ae07300f\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"1827d0a8\",\n        \"2a7816d0\",\n        \"45e5f525\",\n        \"ad0dfb4f\",\n        \"2b4a7ad2\",\n        \"eb6c5021\",\n        \"622ca716\",\n        \"b8dedcfd\",\n        \"43a37ead\",\n        \"cd5858c6\",\n        \"6dce026f\",\n        \"3fa1cf80\",\n        \"79dd11db\",\n        \"637ec0f5\",\n        \"8a9872d4\",\n        \"84ab4ec7\",\n        \"405a3f3b\",\n        \"1f4770e5\",\n        \"ae07300f\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-potential-pitfalls-of-using-closures/en-US.mdx",
    "content": "---\ntitle: What are the potential pitfalls of using closures?\n---\n\n## TL;DR\n\nClosures can lead to memory leaks if not managed properly, especially when they capture variables that are no longer needed. They can also make debugging more difficult due to the complexity of the scope chain. Additionally, closures can cause performance issues if they are overused or used inappropriately, as they keep references to variables in their scope, which can prevent garbage collection.\n\n---\n\n## Potential pitfalls of using closures\n\n### Memory leaks\n\nClosures can cause memory leaks if they capture variables that are no longer needed. This happens because closures keep references to the variables in their scope, preventing the garbage collector from freeing up memory.\n\n```js live\nfunction createClosure() {\n  let largeArray = new Array(1000000).fill('some data');\n  return function () {\n    console.log(largeArray[0]);\n  };\n}\n\nlet closure = createClosure();\n// The largeArray is still in memory because the closure keeps a reference to it\nclosure(); // Output: 'some data'\n```\n\n### Debugging complexity\n\nClosures can make debugging more difficult due to the complexity of the scope chain. When a bug occurs, it can be challenging to trace the source of the problem through multiple layers of nested functions and scopes.\n\n```js live\nfunction outerFunction() {\n  let outerVar = 'I am outside!';\n\n  function innerFunction() {\n    console.log(outerVar); // What if outerVar is not what you expect?\n  }\n\n  return innerFunction;\n}\n\nlet myFunction = outerFunction();\nmyFunction(); // Output: 'I am outside!'\n```\n\n### Performance issues\n\nOverusing closures or using them inappropriately can lead to performance issues. Since closures keep references to variables in their scope, they can prevent garbage collection, leading to increased memory usage and potential slowdowns.\n\n```js live\nfunction createManyClosures() {\n  let counter = 0;\n\n  for (let i = 0; i < 1000000; i++) {\n    (function () {\n      counter++;\n    })();\n    // The closure is executed immediately, but it still holds onto the reference to the `counter` variable\n    // This prevents the counter from being garbage collected\n  }\n\n  console.log(counter); // This can be inefficient\n}\n\ncreateManyClosures();\n```\n\n### Unintended variable sharing\n\nClosures can lead to unintended variable sharing, especially in loops. This happens when all closures share the same reference to a variable, leading to unexpected behavior.\n\n```js live\nfunction createFunctions() {\n  let functions = [];\n\n  for (var i = 0; i < 3; i++) {\n    functions.push(function () {\n      console.log(i); // All functions will log the same value of i\n    });\n  }\n\n  return functions;\n}\n\nlet funcs = createFunctions();\nfuncs[0](); // 3\nfuncs[1](); // 3\nfuncs[2](); // 3\n```\n\nTo avoid this, use `let` instead of `var` to create a new binding for each iteration:\n\n```js live\nfunction createFunctions() {\n  let functions = [];\n\n  for (let i = 0; i < 3; i++) {\n    functions.push(function () {\n      console.log(i); // Each function will log its own value of i\n    });\n  }\n\n  return functions;\n}\n\nlet funcs = createFunctions();\nfuncs[0](); // 0\nfuncs[1](); // 1\nfuncs[2](); // 2\n```\n\n## Further reading\n\n- [MDN Web Docs: Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n- [JavaScript.info: Closures](https://javascript.info/closure)\n- [Understanding JavaScript Closures with Ease](https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8)\n"
  },
  {
    "path": "questions/what-are-the-potential-pitfalls-of-using-closures/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-potential-pitfalls-of-using-closures\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"closure\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Closures & Scope\"\n}\n"
  },
  {
    "path": "questions/what-are-the-potential-pitfalls-of-using-closures/zh-CN.mdx",
    "content": "---\ntitle: 使用闭包的潜在陷阱是什么？\n---\n\n## TL;DR\n\n如果管理不当，闭包可能导致内存泄漏，尤其是在捕获不再需要的变量时。由于作用域链的复杂性，它们也可能使调试更加困难。此外，如果过度使用或不当使用闭包，它们可能会导致性能问题，因为它们保留对其作用域中变量的引用，这可能会阻止垃圾回收。\n\n***\n\n## 使用闭包的潜在陷阱\n\n### 内存泄漏\n\n如果闭包捕获不再需要的变量，则可能导致内存泄漏。发生这种情况是因为闭包保留对其作用域中变量的引用，从而阻止垃圾回收器释放内存。\n\n```js live\nfunction createClosure() {\n  let largeArray = new Array(1000000).fill('some data');\n  return function () {\n    console.log(largeArray[0]);\n  };\n}\n\nlet closure = createClosure();\n// The largeArray is still in memory because the closure keeps a reference to it\nclosure(); // Output: 'some data'\n```\n\n### 调试复杂性\n\n由于作用域链的复杂性，闭包会使调试更加困难。当发生错误时，通过多层嵌套函数和作用域来追踪问题的根源可能具有挑战性。\n\n```js live\nfunction outerFunction() {\n  let outerVar = 'I am outside!';\n\n  function innerFunction() {\n    console.log(outerVar); // What if outerVar is not what you expect?\n  }\n\n  return innerFunction;\n}\n\nlet myFunction = outerFunction();\nmyFunction(); // Output: 'I am outside!'\n```\n\n### 性能问题\n\n过度使用或不当使用闭包可能导致性能问题。由于闭包保留对其作用域中变量的引用，它们可能会阻止垃圾回收，从而导致内存使用量增加和潜在的减速。\n\n```js live\nfunction createManyClosures() {\n  let counter = 0;\n\n  for (let i = 0; i < 1000000; i++) {\n    (function () {\n      counter++;\n    })();\n    // The closure is executed immediately, but it still holds onto the reference to the `counter` variable\n    // This prevents the counter from being garbage collected\n  }\n\n  console.log(counter); // This can be inefficient\n}\n\ncreateManyClosures();\n```\n\n### 意外的变量共享\n\n闭包可能导致意外的变量共享，尤其是在循环中。当所有闭包共享对变量的相同引用时，就会发生这种情况，从而导致意外行为。\n\n```js live\nfunction createFunctions() {\n  let functions = [];\n\n  for (var i = 0; i < 3; i++) {\n    functions.push(function () {\n      console.log(i); // All functions will log the same value of i\n    });\n  }\n\n  return functions;\n}\n\nlet funcs = createFunctions();\nfuncs[0](); // 3\nfuncs[1](); // 3\nfuncs[2](); // 3\n```\n\n为了避免这种情况，请使用 `let` 而不是 `var` 来为每次迭代创建一个新的绑定：\n\n```js live\nfunction createFunctions() {\n  let functions = [];\n\n  for (let i = 0; i < 3; i++) {\n    functions.push(function () {\n      console.log(i); // Each function will log its own value of i\n    });\n  }\n\n  return functions;\n}\n\nlet funcs = createFunctions();\nfuncs[0](); // 0\nfuncs[1](); // 1\nfuncs[2](); // 2\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n* [JavaScript.info: Closures](https://javascript.info/closure)\n* [Understanding JavaScript Closures with Ease](https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8)\n"
  },
  {
    "path": "questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"c412ba2d\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"7fa026bc\",\n        \"2a7816d0\",\n        \"512a28be\",\n        \"d764361a\",\n        \"d9b093d7\",\n        \"4ebb1ee2\",\n        \"b5b10340\",\n        \"63feabd\",\n        \"3592fac\",\n        \"8e710086\",\n        \"67266c1d\",\n        \"d9474d27\",\n        \"8ce1b750\",\n        \"f41597bd\",\n        \"7e9ebd41\",\n        \"610c4a30\",\n        \"a5cdccec\",\n        \"4aac36ab\",\n        \"5fe5bc4d\",\n        \"13797f10\",\n        \"9fbbe7b8\",\n        \"45da4e57\",\n        \"1f4ed4b1\",\n        \"1f4770e5\",\n        \"2f7d9128\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"7fa026bc\",\n        \"2a7816d0\",\n        \"512a28be\",\n        \"d764361a\",\n        \"d9b093d7\",\n        \"4ebb1ee2\",\n        \"b5b10340\",\n        \"63feabd\",\n        \"3592fac\",\n        \"8e710086\",\n        \"67266c1d\",\n        \"d9474d27\",\n        \"8ce1b750\",\n        \"f41597bd\",\n        \"7e9ebd41\",\n        \"610c4a30\",\n        \"a5cdccec\",\n        \"4aac36ab\",\n        \"5fe5bc4d\",\n        \"13797f10\",\n        \"9fbbe7b8\",\n        \"45da4e57\",\n        \"1f4ed4b1\",\n        \"1f4770e5\",\n        \"2f7d9128\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/en-US.mdx",
    "content": "---\ntitle: What are the pros and cons of using Promises instead of callbacks in JavaScript?\n---\n\n## TL;DR\n\nPromises offer a cleaner alternative to callbacks, helping to avoid callback hell and making asynchronous code more readable. They facilitate writing sequential and parallel asynchronous operations with ease. However, using promises may introduce slightly more complex code.\n\n---\n\n## Pros\n\n### Avoid callback hell which can be unreadable.\n\nCallback hell, also known as the \"pyramid of doom,\" is a phenomenon that occurs when you have multiple nested callbacks in your code. This can lead to code that is difficult to read, maintain, and debug. Here's an example of callback hell:\n\n```js live\nfunction getFirstData(callback) {\n  setTimeout(() => {\n    callback({ id: 1, title: 'First Data' });\n  }, 1000);\n}\n\nfunction getSecondData(data, callback) {\n  setTimeout(() => {\n    callback({ id: data.id, title: data.title + ' Second Data' });\n  }, 1000);\n}\n\nfunction getThirdData(data, callback) {\n  setTimeout(() => {\n    callback({ id: data.id, title: data.title + ' Third Data' });\n  }, 1000);\n}\n\n// Callback hell\ngetFirstData((data) => {\n  getSecondData(data, (data) => {\n    getThirdData(data, (result) => {\n      console.log(result); // Output: {id: 1, title: \"First Data Second Data Third Data\"}\n    });\n  });\n});\n```\n\nPromises address the problem of callback hell by providing a more linear and readable structure for your code.\n\n```js live\n// Example of sequential asynchronous code using setTimeout and Promises\nfunction getFirstData() {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: 1, title: 'First Data' });\n    }, 1000);\n  });\n}\n\nfunction getSecondData(data) {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: data.id, title: data.title + ' Second Data' });\n    }, 1000);\n  });\n}\n\nfunction getThirdData(data) {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: data.id, title: data.title + ' Third Data' });\n    }, 1000);\n  });\n}\n\ngetFirstData()\n  .then(getSecondData)\n  .then(getThirdData)\n  .then((data) => {\n    console.log(data); // Output: {id: 1, title: \"First Data Second Data Third Data\"}\n  })\n  .catch((error) => console.error('Error:', error));\n```\n\n### Makes it easy to write sequential asynchronous code that is readable with `.then()`.\n\nIn the above code example, we use `.then()` method to chain these Promises together, allowing the code to execute sequentially. It provides a cleaner and more manageable way to handle asynchronous operations in JavaScript.\n\n### Makes it easy to write parallel asynchronous code with `Promise.all()`.\n\nBoth `Promise.all()` and callbacks can be used to write parallel asynchronous code. However, `Promise.all()` provides a more concise and readable way to handle multiple Promises, especially when dealing with complex asynchronous workflows.\n\n```js live\nfunction getData1() {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: 1, title: 'Data 1' });\n    }, 1000);\n  });\n}\n\nfunction getData2() {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: 2, title: 'Data 2' });\n    }, 1000);\n  });\n}\n\nfunction getData3() {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: 3, title: 'Data 3' });\n    }, 1000);\n  });\n}\n\nPromise.all([getData1(), getData2(), getData3()])\n  .then((results) => {\n    console.log(results); // Output: [{ id: 1, title: 'Data 1' }, { id: 2, title: 'Data 2' }, { id: 3, title: 'Data 3' }]\n  })\n  .catch((error) => {\n    console.error('Error:', error);\n  });\n```\n\n### Easier error handling with `.catch()` and guaranteed cleanup with `.finally()`\n\nPromises make error handling more straightforward by allowing you to catch errors at the end of a chain using `.catch()`, instead of manually checking for errors in every callback. This leads to cleaner and more maintainable code.\n\nAdditionally, `.finally()` lets you run code after the Promise settles, whether it was successful or failed, which is great for cleanup tasks like hiding spinners or resetting UI states.\n\n```js live\nfunction getFirstData() {\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve({ id: 1, title: 'First Data' });\n    }, 1000);\n  });\n}\n\nfunction getSecondData(data) {\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve({ id: data.id, title: data.title + ' -> Second Data' });\n    }, 1000);\n  });\n}\n\ngetFirstData()\n  .then(getSecondData)\n  .then((data) => {\n    console.log('Success:', data);\n  })\n  .catch((error) => {\n    console.error('Error:', error);\n  })\n  .finally(() => {\n    console.log('This runs no matter what');\n  });\n```\n\n### With promises, these scenarios which are present in callbacks-only coding, will not happen:\n\n- Call the callback too early\n- Call the callback too late (or never)\n- Call the callback too few or too many times\n- Fail to pass along any necessary environment/parameters\n- Swallow any errors/exceptions that may happen\n\n## Cons\n\n- Slightly more complex code (debatable).\n\n## Practice\n\n- Try implementing your own [`Promise.resolve()` method](/questions/javascript/promise-resolve), [`Promise.reject()` method](/questions/javascript/promise-reject) and [`Promise.all()` method](/questions/javascript/promise-all) on GreatFrontEnd.\n\n## Further reading\n\n- [Promise | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\n- [Callback function | MDN](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function)\n"
  },
  {
    "path": "questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks\",\n  \"languages\": [],\n  \"companies\": [\"linkedin\", \"google\", \"amazon\", \"bytedance\", \"atlassian\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"async\", \"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 260,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/pt-BR.mdx",
    "content": "---\ntitle: Quais são os prós e contras de usar Promises em vez de callbacks?\n---\n\n## Prós\n\n- Evite o \"callback hell\", que pode ser ilegível.\n- Facilita a escrita de código assíncrono sequencial que é legívell com `.then()`.\n- Facilita a escrita paralela de código assíncrono com `Promise.all()`.\n- Com promessas, esses cenários que estão presentes em código somente com retorno de chamada não ocorrerão:\n  - Chamar a função de retorno de chamada muito cedo\n  - Chamar a função de retorno de chamada tarde demais (ou nunca)\n  - Chamar a função de retorno de chamada poucas ou muitas vezes\n  - Falhar em passar qualquer ambiente/parâmetros necessários para a função de retorno de chamada\n  - Ignorar quaisquer erros/exceções que possam ocorrer\n\n## Contras\n\n- O código pode se tornar ligeiramente mais complexo (isso pode ser discutível).\n- Em navegadores mais antigos onde ES2015 não é suportado, é necessário carregar um polyfill para poder usá-lo.\n"
  },
  {
    "path": "questions/what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks/zh-CN.mdx",
    "content": "---\ntitle: 在 JavaScript 中使用 Promise 而不是回调有什么优缺点？\n---\n\n## TL;DR\n\nPromise 提供了一种比回调更简洁的替代方案，有助于避免回调地狱，并使异步代码更具可读性。它们有助于轻松编写顺序和并行的异步操作。但是，使用 Promise 可能会引入稍微复杂的代码。\n\n***\n\n## 优点\n\n### 避免难以阅读的回调地狱。\n\n回调地狱，也称为“厄运金字塔”，是指在代码中具有多个嵌套回调时发生的现象。这可能导致代码难以阅读、维护和调试。以下是回调地狱的示例：\n\n```js live\nfunction getFirstData(callback) {\n  setTimeout(() => {\n    callback({ id: 1, title: 'First Data' });\n  }, 1000);\n}\n\nfunction getSecondData(data, callback) {\n  setTimeout(() => {\n    callback({ id: data.id, title: data.title + ' Second Data' });\n  }, 1000);\n}\n\nfunction getThirdData(data, callback) {\n  setTimeout(() => {\n    callback({ id: data.id, title: data.title + ' Third Data' });\n  }, 1000);\n}\n\n// Callback hell\ngetFirstData((data) => {\n  getSecondData(data, (data) => {\n    getThirdData(data, (result) => {\n      console.log(result); // Output: {id: 1, title: \"First Data Second Data Third Data\"}\n    });\n  });\n});\n```\n\nPromise 通过为代码提供更线性和可读的结构来解决回调地狱的问题。\n\n```js live\n// Example of sequential asynchronous code using setTimeout and Promises\nfunction getFirstData() {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: 1, title: 'First Data' });\n    }, 1000);\n  });\n}\n\nfunction getSecondData(data) {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: data.id, title: data.title + ' Second Data' });\n    }, 1000);\n  });\n}\n\nfunction getThirdData(data) {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: data.id, title: data.title + ' Third Data' });\n    }, 1000);\n  });\n}\n\ngetFirstData()\n  .then(getSecondData)\n  .then(getThirdData)\n  .then((data) => {\n    console.log(data); // Output: {id: 1, title: \"First Data Second Data Third Data\"}\n  })\n  .catch((error) => console.error('Error:', error));\n```\n\n### 使用 `.then()` 轻松编写可读的顺序异步代码。\n\n在上面的代码示例中，我们使用 `.then()` 方法将这些 Promise 链接在一起，从而允许代码按顺序执行。它提供了一种更简洁、更易于管理的方式来处理 JavaScript 中的异步操作。\n\n### 使用 `Promise.all()` 轻松编写并行异步代码。\n\n`Promise.all()` 和回调都可以用于编写并行异步代码。但是，`Promise.all()` 提供了一种更简洁、更易读的方式来处理多个 Promise，尤其是在处理复杂的异步工作流程时。\n\n```js live\nfunction getData1() {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: 1, title: 'Data 1' });\n    }, 1000);\n  });\n}\n\nfunction getData2() {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: 2, title: 'Data 2' });\n    }, 1000);\n  });\n}\n\nfunction getData3() {\n  return new Promise((resolve, reject) => {\n    setTimeout(() => {\n      resolve({ id: 3, title: 'Data 3' });\n    }, 1000);\n  });\n}\n\nPromise.all([getData1(), getData2(), getData3()])\n  .then((results) => {\n    console.log(results); // Output: [{ id: 1, title: 'Data 1' }, { id: 2, title: 'Data 2' }, { id: 3, title: 'Data 3' }]\n  })\n  .catch((error) => {\n    console.error('Error:', error);\n  });\n```\n\n### 使用`.catch()`更容易处理错误，使用`.finally()`保证清理\n\nPromise 通过允许您在链的末尾使用`.catch()`捕获错误，而不是在每个回调中手动检查错误，从而使错误处理更加简单。这使得代码更简洁、更易于维护。\n\n此外，`.finally()` 允许您在 Promise 确定后运行代码，无论它是否成功，这对于清理任务（如隐藏微调器或重置 UI 状态）非常有用。\n\n```js live\nfunction getFirstData() {\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve({ id: 1, title: 'First Data' });\n    }, 1000);\n  });\n}\n\nfunction getSecondData(data) {\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve({ id: data.id, title: data.title + ' -> Second Data' });\n    }, 1000);\n  });\n}\n\ngetFirstData()\n  .then(getSecondData)\n  .then((data) => {\n    console.log('Success:', data);\n  })\n  .catch((error) => {\n    console.error('Error:', error);\n  })\n  .finally(() => {\n    console.log('This runs no matter what');\n  });\n```\n\n### 使用 Promise，以下情况不会发生，这些情况存在于仅使用回调的编码中：\n\n* 过早调用回调\n* 过晚调用回调（或从不调用）\n* 调用回调的次数太少或太多\n* 未能传递任何必要的环境/参数\n* 吞噬可能发生的任何错误/异常\n\n## 缺点\n\n* 稍微复杂的代码（有争议）。\n\n## 实践\n\n* Try implementing your own [`Promise.resolve()` method](/questions/javascript/promise-resolve), [`Promise.reject()` method](/questions/javascript/promise-reject) and [`Promise.all()` method](/questions/javascript/promise-all) on GreatFrontEnd.\n\n## Further reading\n\n* [Promise | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)\n* [Callback function | MDN](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function)\n"
  },
  {
    "path": "questions/what-are-the-various-data-types-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"69a1004f\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"758ace7d\",\n        \"e70495e3\",\n        \"a5f03467\",\n        \"bbf412df\",\n        \"a5f5e547\",\n        \"e140c3e8\",\n        \"2a7816d0\",\n        \"268965e8\",\n        \"b33d0fda\",\n        \"ba032629\",\n        \"854f9f64\",\n        \"d3241996\",\n        \"3d2bc114\",\n        \"453c017\",\n        \"97319ec5\",\n        \"529949c\",\n        \"f5c01970\",\n        \"9f5075b0\",\n        \"2709db0e\",\n        \"74ffd317\",\n        \"8dfabe67\",\n        \"625c6417\",\n        \"98671648\",\n        \"5cef628e\",\n        \"b441fc9f\",\n        \"1921026e\",\n        \"566d4ffd\",\n        \"b2223d82\",\n        \"934a38b7\",\n        \"f9521072\",\n        \"f1fb5869\",\n        \"ffcb336a\",\n        \"2fa0f8bf\",\n        \"31ce0ec7\",\n        \"582b9f16\",\n        \"730b1163\",\n        \"b8f5c3a7\",\n        \"6f74530b\",\n        \"77e5de80\",\n        \"4eae99ec\",\n        \"3fa6dad\",\n        \"473422af\",\n        \"68b07c90\",\n        \"54bcf9ba\",\n        \"105b8b35\",\n        \"85009c0b\",\n        \"15145dc2\",\n        \"1f4770e5\",\n        \"9ddd0981\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"758ace7d\",\n        \"e70495e3\",\n        \"a5f03467\",\n        \"bbf412df\",\n        \"a5f5e547\",\n        \"e140c3e8\",\n        \"2a7816d0\",\n        \"268965e8\",\n        \"b33d0fda\",\n        \"ba032629\",\n        \"854f9f64\",\n        \"d3241996\",\n        \"3d2bc114\",\n        \"453c017\",\n        \"97319ec5\",\n        \"529949c\",\n        \"f5c01970\",\n        \"9f5075b0\",\n        \"2709db0e\",\n        \"74ffd317\",\n        \"8dfabe67\",\n        \"625c6417\",\n        \"98671648\",\n        \"5cef628e\",\n        \"b441fc9f\",\n        \"1921026e\",\n        \"566d4ffd\",\n        \"b2223d82\",\n        \"934a38b7\",\n        \"f9521072\",\n        \"f1fb5869\",\n        \"ffcb336a\",\n        \"2fa0f8bf\",\n        \"31ce0ec7\",\n        \"582b9f16\",\n        \"730b1163\",\n        \"b8f5c3a7\",\n        \"6f74530b\",\n        \"77e5de80\",\n        \"4eae99ec\",\n        \"3fa6dad\",\n        \"473422af\",\n        \"68b07c90\",\n        \"54bcf9ba\",\n        \"105b8b35\",\n        \"85009c0b\",\n        \"15145dc2\",\n        \"1f4770e5\",\n        \"9ddd0981\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-various-data-types-in-javascript/en-US.mdx",
    "content": "---\ntitle: What are the various data types in JavaScript?\n---\n\n## TL;DR\n\nIn JavaScript, data types can be categorized into `primitive` and `non-primitive` types:\n\n**Primitive data types**\n\n- **Number**: Represents both integers and floating-point numbers.\n- **String**: Represents sequences of characters.\n- **Boolean**: Represents `true` or `false` values.\n- **Undefined**: A variable that has been declared but not assigned a value.\n- **Null**: Represents the intentional absence of any object value.\n- **Symbol**: A unique and immutable value used as object property keys. Read more in our [deep dive on `Symbol`s](/questions/quiz/what-are-symbols-used-for)\n- **BigInt**: Represents integers with arbitrary precision.\n\n**Non-primitive (Reference) data types**\n\n- **Object**: Used to store collections of data.\n- **Array**: An ordered collection of data.\n- **Function**: A callable object.\n- **Date**: Represents dates and times.\n- **RegExp**: Represents regular expressions.\n- **Map**: A collection of keyed data items.\n- **Set**: A collection of unique values.\n\nThe primitive types store a single value, while non-primitive types can store collections of data or complex entities.\n\n---\n\n## Data types in JavaScript\n\nJavaScript, like many programming languages, has a variety of data types to represent different kinds of data. The main data types in JavaScript can be divided into two categories: primitive and non-primitive (reference) types.\n\n### Primitive data types\n\n1. **Number**: Represents both integer and floating-point numbers. JavaScript only has one type of number.\n\n```js live\nlet age = 25;\nlet price = 99.99;\nconsole.log(price); // 99.99\n```\n\n2. **String**: Represents sequences of characters. `Strings` can be enclosed in single quotes, double quotes, or backticks (for template literals).\n\n```js live\nlet myName = 'John Doe';\nlet greeting = 'Hello, world!';\nlet message = `Welcome, ${myName}!`;\nconsole.log(message); // \"Welcome, John Doe!\"\n```\n\n3. **Boolean**: Represents logical entities and can have two values: `true` or `false`.\n\n```js live\nlet isActive = true;\nlet isOver18 = false;\nconsole.log(isOver18); // false\n```\n\n4. **Undefined**: A variable that has been declared but not assigned a value is of type `undefined`.\n\n```js live\nlet user;\nconsole.log(user); // undefined\n```\n\n5. **Null**: Represents the intentional absence of any object value. It is a primitive value and is treated as a falsy value.\n\n```js live\nlet user = null;\nconsole.log(user); // null\nif (!user) {\n  console.log('user is a falsy value');\n}\n```\n\n6. **Symbol**: A unique and immutable `primitive` value, typically used as the key of an object property.\n\n```js\nlet sym1 = Symbol();\nlet sym2 = Symbol('description');\nconsole.log(sym1); // Symbol()\nconsole.log(sym2); // Symbol(description)\n```\n\n7. **BigInt**: Used for representing integers with arbitrary precision, useful for working with very large numbers.\n\n```js\nlet bigNumber = BigInt(9007199254740991);\nlet anotherBigNumber = 1234567890123456789012345678901234567890n;\nconsole.log(bigNumber); // 9007199254740991n\nconsole.log(anotherBigNumber); // 1234567890123456789012345678901234567890n\n```\n\n### Non-primitive (reference) data types\n\n1. **Object**: It is used to store collections of data and more complex entities. `Objects` are created using curly braces `{}`.\n\n```js live\nlet person = {\n  name: 'Alice',\n  age: 30,\n};\nconsole.log(person); // {name: \"Alice\", age: 30}\n```\n\n2. **Array**: A special type of object used for storing ordered collections of data. `Arrays` are created using square brackets `[]`.\n\n```js live\nlet numbers = [1, 2, 3, 4, 5];\nconsole.log(numbers);\n```\n\n3. **Function**: `Functions` in JavaScript are `objects`. They can be defined using function declarations or expressions.\n\n```js live\nfunction greet() {\n  console.log('Hello!');\n}\n\nlet add = function (a, b) {\n  return a + b;\n};\n\ngreet(); // \"Hello!\"\nconsole.log(add(2, 3)); // 5\n```\n\n4. **Date**: Represents dates and times. The `Date` object is used to work with dates.\n\n```js live\nlet today = new Date().toLocaleTimeString();\nconsole.log(today);\n```\n\n5. **RegExp**: Represents regular expressions, which are patterns used to match character combinations in strings.\n\n```js live\nlet pattern = /abc/;\nlet str = '123abc456';\n\nconsole.log(pattern.test(str)); // true\n```\n\n6. **Map**: A collection of keyed data items, similar to an `object` but allows keys of any type.\n\n```js live\nlet map = new Map();\nmap.set('key1', 'value1');\nconsole.log(map);\n```\n\n7. **Set**: A collection of unique values.\n\n```js\nlet set = new Set();\nset.add(1);\nset.add(2);\nconsole.log(set); // { 1, 2 }\n```\n\n## Determining data types\n\nJavaScript is a dynamically-typed language, which means variables can hold values of different data types over time. The `typeof` operator can be used to determine the data type of a value or variable.\n\n```js live\nconsole.log(typeof 42); // \"number\"\nconsole.log(typeof 'hello'); // \"string\"\nconsole.log(typeof true); // \"boolean\"\nconsole.log(typeof undefined); // \"undefined\"\nconsole.log(typeof null); // \"object\" (this is a historical bug in JavaScript)\nconsole.log(typeof Symbol()); // \"symbol\"\nconsole.log(typeof BigInt(123)); // \"bigint\"\nconsole.log(typeof {}); // \"object\"\nconsole.log(typeof []); // \"object\"\nconsole.log(typeof function () {}); // \"function\"\n```\n\n## Pitfalls\n\n### Type coercion\n\nJavaScript often performs type coercion, converting values from one type to another, which can lead to unexpected results.\n\n```js live\nlet result = '5' + 2;\nconsole.log(result, typeof result); // \"52 string\" (string concatenation)\n\nlet difference = '5' - 2;\nconsole.log(difference, typeof difference); // 3 \"number\" (numeric subtraction)\n```\n\nIn the first example, since strings can be concatenated with the `+` operator, the number is converted into a string and the two strings are concatenated together. In the second example, strings cannot work with the minus operator (`-`), but two numbers can be minused, so the string is first converted into a number and the result is the difference.\n\n## Further reading\n\n- [JavaScript data types and data structures - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)\n- [JavaScript guide: Data types](https://www.linkedin.com/pulse/javascript-guide-data-types-mila-mirovi%C4%87-jykmf)\n- [Data types - javascript.info](https://javascript.info/types)\n- [JavaScript data types](https://www.programiz.com/javascript/data-types)\n"
  },
  {
    "path": "questions/what-are-the-various-data-types-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-various-data-types-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 350,\n  \"difficulty\": \"easy\"\n}\n"
  },
  {
    "path": "questions/what-are-the-various-data-types-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中的各种数据类型是什么？\n---\n\n## TL;DR\n\n在 JavaScript 中，数据类型可以分为 `原始` 和 `非原始` 类型：\n\n**原始数据类型**\n\n* **Number**：表示整数和浮点数。\n* **String**：表示字符序列。\n* **Boolean**：表示 `true` 或 `false` 值。\n* **Undefined**：已声明但未赋值的变量。\n* **Null**：表示有意缺失任何对象值。\n* **Symbol**：用作对象属性键的唯一且不可变的值。在我们的 [关于 `Symbol` 的深入探讨](/questions/quiz/what-are-symbols-used-for) 中阅读更多内容\n* **BigInt**：表示任意精度的整数。\n\n**非原始（引用）数据类型**\n\n* **Object**：用于存储数据集合。\n* **Array**：数据的有序集合。\n* **Function**：可调用对象。\n* **Date**：表示日期和时间。\n* **RegExp**：表示正则表达式。\n* **Map**：键控数据项的集合。\n* **Set**：唯一值的集合。\n\n原始类型存储单个值，而非原始类型可以存储数据集合或复杂实体。\n\n***\n\n## JavaScript 中的数据类型\n\n与许多编程语言一样，JavaScript 具有多种数据类型来表示不同种类的数据。 JavaScript 中的主要数据类型可以分为两类：原始类型和非原始（引用）类型。\n\n### 原始数据类型\n\n1. **Number**：表示整数和浮点数。 JavaScript 只有一种数字类型。\n\n```js live\nlet age = 25;\nlet price = 99.99;\nconsole.log(price); // 99.99\n```\n\n2. **String**：表示字符序列。 `Strings` 可以用单引号、双引号或反引号（用于模板字面量）括起来。\n\n```js live\nlet myName = 'John Doe';\nlet greeting = 'Hello, world!';\nlet message = `Welcome, ${myName}!`;\nconsole.log(message); // \"Welcome, John Doe!\"\n```\n\n3. **Boolean**：表示逻辑实体，可以有两个值：`true` 或 `false`。\n\n```js live\nlet isActive = true;\nlet isOver18 = false;\nconsole.log(isOver18); // false\n```\n\n4. **Undefined**：已声明但未赋值的变量的类型为 `undefined`。\n\n```js live\nlet user;\nconsole.log(user); // undefined\n```\n\n5. **Null**: 表示任何对象值有意缺失。它是一个原始值，被视为假值。\n\n```js live\nlet user = null;\nconsole.log(user); // null\nif (!user) {\n  console.log('user is a falsy value');\n}\n```\n\n6. **Symbol**: 一种独特且不可变的`原始`值，通常用作对象属性的键。\n\n```js\nlet sym1 = Symbol();\nlet sym2 = Symbol('description');\nconsole.log(sym1); // Symbol()\nconsole.log(sym2); // Symbol(description)\n```\n\n7. **BigInt**：用于表示任意精度的整数，对于处理非常大的数字很有用。\n\n```js\nlet bigNumber = BigInt(9007199254740991);\nlet anotherBigNumber = 1234567890123456789012345678901234567890n;\nconsole.log(bigNumber); // 9007199254740991n\nconsole.log(anotherBigNumber); // 1234567890123456789012345678901234567890n\n```\n\n### 非原始（引用）数据类型\n\n1. **Object**: 用于存储数据集合和更复杂的实体。`Objects` 使用大括号 `{}` 创建。\n\n```js live\nlet person = {\n  name: 'Alice',\n  age: 30,\n};\nconsole.log(person); // {name: \"Alice\", age: 30}\n```\n\n2. **Array**: 一种特殊类型的对象，用于存储有序的数据集合。`Arrays` 使用方括号 `[]` 创建。\n\n```js live\nlet numbers = [1, 2, 3, 4, 5];\nconsole.log(numbers);\n```\n\n3. **Function**: JavaScript 中的`函数`是`对象`。它们可以使用函数声明或表达式来定义。\n\n```js live\nfunction greet() {\n  console.log('Hello!');\n}\n\nlet add = function (a, b) {\n  return a + b;\n};\n\ngreet(); // \"Hello!\"\nconsole.log(add(2, 3)); // 5\n```\n\n4. **Date**: 表示日期和时间。`Date` 对象用于处理日期。\n\n```js live\nlet today = new Date().toLocaleTimeString();\nconsole.log(today);\n```\n\n5. **RegExp**: 表示正则表达式，正则表达式是用于匹配字符串中字符组合的模式。\n\n```js live\nlet pattern = /abc/;\nlet str = '123abc456';\n\nconsole.log(pattern.test(str)); // true\n```\n\n6. **Map**: 键控数据项的集合，类似于`对象`，但允许任何类型的键。\n\n```js live\nlet map = new Map();\nmap.set('key1', 'value1');\nconsole.log(map);\n```\n\n7. **Set**: 唯一值的集合。\n\n```js\nlet set = new Set();\nset.add(1);\nset.add(2);\nconsole.log(set); // { 1, 2 }\n```\n\n## 确定数据类型\n\nJavaScript 是一种动态类型语言，这意味着变量可以随时间推移保存不同数据类型的值。`typeof` 运算符可用于确定值或变量的数据类型。\n\n```js live\nconsole.log(typeof 42); // \"number\"\nconsole.log(typeof 'hello'); // \"string\"\nconsole.log(typeof true); // \"boolean\"\nconsole.log(typeof undefined); // \"undefined\"\nconsole.log(typeof null); // \"object\" (this is a historical bug in JavaScript)\nconsole.log(typeof Symbol()); // \"symbol\"\nconsole.log(typeof BigInt(123)); // \"bigint\"\nconsole.log(typeof {}); // \"object\"\nconsole.log(typeof []); // \"object\"\nconsole.log(typeof function () {}); // \"function\"\n```\n\n## 陷阱\n\n### 类型强制转换\n\nJavaScript 经常执行类型强制转换，将值从一种类型转换为另一种类型，这可能导致意外结果。\n\n```js live\nlet result = '5' + 2;\nconsole.log(result, typeof result); // \"52 string\" (string concatenation)\n\nlet difference = '5' - 2;\nconsole.log(difference, typeof difference); // 3 \"number\" (numeric subtraction)\n```\n\n在第一个例子中，由于字符串可以使用 `+` 运算符进行连接，因此该数字被转换为字符串，并且两个字符串连接在一起。在第二个例子中，字符串不能与减号运算符 (`-`) 一起使用，但两个数字可以相减，因此字符串首先被转换为数字，结果是差值。\n\n## 延伸阅读\n\n* [JavaScript data types and data structures - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures)\n* [JavaScript guide: Data types](https://www.linkedin.com/pulse/javascript-guide-data-types-mila-mirovi%C4%87-jykmf)\n* [Data types - javascript.info](https://javascript.info/types)\n* [JavaScript data types](https://www.programiz.com/javascript/data-types)\n"
  },
  {
    "path": "questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"e13fca9e\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"62eb59fc\",\n        \"4ff6031a\",\n        \"2a7816d0\",\n        \"55903540\",\n        \"3a12ed18\",\n        \"ed382f86\",\n        \"8feb25c0\",\n        \"bcdac678\",\n        \"79c96400\",\n        \"ebfb3652\",\n        \"bd974763\",\n        \"481034e6\",\n        \"23c56234\",\n        \"d3f604f5\",\n        \"af717038\",\n        \"c04d7101\",\n        \"ab8ab5a0\",\n        \"7cba1dea\",\n        \"c17d1a8d\",\n        \"ecb9dad1\",\n        \"629f355f\",\n        \"ea24d7eb\",\n        \"1f4770e5\",\n        \"e18343d2\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"62eb59fc\",\n        \"4ff6031a\",\n        \"2a7816d0\",\n        \"55903540\",\n        \"3a12ed18\",\n        \"ed382f86\",\n        \"8feb25c0\",\n        \"bcdac678\",\n        \"79c96400\",\n        \"ebfb3652\",\n        \"bd974763\",\n        \"481034e6\",\n        \"23c56234\",\n        \"d3f604f5\",\n        \"af717038\",\n        \"c04d7101\",\n        \"ab8ab5a0\",\n        \"7cba1dea\",\n        \"c17d1a8d\",\n        \"ecb9dad1\",\n        \"629f355f\",\n        \"ea24d7eb\",\n        \"1f4770e5\",\n        \"e18343d2\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-the-various-ways-to-create-objects-in-javascript/en-US.mdx",
    "content": "---\ntitle: What are the various ways to create objects in JavaScript?\n---\n\n## TL;DR\n\nCreating objects in JavaScript offers several methods:\n\n- **Object literals (`{}`)**: Simplest and most popular approach. Define key-value pairs within curly braces.\n- **`Object()` constructor**: Use `new Object()` with dot notation to add properties.\n- **`Object.create()`**: Create new objects using existing objects as prototypes, inheriting properties and methods.\n- **Constructor functions**: Define blueprints for objects using functions, creating instances with `new`.\n- **ES2015 classes**: Structured syntax similar to other languages, using `class` and `constructor` keywords.\n\n---\n\n## Objects in JavaScript\n\nCreating objects in JavaScript involves several methods. Here are the various ways to create objects in JavaScript:\n\n## Object literals (`{}`)\n\nThis is the simplest and most popular way to create objects in JavaScript. It involves defining a collection of key-value pairs within curly braces (`{}`). It can be used when you need to create a single object with a fixed set of properties.\n\n```js live\nconst person = {\n  firstName: 'John',\n  lastName: 'Doe',\n  age: 50,\n  eyeColor: 'blue',\n};\n\nconsole.log(person); // {firstName: \"John\", lastName: \"Doe\", age: 50, eyeColor: \"blue\"}\n```\n\n## `Object()` constructor\n\nThis method involves using the `new` keyword with the built-in `Object` constructor to create an object. You can then add properties to the object using dot notation. It can be used when you need to create an object from a primitive value or to create an empty object.\n\n```js live\nconst person = new Object();\nperson.firstName = 'John';\nperson.lastName = 'Doe';\n\nconsole.log(person); // {firstName: \"John\", lastName: \"Doe\"}\n```\n\n## `Object.create()` Method\n\nThis method allows you to create a new object using an existing object as a prototype. The new object inherits properties and methods from the prototype object. It can be used when you need to create a new object with a specific prototype.\n\n```js live\n// Object.create() Method\nconst personPrototype = {\n  greet() {\n    console.log(\n      `Hello, my name is ${this.name} and I'm ${this.age} years old.`,\n    );\n  },\n};\n\nconst person = Object.create(personPrototype);\nperson.name = 'John';\nperson.age = 30;\n\nperson.greet(); // Output: Hello, my name is John and I'm 30 years old.\n```\n\nAn object without a prototype can be created by doing `Object.create(null)`.\n\n## ES2015 classes\n\nClasses provide a more structured and familiar syntax (similar to other programming languages) for creating objects. They define a blueprint and use methods to interact with the object's properties. It can be used when you need to create complex objects with inheritance and encapsulation.\n\n```js live\nclass Person {\n  constructor(name, age) {\n    this.name = name;\n    this.age = age;\n  }\n  greet = function () {\n    console.log(\n      `Hello, my name is ${this.name} and I'm ${this.age} years old.`,\n    );\n  };\n}\n\nconst person1 = new Person('John', 30);\nconst person2 = new Person('Alice', 25);\n\nperson1.greet(); // Output: Hello, my name is John and I'm 30 years old.\nperson2.greet(); // Output: Hello, my name is Alice and I'm 25 years old.\n```\n\n## Constructor functions\n\nConstructor functions are used to create reusable blueprints for objects. They define the properties and behaviors shared by all objects of that type. You use the `new` keyword to create instances of the object. It can be used when you need to create multiple objects with similar properties and methods.\n\nHowever, now that ES2015 classes are readily supported in modern browsers, there's little reason to use constructor functions to create objects.\n\n```js live\n// Constructor function\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n  this.greet = function () {\n    console.log(\n      `Hello, my name is ${this.name} and I'm ${this.age} years old.`,\n    );\n  };\n}\n\nconst person1 = new Person('John', 30);\nconst person2 = new Person('Alice', 25);\n\nperson1.greet(); // Output: Hello, my name is John and I'm 30 years old.\nperson2.greet(); // Output: Hello, my name is Alice and I'm 25 years old.\n```\n\n## Further reading\n\n- [`Object()` constructor | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)\n- [`new` keyword | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new)\n- [`Object.create()` | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create)\n"
  },
  {
    "path": "questions/what-are-the-various-ways-to-create-objects-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"what-are-the-various-ways-to-create-objects-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 170,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-the-various-ways-to-create-objects-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中创建对象的各种方法是什么？\n---\n\n## TL;DR\n\n在 JavaScript 中创建对象提供了几种方法：\n\n* **对象字面量 (`{}`)**：最简单、最流行的方法。在花括号内定义键值对。\n* **`Object()` 构造函数**：使用 `new Object()` 和点表示法添加属性。\n* **`Object.create()`**：使用现有对象作为原型创建新对象，继承属性和方法。\n* **构造函数**：使用函数定义对象的蓝图，使用 `new` 创建实例。\n* **ES2015 类**：类似于其他语言的结构化语法，使用 `class` 和 `constructor` 关键字。\n\n***\n\n## JavaScript 中的对象\n\n在 JavaScript 中创建对象涉及几种方法。以下是在 JavaScript 中创建对象的各种方法：\n\n## 对象字面量 (`{}`)\n\n这是在 JavaScript 中创建对象的最简单、最流行的方法。它涉及在花括号 (`{}`) 中定义键值对的集合。当您需要创建一个具有固定属性集的单个对象时，可以使用它。\n\n```js live\nconst person = {\n  firstName: 'John',\n  lastName: 'Doe',\n  age: 50,\n  eyeColor: 'blue',\n};\n\nconsole.log(person); // {firstName: \"John\", lastName: \"Doe\", age: 50, eyeColor: \"blue\"}\n```\n\n## `Object()` 构造函数\n\n此方法涉及将 `new` 关键字与内置的 `Object` 构造函数一起使用以创建对象。然后，您可以使用点表示法将属性添加到对象。当您需要从原始值创建对象或创建空对象时，可以使用它。\n\n```js live\nconst person = new Object();\nperson.firstName = 'John';\nperson.lastName = 'Doe';\n\nconsole.log(person); // {firstName: \"John\", lastName: \"Doe\"}\n```\n\n## `Object.create()` 方法\n\n此方法允许您使用现有对象作为原型来创建新对象。新对象从原型对象继承属性和方法。当您需要创建一个具有特定原型的新对象时，可以使用它。\n\n```js live\n// Object.create() 方法\nconst personPrototype = {\n  greet() {\n    console.log(\n      `Hello, my name is ${this.name} and I'm ${this.age} years old.`,\n    );\n  },\n};\n\nconst person = Object.create(personPrototype);\nperson.name = 'John';\nperson.age = 30;\n\nperson.greet(); // Output: Hello, my name is John and I'm 30 years old.\n```\n\n可以通过执行 `Object.create(null)` 来创建没有原型的对象。\n\n## ES2015 类\n\n类为创建对象提供了更结构化和熟悉的语法（类似于其他编程语言）。它们定义了一个蓝图，并使用方法与对象的属性进行交互。当您需要创建具有继承和封装的复杂对象时，可以使用它。\n\n```js live\nclass Person {\n  constructor(name, age) {\n    this.name = name;\n    this.age = age;\n  }\n  greet = function () {\n    console.log(\n      `Hello, my name is ${this.name} and I'm ${this.age} years old.`,\n    );\n  };\n}\n\nconst person1 = new Person('John', 30);\nconst person2 = new Person('Alice', 25);\n\nperson1.greet(); // Output: Hello, my name is John and I'm 30 years old.\nperson2.greet(); // Output: Hello, my name is Alice and I'm 25 years old.\n```\n\n## 构造函数\n\n构造函数用于创建可重用的对象蓝图。它们定义了该类型的所有对象共享的属性和行为。您使用 `new` 关键字创建对象的实例。当您需要创建具有相似属性和方法的多个对象时，可以使用它。\n\n然而，现在 ES2015 类在现代浏览器中得到了广泛支持，因此使用构造函数创建对象的原因已经不多了。\n\n```js live\n// Constructor function\nfunction Person(name, age) {\n  this.name = name;\n  this.age = age;\n  this.greet = function () {\n    console.log(\n      `Hello, my name is ${this.name} and I'm ${this.age} years old.`,\n    );\n  };\n}\n\nconst person1 = new Person('John', 30);\nconst person2 = new Person('Alice', 25);\n\nperson1.greet(); // Output: Hello, my name is John and I'm 30 years old.\nperson2.greet(); // Output: Hello, my name is Alice and I'm 25 years old.\n```\n\n## 延伸阅读\n\n* [`Object()` constructor | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object)\n* [`new` keyword | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new)\n* [`Object.create()` | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create)\n"
  },
  {
    "path": "questions/what-are-web-workers-and-how-can-they-be-used-to-improve-performance/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"f22f848f\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3ba8c62\",\n        \"f46a95bc\",\n        \"2a7816d0\",\n        \"edd9aed9\",\n        \"45d45274\",\n        \"bfd3ca9f\",\n        \"46be4a72\",\n        \"f7d34aad\",\n        \"6d62c52d\",\n        \"d6a5d89f\",\n        \"451b240f\",\n        \"45cdadb6\",\n        \"194a29a3\",\n        \"a8313ca5\",\n        \"bba81cf0\",\n        \"76e3fbd3\",\n        \"a044ef31\",\n        \"e900c113\",\n        \"fabae248\",\n        \"75a10f2a\",\n        \"54b6c21c\",\n        \"c673dc3d\",\n        \"63c3193d\",\n        \"ef947b5\",\n        \"1f4770e5\",\n        \"d5e8780e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3ba8c62\",\n        \"f46a95bc\",\n        \"2a7816d0\",\n        \"edd9aed9\",\n        \"45d45274\",\n        \"bfd3ca9f\",\n        \"46be4a72\",\n        \"f7d34aad\",\n        \"6d62c52d\",\n        \"d6a5d89f\",\n        \"451b240f\",\n        \"45cdadb6\",\n        \"194a29a3\",\n        \"a8313ca5\",\n        \"bba81cf0\",\n        \"76e3fbd3\",\n        \"a044ef31\",\n        \"e900c113\",\n        \"fabae248\",\n        \"75a10f2a\",\n        \"54b6c21c\",\n        \"c673dc3d\",\n        \"63c3193d\",\n        \"ef947b5\",\n        \"1f4770e5\",\n        \"d5e8780e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-web-workers-and-how-can-they-be-used-to-improve-performance/en-US.mdx",
    "content": "---\ntitle: What are Web Workers and how can they be used to improve performance?\n---\n\n## TL;DR\n\nWeb Workers are a way to run JavaScript in the background, separate from the main execution thread of a web application. This helps in performing heavy computations without blocking the user interface. You can create a Web Worker using the `Worker` constructor and communicate with it using the `postMessage` and `onmessage` methods.\n\n```js\n// main.js\nconst worker = new Worker('worker.js');\nworker.postMessage('Hello, worker!');\n\nworker.onmessage = function (event) {\n  console.log('Message from worker:', event.data);\n};\n\n// worker.js\nonmessage = function (event) {\n  console.log('Message from main script:', event.data);\n  postMessage('Hello, main script!');\n};\n```\n\n---\n\n## What are Web Workers and how can they be used to improve performance?\n\n### Introduction to Web Workers\n\nWeb Workers provide a way to run JavaScript in the background, separate from the main execution thread. This allows for performing tasks like heavy computations or I/O operations without blocking the user interface, leading to a smoother user experience.\n\n### Creating a Web Worker\n\nTo create a Web Worker, you use the `Worker` constructor and pass the URL of the JavaScript file that contains the worker code.\n\n```js\nconst worker = new Worker('worker.js');\n```\n\n### Communication between main script and Web Worker\n\nCommunication between the main script and the Web Worker is done using the `postMessage` method and the `onmessage` event handler.\n\n#### Main script\n\n```js\n// main.js\nconst worker = new Worker('worker.js');\n\n// Send a message to the worker\nworker.postMessage('Hello, worker!');\n\n// Receive messages from the worker\nworker.onmessage = function (event) {\n  console.log('Message from worker:', event.data);\n};\n```\n\n#### Worker script\n\n```js\n// worker.js\nonmessage = function (event) {\n  console.log('Message from main script:', event.data);\n  // Send a message back to the main script\n  postMessage('Hello, main script!');\n};\n```\n\n### Use cases for Web Workers\n\n#### Heavy computations\n\nWeb Workers can be used to perform heavy computations without blocking the main thread. For example, calculating large datasets or performing complex mathematical operations.\n\n```js\n// worker.js\nonmessage = function (event) {\n  const result = heavyComputation(event.data);\n  postMessage(result);\n};\n\nfunction heavyComputation(data) {\n  // Perform heavy computation here\n  return data * 2; // Example computation\n}\n```\n\n#### Data processing\n\nWeb Workers can be used to process large amounts of data, such as parsing large JSON files or processing images.\n\n```js\n// worker.js\nonmessage = function (event) {\n  const processedData = processData(event.data);\n  postMessage(processedData);\n};\n\nfunction processData(data) {\n  // Process data here\n  return data.map((item) => item * 2); // Example processing\n}\n```\n\n### Limitations of Web Workers\n\n- Web Workers do not have access to the DOM, so they cannot directly manipulate the user interface.\n- They have a separate scope from the main script, so you need to pass data back and forth using `postMessage`.\n- Creating and managing Web Workers can add complexity to your codebase.\n\n## Further reading\n\n- [MDN Web Docs: Using Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)\n- [HTML5 Rocks: Web Workers](https://www.html5rocks.com/en/tutorials/workers/basics/)\n- [MDN Web Docs: Worker](https://developer.mozilla.org/en-US/docs/Web/API/Worker)\n"
  },
  {
    "path": "questions/what-are-web-workers-and-how-can-they-be-used-to-improve-performance/metadata.json",
    "content": "{\n  \"slug\": \"what-are-web-workers-and-how-can-they-be-used-to-improve-performance\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"advanced\",\n  \"topics\": [\"web-api\", \"javascript\", \"performance\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Performance Optimization\"\n}\n"
  },
  {
    "path": "questions/what-are-web-workers-and-how-can-they-be-used-to-improve-performance/zh-CN.mdx",
    "content": "---\ntitle: 什么是 Web Worker 以及如何使用它们来提高性能？\n---\n\n## TL;DR\n\nWeb Worker 是一种在后台运行 JavaScript 的方法，与 Web 应用程序的主执行线程分开。这有助于执行繁重的计算，而不会阻塞用户界面。您可以使用 `Worker` 构造函数创建 Web Worker，并使用 `postMessage` 和 `onmessage` 方法与其通信。\n\n```js\n// main.js\nconst worker = new Worker('worker.js');\nworker.postMessage('Hello, worker!');\n\nworker.onmessage = function (event) {\n  console.log('Message from worker:', event.data);\n};\n\n// worker.js\nonmessage = function (event) {\n  console.log('Message from main script:', event.data);\n  postMessage('Hello, main script!');\n};\n```\n\n***\n\n## 什么是 Web Worker 以及如何使用它们来提高性能？\n\n### Web Worker 简介\n\nWeb Worker 提供了一种在后台运行 JavaScript 的方法，与主执行线程分开。这允许执行繁重的任务，如繁重的计算或 I/O 操作，而不会阻塞用户界面，从而带来更流畅的用户体验。\n\n### 创建 Web Worker\n\n要创建 Web Worker，您可以使用 `Worker` 构造函数并传递包含 worker 代码的 JavaScript 文件的 URL。\n\n```js\nconst worker = new Worker('worker.js');\n```\n\n### 主脚本和 Web Worker 之间的通信\n\n主脚本和 Web Worker 之间的通信使用 `postMessage` 方法和 `onmessage` 事件处理程序完成。\n\n#### 主脚本\n\n```js\n// main.js\nconst worker = new Worker('worker.js');\n\n// Send a message to the worker\nworker.postMessage('Hello, worker!');\n\n// Receive messages from the worker\nworker.onmessage = function (event) {\n  console.log('Message from worker:', event.data);\n};\n```\n\n#### Worker 脚本\n\n```js\n// worker.js\nonmessage = function (event) {\n  console.log('Message from main script:', event.data);\n  // Send a message back to the main script\n  postMessage('Hello, main script!');\n};\n```\n\n### Web Worker 的用例\n\n#### 繁重的计算\n\nWeb Worker 可用于执行繁重的计算，而不会阻塞主线程。例如，计算大型数据集或执行复杂的数学运算。\n\n```js\n// worker.js\nonmessage = function (event) {\n  const result = heavyComputation(event.data);\n  postMessage(result);\n};\n\nfunction heavyComputation(data) {\n  // Perform heavy computation here\n  return data * 2; // Example computation\n}\n```\n\n#### 数据处理\n\nWeb Workers 可用于处理大量数据，例如解析大型 JSON 文件或处理图像。\n\n```js\n// worker.js\nonmessage = function (event) {\n  const processedData = processData(event.data);\n  postMessage(processedData);\n};\n\nfunction processData(data) {\n  // Process data here\n  return data.map((item) => item * 2); // Example processing\n}\n```\n\n### Web Workers 的局限性\n\n* Web Workers 无法访问 DOM，因此它们无法直接操作用户界面。\n* 它们与主脚本具有单独的作用域，因此您需要使用 `postMessage` 来回传递数据。\n* 创建和管理 Web Workers 可能会增加代码库的复杂性。\n\n## 延伸阅读\n\n* [MDN Web 文档：使用 Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)\n* [HTML5 Rocks：Web Workers](https://www.html5rocks.com/en/tutorials/workers/basics/)\n* [MDN Web 文档：Worker](https://developer.mozilla.org/en-US/docs/Web/API/Worker)\n"
  },
  {
    "path": "questions/what-are-workers-in-javascript-used-for/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"82174ead\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"81b305fd\",\n        \"492d66f6\",\n        \"8bc8629e\",\n        \"dc65c225\",\n        \"2a7816d0\",\n        \"dcdc9685\",\n        \"63cd0c43\",\n        \"f585af79\",\n        \"31a7fb80\",\n        \"7605e333\",\n        \"a38e1c24\",\n        \"fe3ffc59\",\n        \"91fab7f4\",\n        \"48ab8881\",\n        \"17797f57\",\n        \"5acd4d9\",\n        \"1f38fab\",\n        \"670df17e\",\n        \"10549b9d\",\n        \"c30c06aa\",\n        \"eef673d7\",\n        \"deb3c04d\",\n        \"ca31f74f\",\n        \"60eec3fb\",\n        \"48ab8881\",\n        \"42977d71\",\n        \"9bc4900\",\n        \"775f7c43\",\n        \"670df17e\",\n        \"142af101\",\n        \"988fcf0f\",\n        \"5145f0e3\",\n        \"60890b68\",\n        \"3735cf9d\",\n        \"82c22e11\",\n        \"97d2c0ae\",\n        \"c216a3c0\",\n        \"942ead1e\",\n        \"5d37b19f\",\n        \"1f4770e5\",\n        \"ab664eb9\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"81b305fd\",\n        \"492d66f6\",\n        \"8bc8629e\",\n        \"dc65c225\",\n        \"2a7816d0\",\n        \"dcdc9685\",\n        \"63cd0c43\",\n        \"f585af79\",\n        \"31a7fb80\",\n        \"7605e333\",\n        \"a38e1c24\",\n        \"fe3ffc59\",\n        \"91fab7f4\",\n        \"48ab8881\",\n        \"17797f57\",\n        \"5acd4d9\",\n        \"1f38fab\",\n        \"670df17e\",\n        \"10549b9d\",\n        \"c30c06aa\",\n        \"eef673d7\",\n        \"deb3c04d\",\n        \"ca31f74f\",\n        \"60eec3fb\",\n        \"48ab8881\",\n        \"42977d71\",\n        \"9bc4900\",\n        \"775f7c43\",\n        \"670df17e\",\n        \"142af101\",\n        \"988fcf0f\",\n        \"5145f0e3\",\n        \"60890b68\",\n        \"3735cf9d\",\n        \"82c22e11\",\n        \"97d2c0ae\",\n        \"c216a3c0\",\n        \"942ead1e\",\n        \"5d37b19f\",\n        \"1f4770e5\",\n        \"ab664eb9\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-are-workers-in-javascript-used-for/en-US.mdx",
    "content": "---\ntitle: What are workers in JavaScript used for?\n---\n\n## TL;DR\n\nWorkers in JavaScript are background threads that allow you to run scripts in parallel with the main execution thread, without blocking or interfering with the user interface. Their key features include:\n\n- **Parallel processing**: Workers run in a separate thread from the main thread, allowing your web page to remain responsive to user interactions while the worker performs its tasks. It's useful for moving CPU-intensive work off the main thread and be free from JavaScript's single-threaded nature.\n- **Communication**: Uses `postMessage()` and `onmessage`/ `'message'` event for messaging.\n- **Access to web APIs**: Workers have access to various Web APIs, including `fetch()`, IndexedDB, and Web Storage, allowing them to perform tasks like data fetching and persisting data independently.\n- **No DOM access**: Workers cannot directly manipulate the DOM, thus cannot interact with the UI, ensuring they don't accidentally interfere with the main thread's operation.\n\nThere are three main types of workers in JavaScript:\n\n- **Web workers / Dedicated workers**\n  - Run scripts in background threads, separate from the main UI thread.\n  - Useful for CPU-intensive tasks like data processing, calculations, etc.\n  - Cannot directly access or manipulate the DOM.\n- **Service workers**\n  - Act as network proxies, handling requests between the app and network.\n  - Enable offline functionality, caching, and push notifications.\n  - Runs independently of the web page, even when it's closed.\n- **Shared workers**\n  - Can be shared by multiple scripts running in different windows or frames, as long as they're in the same domain.\n  - Scripts communicate with the shared worker by sending and receiving messages.\n  - Useful for coordinating tasks across different parts of a web page.\n\n---\n\n## Workers in JavaScript\n\nWorkers in JavaScript are a way to run scripts in background threads, separate from the main execution thread of a web page. This allows for long-running or computationally intensive tasks to be offloaded from the main thread, preventing the user interface from becoming unresponsive or janky.\n\n## Web workers / Dedicated workers\n\n- Run scripts in background threads separate from the main UI thread.\n- Designed for CPU-intensive tasks like data processing, mathematical computations, etc. Generally the non-async work.\n- Cannot directly access the DOM or other main thread resources for security.\n- Communicates with main thread via asynchronous message passing – `postMessage()` and `onmessage`/ `'message'`.\n- Terminated when main script is unloaded or explicitly terminated.\n\nWeb workers can be used for:\n\n- Image/video processing\n- Data compression\n- Complex math\n\n### Creating a web worker\n\nTo create a web worker, you need a separate JavaScript file that contains the code for the worker. Here's an example:\n\n**`main.js` (main script)**\n\n```js\n// Check if the browser supports workers\nif (window.Worker) {\n  // Create a new Worker\n  const myWorker = new Worker('worker.js');\n\n  // Post a message to the worker\n  myWorker.postMessage('Hello, Worker!');\n\n  // Listen for messages from the worker\n  myWorker.onmessage = function (event) {\n    console.log('Message from Worker:', event.data);\n  };\n\n  // Error handling\n  myWorker.onerror = function (error) {\n    console.error('Error from Worker:', error);\n  };\n}\n```\n\n**`worker.js` (worker script)**\n\n```js\n// Listen for messages from the main script\nonmessage = function (event) {\n  console.log('Message from Main Script:', event.data);\n\n  // Perform a task (e.g., some computation)\n  const result = event.data + ' - Processed by Worker';\n\n  // Post the result back to the main script\n  postMessage(result);\n};\n```\n\nIn this example:\n\n- `main.js` creates a worker using the `Worker` constructor and specifies `worker.js` as the script to run in the worker thread.\n- It posts a message to the worker using `postMessage()`.\n- The worker script (`worker.js`) listens for messages from the main script using `onmessage`.\n- After processing the message, the worker posts a message back to the main script using `postMessage()`.\n- The main script listens for messages from the worker using `onmessage` on the `Worker` instance.\n\n### Service workers\n\n- Act as a network proxy between web app, browser, and network.\n- Can intercept and handle network requests, cache resources.\n- Enable offline functionality and push notifications.\n- Have a lifecycle managed by the browser (install, activate, update).\n- No access to DOM and main thread resources for security.\n\nService workers can be used for:\n\n- Caching\n- Offline support\n- Request handling\n- Background sync\n\n#### Creating a service worker\n\n**`main.js` (main script)**\n\n```js\nif ('serviceWorker' in navigator) {\n  navigator.serviceWorker\n    .register('/service-worker.js')\n    .then(function (registration) {\n      console.log('Service Worker registered:', registration);\n    })\n    .catch(function (err) {\n      console.log('Service Worker registration failed:', err);\n    });\n}\n```\n\n**`service-worker.js` (service worker script)**\n\n```js\nself.addEventListener('fetch', function (event) {\n  event.respondWith(\n    caches.match(event.request).then(function (response) {\n      // return cached response if available\n      if (response) {\n        return response;\n      }\n\n      // Otherwise, fetch from network\n      return fetch(event.request);\n    }),\n  );\n});\n```\n\nIn this example:\n\n- The main script registers a service worker at `/service-worker.js`\n- The service worker listens for the `fetch()` event, which is fired whenever the browser makes a network request\n- The service worker first checks if the requested resource is cached using `caches.match(event.request)`\n- If it is, it returns the cached response. Otherwise, it fetches the resource from the network using `fetch(event.request)`\n\n### Bonus: Shared workers\n\n- **Scope**: Can be accessed from multiple scripts in different windows/tabs/iframes\n- **Sharing of data**: Allow data sharing between browser contexts via a messaging interface\n- **Browser support**: Limited support, especially [not available on Android browsers](https://issues.chromium.org/issues/40290702)\n\n#### Use cases for shared workers:\n\n- State sharing across multiple windows.\n\n### Bonus: Worklets\n\nThe `Worklet` interface is a lightweight version of Web Workers and gives developers access to low-level parts of the rendering pipeline. With Worklets, you can run JavaScript and WebAssembly code to do graphics rendering or audio processing where high performance is required.\n\nYou are not expected to know about worklets, so it won't be covered in great detail. Read more about [worklets on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Worklet).\n\n## Considerations and limitations\n\n- **Same-Origin policy**: Workers must comply with the same-origin policy, meaning the script that creates the worker and the worker script itself must be from the same origin\n- **No DOM access**: Workers do not have direct access to the DOM. They can communicate with the main thread through messages\n- **Performance**: Creating and managing workers incurs overhead. They should be used judiciously for tasks that truly benefit from parallel execution\n- **Error handling**: Proper error handling mechanisms should be in place to handle any issues within the worker scripts\n\n## Further reading\n\n- [Worker - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Worker)\n- [Using Web Workers - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)\n- [Service Worker API - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)\n- [Understanding web workers in JavaScript with real world example](https://javascript.plainenglish.io/understanding-web-workers-in-js-with-real-world-example-1629a283aeec?gi=89cf0dd4c3f4)\n- [Web worker, Service worker, and Worklets: A comprehensive guide](https://dev.to/bharat5604/web-worker-service-worker-and-worklets-a-comprehensive-guide-1f64)\n"
  },
  {
    "path": "questions/what-are-workers-in-javascript-used-for/metadata.json",
    "content": "{\n  \"slug\": \"what-are-workers-in-javascript-used-for\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 490,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-are-workers-in-javascript-used-for/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中的 Worker 有什么作用？\n---\n\n## TL;DR\n\nJavaScript 中的 Worker 是后台线程，允许您与主执行线程并行运行脚本，而不会阻塞或干扰用户界面。 它们的主要特点包括：\n\n* **并行处理**：Worker 在与主线程不同的线程中运行，允许您的网页在 worker 执行其任务时保持对用户交互的响应。 这对于将 CPU 密集型工作从主线程中移出并摆脱 JavaScript 单线程的特性非常有用。\n* **通信**：使用 `postMessage()` 和 `onmessage`/ `'message'` 事件进行消息传递。\n* **访问 Web API**：Worker 可以访问各种 Web API，包括 `fetch()`、IndexedDB 和 Web Storage，允许它们独立执行数据获取和持久化数据等任务。\n* **无法访问 DOM**：Worker 无法直接操作 DOM，因此无法与 UI 交互，确保它们不会意外干扰主线程的操作。\n\nJavaScript 中有三种主要的 worker 类型：\n\n* **Web worker / 专用 worker**\n  * 在后台线程中运行脚本，与主 UI 线程分开。\n  * 适用于 CPU 密集型任务，如数据处理、计算等。\n  * 无法直接访问或操作 DOM。\n* **Service worker**\n  * 充当网络代理，处理应用程序和网络之间的请求。\n  * 启用离线功能、缓存和推送通知。\n  * 独立于网页运行，即使网页已关闭。\n* **共享 worker**\n  * 只要它们在同一域中，就可以由在不同窗口或框架中运行的多个脚本共享。\n  * 脚本通过发送和接收消息与共享 worker 通信。\n  * 适用于协调网页不同部分的任务。\n\n***\n\n## JavaScript 中的 Worker\n\nJavaScript 中的 Worker 是一种在后台线程中运行脚本的方式，与网页的主执行线程分开。 这允许将长时间运行或计算密集型任务从主线程中卸载，防止用户界面变得无响应或卡顿。\n\n## Web worker / 专用 worker\n\n* 在与主 UI 线程分开的后台线程中运行脚本。\n* 专为 CPU 密集型任务而设计，如数据处理、数学计算等。 通常是非异步工作。\n* 出于安全原因，无法直接访问 DOM 或其他主线程资源。\n* 通过异步消息传递进行与主线程的通信 – `postMessage()` 和 `onmessage`/ `'message'`。\n* 当主脚本被卸载或显式终止时终止。\n\nWeb worker 可用于：\n\n* 图像/视频处理\n* 数据压缩\n* 复杂数学\n\n### 创建一个 web worker\n\n要创建一个 web worker，您需要一个单独的 JavaScript 文件，其中包含 worker 的代码。 这是一个例子：\n\n**`main.js` (主脚本)**\n\n```js\n// 检查浏览器是否支持 worker\nif (window.Worker) {\n  // 创建一个新的 Worker\n  const myWorker = new Worker('worker.js');\n\n  // 向 worker 发送消息\n  myWorker.postMessage('Hello, Worker!');\n\n  // 监听来自 worker 的消息\n  myWorker.onmessage = function (event) {\n    console.log('来自 Worker 的消息：', event.data);\n  };\n\n  // 错误处理\n  myWorker.onerror = function (error) {\n    console.error('来自 Worker 的错误：', error);\n  };\n}\n```\n\n**`worker.js` (worker 脚本)**\n\n```js\n// 监听来自主脚本的消息\nonmessage = function (event) {\n  console.log('来自主脚本的消息：', event.data);\n\n  // 执行一个任务（例如，一些计算）\n  const result = event.data + ' - 由 Worker 处理';\n\n  // 将结果发回给主脚本\n  postMessage(result);\n};\n```\n\n在这个例子中：\n\n* `main.js` 使用 `Worker` 构造函数创建一个 worker，并指定 `worker.js` 作为在 worker 线程中运行的脚本。\n* 它使用 `postMessage()` 向 worker 发送消息。\n* worker 脚本 (`worker.js`) 使用 `onmessage` 监听来自主脚本的消息。\n* 处理完消息后，worker 使用 `postMessage()` 将消息发回给主脚本。\n* 主脚本在 `Worker` 实例上使用 `onmessage` 监听来自 worker 的消息。\n\n### Service workers\n\n* 充当 Web 应用程序、浏览器和网络之间的网络代理。\n* 可以拦截和处理网络请求，缓存资源。\n* 启用离线功能和推送通知。\n* 具有由浏览器管理的生命周期（安装、激活、更新）。\n* 出于安全考虑，无法访问 DOM 和主线程资源。\n\nService workers 可以用于：\n\n* 缓存\n* 离线支持\n* 请求处理\n* 后台同步\n\n#### 创建 service worker\n\n**`main.js` (主脚本)**\n\n```js\nif ('serviceWorker' in navigator) {\n  navigator.serviceWorker\n    .register('/service-worker.js')\n    .then(function (registration) {\n      console.log('Service Worker registered:', registration);\n    })\n    .catch(function (err) {\n      console.log('Service Worker registration failed:', err);\n    });\n}\n```\n\n**`service-worker.js` (service worker 脚本)**\n\n```js\nself.addEventListener('fetch', function (event) {\n  event.respondWith(\n    caches.match(event.request).then(function (response) {\n      // return cached response if available\n      if (response) {\n        return response;\n      }\n\n      // Otherwise, fetch from network\n      return fetch(event.request);\n    }),\n  );\n});\n```\n\n在这个例子中：\n\n* 主脚本在 `/service-worker.js` 注册一个 service worker\n* service worker 监听 `fetch()` 事件，该事件在浏览器发出网络请求时触发\n* service worker 首先使用 `caches.match(event.request)` 检查请求的资源是否已缓存\n* 如果已缓存，则返回缓存的响应。 否则，它使用 `fetch(event.request)` 从网络获取资源\n\n### 奖励：共享 worker\n\n* **范围**：可以从不同窗口/标签页/iframe 中的多个脚本访问\n* **数据共享**：允许通过消息传递接口在浏览器上下文之间共享数据\n* **浏览器支持**：支持有限，尤其[在 Android 浏览器上不可用](https://issues.chromium.org/issues/40290702)\n\n#### 共享 worker 的用例：\n\n* 跨多个窗口共享状态。\n\n### 奖励：Worklets\n\n`Worklet` 接口是 Web Workers 的轻量级版本，它使开发人员可以访问渲染管道的低级部分。 使用 Worklets，您可以运行 JavaScript 和 WebAssembly 代码来执行图形渲染或音频处理，其中需要高性能。\n\n您不需要了解 worklets，因此不会详细介绍。 在 [MDN 上阅读有关 worklets 的更多信息](https://developer.mozilla.org/en-US/docs/Web/API/Worklet)。\n\n## 考虑事项和限制\n\n* **同源策略**：Workers 必须遵守同源策略，这意味着创建 worker 的脚本和 worker 脚本本身必须来自同一源\n* **无 DOM 访问**：Workers 无法直接访问 DOM。 它们可以通过消息与主线程通信\n* **性能**：创建和管理 workers 会产生开销。 它们应该谨慎用于真正受益于并行执行的任务\n* **错误处理**：应建立适当的错误处理机制来处理 worker 脚本中的任何问题\n\n## 延伸阅读\n\n* [Worker - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Worker)\n* [Using Web Workers - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers)\n* [Service Worker API - MDN](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API)\n* [Understanding web workers in JavaScript with real world example](https://javascript.plainenglish.io/understanding-web-workers-in-js-with-real-world-example-1629a283aeec?gi=89cf0dd4c3f4)\n* [Web worker, Service worker, and Worklets: A comprehensive guide](https://dev.to/bharat5604/web-worker-service-worker-and-worklets-a-comprehensive-guide-1f64)\n"
  },
  {
    "path": "questions/what-do-you-think-of-amd-vs-commonjs/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"d4ad4303\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"ac7f1dcb\",\n        \"2a7816d0\",\n        \"7e5d8c12\",\n        \"7cc5a809\",\n        \"96b698d\",\n        \"6bf6ed5b\",\n        \"ef879098\",\n        \"748ffe75\",\n        \"b58e02f3\",\n        \"bf6d8053\",\n        \"6bf6ed5b\",\n        \"7b1a935b\",\n        \"748ffe75\",\n        \"fe92c745\",\n        \"67423e0a\",\n        \"a82a90cc\",\n        \"72cbbd54\",\n        \"d7ae6d3f\",\n        \"2e3b1e66\",\n        \"f4801713\",\n        \"b0600791\",\n        \"8ce3d8ef\",\n        \"c735cbf9\",\n        \"6dd3b324\",\n        \"937e3338\",\n        \"9ff078\",\n        \"34105638\",\n        \"d9138816\",\n        \"1f4770e5\",\n        \"19ad870f\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"ac7f1dcb\",\n        \"2a7816d0\",\n        \"7e5d8c12\",\n        \"7cc5a809\",\n        \"96b698d\",\n        \"6bf6ed5b\",\n        \"ef879098\",\n        \"748ffe75\",\n        \"b58e02f3\",\n        \"bf6d8053\",\n        \"6bf6ed5b\",\n        \"7b1a935b\",\n        \"748ffe75\",\n        \"fe92c745\",\n        \"67423e0a\",\n        \"a82a90cc\",\n        \"72cbbd54\",\n        \"d7ae6d3f\",\n        \"2e3b1e66\",\n        \"f4801713\",\n        \"b0600791\",\n        \"8ce3d8ef\",\n        \"c735cbf9\",\n        \"6dd3b324\",\n        \"937e3338\",\n        \"9ff078\",\n        \"34105638\",\n        \"d9138816\",\n        \"1f4770e5\",\n        \"19ad870f\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-do-you-think-of-amd-vs-commonjs/en-US.mdx",
    "content": "---\ntitle: What do you think of CommonJS vs ESM?\n---\n\n## TL;DR\n\nJavaScript has evolved its module systems. ESM (ECMAScript Modules) using `import` / `export` is the official standard, natively supported in modern browsers and Node.js, designed for both synchronous and asynchronous use cases. CommonJS (CJS) using `require` / `module.exports` was the original standard for Node.js, primarily synchronous, and remains prevalent in the Node ecosystem. AMD (Asynchronous Module Definition) using `define` / `require` was an early system designed for asynchronous loading in browsers but is now largely obsolete, replaced by ESM.\n\n---\n\n### Overview\n\nModule systems help manage this complexity by allowing code to be split into reusable pieces (modules) with clear dependencies. Over time, different module systems emerged before an official standard was adopted.\n\n### CommonJS\n\n#### Characteristics\n\n- Designed for synchronous loading of modules\n- Primarily used in server-side environments like Node.js\n- Uses `module.exports` and `require` for defining and loading modules\n\n#### Example\n\n```javascript\n// Defining a module in CommonJS\nconst dep1 = require('dependency1');\nconst dep2 = require('dependency2');\n\nmodule.exports = {\n  // Module code here\n};\n\n// Loading a module in CommonJS\nconst mod1 = require('module1');\nconst mod2 = require('module2');\n\n// Code that uses mod1 and mod2\n```\n\n### ESM (ECMAScript Modules)\n\n#### Characteristics\n\n- Official JavaScript standard module system\n- Supported natively in modern browsers and Node.js\n- Designed for both asynchronous and synchronous scenarios\n- Uses `export` and `import` for defining and loading modules\n\n#### Example\n\n```javascript\nimport dep1 from 'dependency1'; // if dependency1 had a default export\nimport { dep2 } from 'dependency2'; // named import to import something specific from dependency2\n\n// Module code using dep1, dep2...\n\nexport function someFunction() {\n  // ... function logic ...\n}\nexport const someValue = 'hello';\n\n// Or export multiple things at once\n// export { someFunction, someValue };\n\n// Or export a default value\n// export default class MyClass {\n// ...\n// }\n```\n\n### Key differences\n\n#### Loading mechanism\n\n- **CommonJS**: Synchronous (blocks until loaded).\n- **ESM**: Asynchronous-friendly (non-blocking in browsers).\n\n#### Environment suitability\n\n- **CommonJS**: Node.js legacy standard.\n- **ESM**: Official standard (Browser & Node.js).\n\n#### Syntax\n\n- **CommonJS**: `require()` / `module.exports`.\n- **ESM**: `import` / `export`.\n\n#### Analysis\n\n- **CommonJS**: Dynamic (runtime analysis).\n- **ESM**: Static (compile-time analysis, enables tree-shaking).\n\n### Use cases\n\n#### CommonJS\n\n- Older Node.js projects or where sync loading is needed.\n- Default in Node.js unless configured for ESM.\n\n#### ESM\n\n- Modern web development (native browser support).\n- New Node.js projects, especially those needing async features or optimizations.\n- Code intended for both browser and server.\n\n## Further reading\n\n- [MDN Web Docs on JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n- [Node.js: CommonJS modules](https://nodejs.org/api/modules.html)\n- [Node.js: ESM](https://nodejs.org/api/esm.html)\n- [RequireJS (AMD Loader - Historical)](https://requirejs.org/docs/api.html)\n"
  },
  {
    "path": "questions/what-do-you-think-of-amd-vs-commonjs/metadata.json",
    "content": "{\n  \"slug\": \"what-do-you-think-of-amd-vs-commonjs\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": false,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-do-you-think-of-amd-vs-commonjs/pt-BR.mdx",
    "content": "---\ntitle: O que você acha de AMD versus CommonJS?\n---\n\nAmbas são formas de implementar um sistema de módulos, que não estava nativamente presente em JavaScript até o surgimento da ES2015. CommonJS é síncrono enquanto AMD (Definição de Módulo Assíncrona) é obviamente assíncrona. O CommonJS foi projetado com o desenvolvimento do lado do servidor em mente, enquanto o AMD, com seu suporte para carregamento assíncrono de módulos, é mais destinado a navegadores.\n\nA sintaxe do AMD pode ser bastante verbosa, enquanto o CommonJS é mais próximo do estilo que você usaria em outras linguagens para escrever declarações de importação (import statements). Na maioria das vezes, o AMD é desnecessário, porque se você servir todo o seu JavaScript em um único arquivo de pacote concatenado, não se beneficiará das propriedades de carregamento assíncrono. Além disso, a sintaxe do CommonJS é mais próxima do estilo de escrita/importação de módulos do Node.js e há menos sobrecarga de troca de contexto ao alternar entre o desenvolvimento JavaScript do lado do cliente e do servidor.\n\nO padrão futuro, ES modules (ESM), tem suporte tanto para carregamento síncrono quanto assíncrono e é suportado tanto por navegadores quanto por runtimes do lado do servidor. Finalmente, podemos apenas aderir a uma abordagem (exceto em aplicativos legados).\n"
  },
  {
    "path": "questions/what-do-you-think-of-amd-vs-commonjs/zh-CN.mdx",
    "content": "---\ntitle: 你如何看待 CommonJS 与 ESM？\n---\n\n## TL;DR\n\nJavaScript 已经演进其模块系统。ESM (ECMAScript Modules) 使用 `import` / `export` 是官方标准，在现代浏览器和 Node.js 中原生支持，专为同步和异步用例设计。CommonJS (CJS) 使用 `require` / `module.exports` 是 Node.js 的原始标准，主要用于同步，并且仍然在 Node 生态系统中占主导地位。AMD (Asynchronous Module Definition) 使用 `define` / `require` 是早期为浏览器中的异步加载而设计的系统，但现在已经基本过时，被 ESM 取代。\n\n***\n\n### 概述\n\n模块系统通过允许代码被拆分成具有清晰依赖关系的可重用部分（模块）来帮助管理这种复杂性。随着时间的推移，在官方标准被采用之前，出现了不同的模块系统。\n\n### CommonJS\n\n#### 特点\n\n* 专为同步加载模块而设计\n* 主要用于服务器端环境，如 Node.js\n* 使用 `module.exports` 和 `require` 来定义和加载模块\n\n#### 示例\n\n```javascript\n// 在 CommonJS 中定义一个模块\nconst dep1 = require('dependency1');\nconst dep2 = require('dependency2');\n\nmodule.exports = {\n  // 模块代码在这里\n};\n\n// 在 CommonJS 中加载一个模块\nconst mod1 = require('module1');\nconst mod2 = require('module2');\n\n// 使用 mod1 和 mod2 的代码\n```\n\n### ESM (ECMAScript Modules)\n\n#### 特点\n\n* 官方 JavaScript 标准模块系统\n* 在现代浏览器和 Node.js 中原生支持\n* 专为异步和同步场景设计\n* 使用 `export` 和 `import` 定义和加载模块\n\n#### 示例\n\n```javascript\nimport dep1 from 'dependency1'; // if dependency1 had a default export\nimport { dep2 } from 'dependency2'; // named import to import something specific from dependency2\n\n// Module code using dep1, dep2...\n\nexport function someFunction() {\n  // ... function logic ...\n}\nexport const someValue = 'hello';\n\n// Or export multiple things at once\n// export { someFunction, someValue };\n\n// Or export a default value\n// export default class MyClass {\n// ...\n// }\n```\n\n### 主要区别\n\n#### 加载机制\n\n* **CommonJS**: 同步（加载完成前阻塞）。\n* **ESM**: 异步友好（在浏览器中非阻塞）。\n\n#### 环境适用性\n\n* **CommonJS**: Node.js 遗留标准。\n* **ESM**: 官方标准（浏览器和 Node.js）。\n\n#### 语法\n\n* **CommonJS**: `require()` / `module.exports`。\n* **ESM**: `import` / `export`。\n\n#### 分析\n\n* **CommonJS**: 动态（运行时分析）。\n* **ESM**: 静态（编译时分析，启用 tree-shaking）。\n\n### 用例\n\n#### CommonJS\n\n* 旧的 Node.js 项目或需要同步加载的地方。\n* Node.js 中的默认设置，除非配置为 ESM。\n\n#### ESM\n\n* 现代 Web 开发（原生浏览器支持）。\n* 新的 Node.js 项目，特别是那些需要异步特性或优化的项目。\n* 既用于浏览器又用于服务器的代码。\n\n## 延伸阅读\n\n* [MDN Web Docs on JavaScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n* [Node.js: CommonJS modules](https://nodejs.org/api/modules.html)\n* [Node.js: ESM](https://nodejs.org/api/esm.html)\n* [RequireJS (AMD Loader - Historical)](https://requirejs.org/docs/api.html)\n"
  },
  {
    "path": "questions/what-is-a-closure-and-how-why-would-you-use-one/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"86e9e9c7\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"e9ebe1da\",\n        \"c1c219dd\",\n        \"630e9d15\",\n        \"773802b\",\n        \"6cec583\",\n        \"ac1fd332\",\n        \"2a7816d0\",\n        \"564ad39f\",\n        \"531ffdc\",\n        \"7c3c0cfd\",\n        \"eb7c4eaf\",\n        \"8345ca93\",\n        \"22608380\",\n        \"816f4b7e\",\n        \"f07ed3c2\",\n        \"72df5f77\",\n        \"3f3755cd\",\n        \"947d4f14\",\n        \"bfc3c199\",\n        \"49adb6a1\",\n        \"1f4770e5\",\n        \"d37a144c\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"e9ebe1da\",\n        \"c1c219dd\",\n        \"630e9d15\",\n        \"773802b\",\n        \"6cec583\",\n        \"ac1fd332\",\n        \"2a7816d0\",\n        \"564ad39f\",\n        \"531ffdc\",\n        \"7c3c0cfd\",\n        \"eb7c4eaf\",\n        \"8345ca93\",\n        \"22608380\",\n        \"816f4b7e\",\n        \"f07ed3c2\",\n        \"72df5f77\",\n        \"3f3755cd\",\n        \"947d4f14\",\n        \"bfc3c199\",\n        \"49adb6a1\",\n        \"1f4770e5\",\n        \"d37a144c\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-a-closure-and-how-why-would-you-use-one/en-US.mdx",
    "content": "---\ntitle: What is a closure in JavaScript, and how/why would you use one?\n---\n\n## TL;DR\n\nIn the book [\"You Don't Know JS\"](https://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/scope-closures) (YDKJS) by Kyle Simpson, a closure is defined as follows:\n\n> Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope\n\nIn simple terms, functions have access to variables that were in their scope at the time of their creation. This is what we call the function's lexical scope. A closure is a function that retains access to these variables even after the outer function has finished executing. This is like the function has a memory of its original environment.\n\n```js live\nfunction outerFunction() {\n  const outerVar = 'I am outside of innerFunction';\n\n  function innerFunction() {\n    console.log(outerVar); // `innerFunction` can still access `outerVar`.\n  }\n\n  return innerFunction;\n}\n\nconst inner = outerFunction(); // `inner` now holds a reference to `innerFunction`.\n\ninner(); // \"I am outside of innerFunction\"\n// Even though `outerFunction` has completed execution, `inner` still has access to variables defined inside `outerFunction`.\n```\n\nKey points to remember:\n\n- Closure occurs when an inner function has access to variables in its outer (lexical) scope, even when the outer function has finished executing.\n- Closure allows a function to **remember** the environment in which it was created, even if that environment is no longer present.\n- Closures are used extensively in JavaScript, such as in callbacks, event handlers, and asynchronous functions.\n\n---\n\n## Understanding JavaScript closures\n\nIn JavaScript, a closure is a function that captures the lexical scope in which it was declared, allowing it to access and manipulate variables from an outer scope even after that scope has been closed.\n\nHere's how closures work:\n\n1. **Lexical scoping**: JavaScript uses lexical scoping, meaning a function's access to variables is determined by its actual location within the source code.\n1. **Function creation**: When a function is created, it keeps a reference to its lexical scope. This scope contains all the local variables that were in-scope at the time the closure was created.\n1. **Maintaining state**: Closures are often used to maintain state in a secure way because the variables captured by the closure are not accessible outside the function.\n\n## ES6 syntax and closures\n\nWith ES6, closures can be created using arrow functions, which provide a more concise syntax and lexically bind the `this` value. Here's an example:\n\n```js live\nconst createCounter = () => {\n  let count = 0;\n  return () => {\n    count += 1;\n    return count;\n  };\n};\n\nconst counter = createCounter();\nconsole.log(counter()); // Outputs: 1\nconsole.log(counter()); // Outputs: 2\n```\n\n## Closures in React\n\nClosures are everywhere. Below code shows a simple example of increasing a counter on a button click. In this code, `handleClick` forms a closure. It has access to its outer scope variable `count` and `setCount`.\n\n```jsx\nimport React, { useState } from 'react';\n\nfunction Counter() {\n  // Define a state variable using the useState hook\n  const [count, setCount] = useState(0);\n\n  // This handleClick function is a closure\n  function handleClick() {\n    // It can access the 'count' state variable\n    setCount(count + 1);\n  }\n\n  return (\n    <div>\n      <p>Count: {count}</p>\n      <button onClick={handleClick}>Increment</button>\n    </div>\n  );\n}\n\nfunction App() {\n  return (\n    <div>\n      <h1>Counter App</h1>\n      <Counter />\n    </div>\n  );\n}\n\nexport default App;\n```\n\n## Why use closures?\n\nUsing closures provide the following benefits:\n\n1. **Data encapsulation**: Closures provide a way to create private variables and functions that can't be accessed from outside the closure. This is useful for hiding implementation details and maintaining state in an encapsulated way.\n1. **Functional programming**: Closures are fundamental in functional programming paradigms, where they are used to create functions that can be passed around and invoked later, retaining access to the scope in which they were created, e.g. [partial applications or currying](https://medium.com/javascript-scene/curry-or-partial-application-8150044c78b8#.l4b6l1i3x).\n1. **Event handlers and callbacks**: In JavaScript, closures are often used in event handlers and callbacks to maintain state or access variables that were in scope when the handler or callback was defined.\n1. **Module patterns**: Closures enable the [module pattern](https://www.patterns.dev/vanilla/module-pattern) in JavaScript, allowing the creation of modules with private and public parts.\n\n## Further reading\n\n- [Closures - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n- [Closures - Javascript.info](https://javascript.info/closure)\n- [Closure - Eloquent Javascript](https://eloquentjavascript.net/03_functions.html)\n- [You Don't Know JS Yet: Scope & Closures](https://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/scope-closures)\n"
  },
  {
    "path": "questions/what-is-a-closure-and-how-why-would-you-use-one/metadata.json",
    "content": "{\n  \"slug\": \"what-is-a-closure-and-how-why-would-you-use-one\",\n  \"languages\": [],\n  \"companies\": [\"amazon\", \"linkedin\", \"microsoft\", \"salesforce\", \"bytedance\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"closure\", \"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 180,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-is-a-closure-and-how-why-would-you-use-one/pt-BR.mdx",
    "content": "---\ntitle: O que é um closure e como/por que você usaria um?\n---\n\n## Compreendendo Closures em JavaScript\n\nEm JavaScript, um closure é uma função que captura o escopo léxico no qual foi declarada, permitindo que ela acesse e manipule variáveis de um escopo externo mesmo depois que esse escopo foi fechado.\n\nAqui está como os closures funcionam:\n\n1. **Escopo léxico**: JavaScript utiliza o escopo léxico, o que significa que o acesso de uma função às variáveis é determinado pela sua localização física no código-fonte.\n1. **Criação de função**: Quando uma função é criada, ela mantém uma referência ao seu escopo léxico. Este escopo contém todas as variáveis locais que estavam em escopo no momento em que o closure foi criado.\n1. **Manutenção de estado**: Closures são frequentemente usados para manter o estado de uma forma segura, porque as variáveis capturadas pelo closure não são acessíveis fora da função.\n\nSintaxe do ES6 e closures\n\nCom o ES6, closures podem ser criados usando funções de seta (arrow functions), que proporcionam uma sintaxe mais concisa e vinculam lexicalmente o valor de `this`. Aqui está um exemplo:\n\n```js\nconst criarContador = () => {\n  let contador = 0;\n  return () => {\n    contador += 1;\n    return contador;\n  };\n};\n\nconst contador = criarContador();\nconsole.log(contador()); // Saída: 1\nconsole.log(contador()); // Saída: 2\n```\n\n## Por que usar closures?\n\n1. **Encapsulamento de dados**: Closures fornecem uma maneira de criar variáveis e funções privadas que não podem ser acessadas fora do closure. Isso é útil para ocultar detalhes de implementação e manter o estado de forma encapsulada.\n1. **Programação funcional**: Closures são fundamentais em paradigmas de programação funcional, onde são usados para criar funções que podem ser passadas e invocadas posteriormente, mantendo o acesso ao escopo em que foram criadas, por exemplo, [aplicações parciais ou currying](https://medium.com/javascript-scene/curry-or-partial-application-8150044c78b8#.l4b6l1i3x).\n1. **Manipuladores de eventos e callbacks**: Em JavaScript, closures são frequentemente usados em manipuladores de eventos e callbacks para manter o estado ou acessar variáveis que estavam em escopo quando o manipulador ou callback foi definido.\n1. **Padrões de módulo**: Closures permitem o uso do [padrão de módulo](https://www.patterns.dev/vanilla/module-pattern) em JavaScript, possibilitando a criação de módulos com partes privadas e públicas.\n"
  },
  {
    "path": "questions/what-is-a-closure-and-how-why-would-you-use-one/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中的闭包是什么？你将如何/为什么要使用它？\n---\n\n## TL;DR\n\n在 Kyle Simpson 撰写的 [\"You Don't Know JS\"](https://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/scope-closures) (YDKJS) 一书中，闭包定义如下：\n\n> 闭包是指一个函数能够记住并访问其词法作用域，即使该函数在其词法作用域之外执行\n\n简单来说，函数可以访问它们在创建时在其作用域中的变量。 这就是我们所说的函数的词法作用域。 闭包是一个函数，即使外部函数执行完毕后，它仍然保留对这些变量的访问权限。 这就像函数记住了它最初的环境。\n\n```js live\nfunction outerFunction() {\n  const outerVar = '我位于 innerFunction 之外';\n\n  function innerFunction() {\n    console.log(outerVar); // `innerFunction` 仍然可以访问 `outerVar`。\n  }\n\n  return innerFunction;\n}\n\nconst inner = outerFunction(); // `inner` 现在持有对 `innerFunction` 的引用。\n\ninner(); // \"我位于 innerFunction 之外\"\n// 即使 `outerFunction` 已经执行完毕，`inner` 仍然可以访问在 `outerFunction` 内部定义的变量。\n```\n\n要记住的关键点：\n\n* 当内部函数可以访问其外部（词法）作用域中的变量时，就会发生闭包，即使外部函数已经执行完毕。\n* 闭包允许一个函数**记住**它被创建的环境，即使该环境不再存在。\n* 闭包在 JavaScript 中被广泛使用，例如在回调、事件处理程序和异步函数中。\n\n***\n\n## 了解 JavaScript 闭包\n\n在 JavaScript 中，闭包是一个捕获其声明的词法作用域的函数，允许它访问和操作来自外部作用域的变量，即使该作用域已关闭。\n\n以下是闭包的工作原理：\n\n1. **词法作用域**：JavaScript 使用词法作用域，这意味着函数对变量的访问由其在源代码中的实际位置决定。\n2. **函数创建**：当创建一个函数时，它会保留对其词法作用域的引用。 此作用域包含在创建闭包时在其作用域中的所有局部变量。\n3. **维护状态**：闭包通常用于以安全的方式维护状态，因为闭包捕获的变量在函数外部不可访问。\n\n## ES6 语法和闭包\n\n使用 ES6，可以使用箭头函数创建闭包，这提供了更简洁的语法并以词法方式绑定 `this` 值。 这是一个例子：\n\n```js live\nconst createCounter = () => {\n  let count = 0;\n  return () => {\n    count += 1;\n    return count;\n  };\n};\n\nconst counter = createCounter();\nconsole.log(counter()); // 输出：1\nconsole.log(counter()); // 输出：2\n```\n\n## React 中的闭包\n\n闭包无处不在。 下面的代码显示了一个在单击按钮时增加计数器的简单示例。 在此代码中，`handleClick` 形成一个闭包。 它可以访问其外部作用域变量 `count` 和 `setCount`\n\n```jsx\nimport React, { useState } from 'react';\n\nfunction Counter() {\n  // 使用 useState 钩子定义一个状态变量\n  const [count, setCount] = useState(0);\n\n  // 此 handleClick 函数是一个闭包\n  function handleClick() {\n    // 它可以访问 'count' 状态变量\n    setCount(count + 1);\n  }\n\n  return (\n    <div>\n      <p>Count: {count}</p>\n      <button onClick={handleClick}>Increment</button>\n    </div>\n  );\n}\n\nfunction App() {\n  return (\n    <div>\n      <h1>Counter App</h1>\n      <Counter />\n    </div>\n  );\n}\n\nexport default App;\n```\n\n## 为什么使用闭包？\n\n使用闭包提供以下好处：\n\n1. **数据封装**：闭包提供了一种创建私有变量和函数的方法，这些变量和函数无法从闭包外部访问。这对于隐藏实现细节并以封装的方式维护状态非常有用。\n2. **函数式编程**：闭包是函数式编程范例的基础，它们用于创建可以传递和稍后调用的函数，保留对创建它们的范围的访问权限，例如 [部分应用或柯里化](https://medium.com/javascript-scene/curry-or-partial-application-8150044c78b8#.l4b6l1i3x)。\n3. **事件处理程序和回调**：在 JavaScript 中，闭包通常用于事件处理程序和回调，以维护状态或访问在定义处理程序或回调时作用域中的变量。\n4. **模块模式**：闭包在 JavaScript 中启用 [模块模式](https://www.patterns.dev/vanilla/module-pattern)，允许创建具有私有和公共部分的模块。\n\n## 延伸阅读\n\n* [闭包 - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n* [闭包 - Javascript.info](https://javascript.info/closure)\n* [闭包 - Eloquent Javascript](https://eloquentjavascript.net/03_functions.html)\n* [你还不了解 JS：作用域和闭包](https://github.com/getify/You-Dont-Know-JS/tree/2nd-ed/scope-closures)\n"
  },
  {
    "path": "questions/what-is-asyncawait-and-how-does-it-simplify-asynchronous-code/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"ebd9ecc9\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"41e5b333\",\n        \"27f732be\",\n        \"2a7816d0\",\n        \"b46a6d8c\",\n        \"5fddcf9c\",\n        \"ed0c0a4d\",\n        \"d42e4283\",\n        \"e7d91d8d\",\n        \"295f1e70\",\n        \"849553db\",\n        \"3ce58a7e\",\n        \"27f732be\",\n        \"8c7b0ca\",\n        \"c2b2f508\",\n        \"879dbb14\",\n        \"e8e49a6a\",\n        \"91118d44\",\n        \"27f732be\",\n        \"c019b9d8\",\n        \"8a2ab78c\",\n        \"e5cb6842\",\n        \"1f4770e5\",\n        \"19b59749\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"41e5b333\",\n        \"27f732be\",\n        \"2a7816d0\",\n        \"b46a6d8c\",\n        \"5fddcf9c\",\n        \"ed0c0a4d\",\n        \"d42e4283\",\n        \"e7d91d8d\",\n        \"295f1e70\",\n        \"849553db\",\n        \"3ce58a7e\",\n        \"27f732be\",\n        \"8c7b0ca\",\n        \"c2b2f508\",\n        \"879dbb14\",\n        \"e8e49a6a\",\n        \"91118d44\",\n        \"27f732be\",\n        \"c019b9d8\",\n        \"8a2ab78c\",\n        \"e5cb6842\",\n        \"1f4770e5\",\n        \"19b59749\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-asyncawait-and-how-does-it-simplify-asynchronous-code/en-US.mdx",
    "content": "---\ntitle: What is async/await and how does it simplify asynchronous code?\n---\n\n## TL;DR\n\n`async/await` is a modern syntax in JavaScript that simplifies working with promises. By using the `async` keyword before a function, you can use the `await` keyword inside that function to pause execution until a promise is resolved. This makes asynchronous code look and behave more like synchronous code, making it easier to read and maintain.\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/posts/1',\n    );\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\nfetchData();\n```\n\n---\n\n## What is async/await and how does it simplify asynchronous code?\n\n### Introduction to async/await\n\n`async/await` is a feature introduced in ECMAScript 2017 (ES8) that allows you to write asynchronous code in a more synchronous-looking manner. It is built on top of promises and provides a cleaner and more readable way to handle asynchronous operations.\n\n### Using the `async` keyword\n\nThe `async` keyword is used to declare an asynchronous function. When a function is declared as `async`, it automatically returns a promise. This means you can use the `await` keyword inside it to pause the execution of the function until a promise is resolved.\n\n```js live\nasync function exampleFunction() {\n  return 'Hello, World!';\n}\n\nexampleFunction().then(console.log); // Output: Hello, World!\n```\n\n### Using the `await` keyword\n\nThe `await` keyword can only be used inside an `async` function. It pauses the execution of the function until the promise is resolved, and then returns the resolved value. If the promise is rejected, it throws an error, which can be caught using a `try...catch` block.\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/posts/1',\n    );\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\nfetchData();\n```\n\n### Simplifying asynchronous code\n\nBefore `async/await`, handling asynchronous operations often involved chaining multiple `.then()` calls, which could lead to \"callback hell\" or \"pyramid of doom.\" `async/await` flattens this structure, making the code more readable and easier to maintain.\n\n#### Example with promises\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/posts/1')\n  .then((response) => response.json())\n  .then((data) => {\n    console.log(data);\n  })\n  .catch((error) => {\n    console.error('Error fetching data:', error);\n  });\n```\n\n#### Example with async/await\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/posts/1',\n    );\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\nfetchData();\n```\n\n### Error handling\n\nError handling with `async/await` is more straightforward compared to promises. You can use `try...catch` blocks to handle errors, making the code cleaner and more intuitive.\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch('https://jsonplaceholder.typicod.com/posts/1'); // Typo in URL\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\nfetchData();\n```\n\n## Further reading\n\n- [MDN Web Docs: async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)\n- [MDN Web Docs: await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)\n- [JavaScript.info: Async/await](https://javascript.info/async-await)\n"
  },
  {
    "path": "questions/what-is-asyncawait-and-how-does-it-simplify-asynchronous-code/metadata.json",
    "content": "{\n  \"slug\": \"what-is-asyncawait-and-how-does-it-simplify-asynchronous-code\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"async\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Asynchronous JavaScript\"\n}\n"
  },
  {
    "path": "questions/what-is-asyncawait-and-how-does-it-simplify-asynchronous-code/zh-CN.mdx",
    "content": "---\ntitle: 什么是 async/await 以及它如何简化异步代码？\n---\n\n## TL;DR\n\n`async/await` 是 JavaScript 中一种现代语法，它简化了处理 Promise 的过程。通过在函数前使用 `async` 关键字，你可以在该函数中使用 `await` 关键字来暂停执行，直到 Promise 被解析。这使得异步代码看起来更像同步代码，并且行为也更像同步代码，从而更容易阅读和维护。\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/posts/1',\n    );\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\nfetchData();\n```\n\n***\n\n## 什么是 async/await 以及它如何简化异步代码？\n\n### async/await 简介\n\n`async/await` 是 ECMAScript 2017 (ES8) 中引入的一个特性，它允许你以更像同步的方式编写异步代码。它建立在 Promise 的基础上，并提供了一种更清晰、更易读的方式来处理异步操作。\n\n### 使用 `async` 关键字\n\n`async` 关键字用于声明一个异步函数。当一个函数被声明为 `async` 时，它会自动返回一个 Promise。这意味着你可以在其中使用 `await` 关键字来暂停函数的执行，直到 Promise 被解析。\n\n```js live\nasync function exampleFunction() {\n  return 'Hello, World!';\n}\n\nexampleFunction().then(console.log); // Output: Hello, World!\n```\n\n### 使用 `await` 关键字\n\n`await` 关键字只能在 `async` 函数中使用。它会暂停函数的执行，直到 Promise 被解析，然后返回解析后的值。如果 Promise 被拒绝，它会抛出一个错误，可以使用 `try...catch` 块捕获该错误。\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/posts/1',\n    );\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\nfetchData();\n```\n\n### 简化异步代码\n\n在 `async/await` 之前，处理异步操作通常涉及链接多个 `.then()` 调用，这可能导致“回调地狱”或“金字塔式厄运”。`async/await` 扁平化了这种结构，使代码更易读，更易于维护。\n\n#### 使用 Promise 的示例\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/posts/1')\n  .then((response) => response.json())\n  .then((data) => {\n    console.log(data);\n  })\n  .catch((error) => {\n    console.error('Error fetching data:', error);\n  });\n```\n\n#### 使用 async/await 的示例\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/posts/1',\n    );\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\nfetchData();\n```\n\n### 错误处理\n\n与 Promise 相比，使用 `async/await` 进行错误处理更直接。你可以使用 `try...catch` 块来处理错误，使代码更清晰、更直观。\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch('https://jsonplaceholder.typicod.com/posts/1'); // Typo in URL\n    const data = await response.json();\n    console.log(data);\n  } catch (error) {\n    console.error('Error fetching data:', error);\n  }\n}\nfetchData();\n```\n\n## 延伸阅读\n\n* [MDN Web 文档：async function](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function)\n* [MDN Web 文档：await](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/await)\n* [JavaScript.info：Async/await](https://zh.javascript.info/async-await)\n"
  },
  {
    "path": "questions/what-is-cross-site-scripting-xss-and-how-can-you-prevent-it/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"66b77b6c\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"cac99c70\",\n        \"2a7816d0\",\n        \"bcad4891\",\n        \"42351ede\",\n        \"caa5f823\",\n        \"5c64601a\",\n        \"638202f1\",\n        \"a4539dd5\",\n        \"f6920b05\",\n        \"22f3d69f\",\n        \"f7e4a1e4\",\n        \"3c9d9bf0\",\n        \"d556bcf7\",\n        \"cb379252\",\n        \"34e2ef73\",\n        \"28157379\",\n        \"3498d072\",\n        \"7916bd14\",\n        \"25511d3a\",\n        \"8630d54\",\n        \"16a53600\",\n        \"76a97e5e\",\n        \"f5ec4fbc\",\n        \"1f4770e5\",\n        \"5971802e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"cac99c70\",\n        \"2a7816d0\",\n        \"bcad4891\",\n        \"42351ede\",\n        \"caa5f823\",\n        \"5c64601a\",\n        \"638202f1\",\n        \"a4539dd5\",\n        \"f6920b05\",\n        \"22f3d69f\",\n        \"f7e4a1e4\",\n        \"3c9d9bf0\",\n        \"d556bcf7\",\n        \"cb379252\",\n        \"34e2ef73\",\n        \"28157379\",\n        \"3498d072\",\n        \"7916bd14\",\n        \"25511d3a\",\n        \"8630d54\",\n        \"16a53600\",\n        \"76a97e5e\",\n        \"f5ec4fbc\",\n        \"1f4770e5\",\n        \"5971802e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-cross-site-scripting-xss-and-how-can-you-prevent-it/en-US.mdx",
    "content": "---\ntitle: What is Cross-Site Scripting (XSS) and how can you prevent it?\n---\n\n## TL;DR\n\nCross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users. This can lead to data theft, session hijacking, and other malicious activities. To prevent XSS, you should validate and sanitize user inputs, use Content Security Policy (CSP), and escape data before rendering it in the browser.\n\n---\n\n## What is Cross-Site Scripting (XSS) and how can you prevent it?\n\n### What is Cross-Site Scripting (XSS)?\n\nCross-Site Scripting (XSS) is a type of security vulnerability typically found in web applications. It allows attackers to inject malicious scripts into content from otherwise trusted websites. These scripts can then be executed in the context of the user's browser, leading to various malicious activities such as:\n\n- Stealing cookies and session tokens\n- Defacing websites\n- Redirecting users to malicious sites\n- Logging keystrokes\n\nThere are three main types of XSS attacks:\n\n1. **Stored XSS**: The malicious script is permanently stored on the target server, such as in a database, comment field, or forum post.\n2. **Reflected XSS**: The malicious script is reflected off a web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server.\n3. **DOM-based XSS**: The vulnerability exists in the client-side code rather than the server-side code. The malicious script is executed as a result of modifying the DOM environment in the victim's browser.\n\n### How can you prevent XSS?\n\n#### Validate and sanitize user inputs\n\nAlways validate and sanitize user inputs to ensure they do not contain malicious code. Use libraries and frameworks that provide built-in functions for input validation and sanitization.\n\n```js\nconst sanitizeHtml = require('sanitize-html');\n\nconst cleanInput = sanitizeHtml(userInput);\n```\n\n#### Use Content Security Policy (CSP)\n\nA Content Security Policy (CSP) is a security feature that helps prevent XSS attacks by specifying which dynamic resources are allowed to load. This can be done by setting HTTP headers.\n\n```http\nContent-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com;\n```\n\n#### Escape data before rendering\n\nAlways escape data before rendering it in the browser to prevent the execution of malicious scripts. Use functions provided by your framework or library to escape HTML, JavaScript, and other content.\n\n```js\nconst escapeHtml = (str) => {\n  return str\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;')\n    .replace(/'/g, '&#039;');\n};\n\nconst safeOutput = escapeHtml(userInput);\n```\n\n#### Use HTTP-only cookies\n\nSet cookies to be HTTP-only to prevent client-side scripts from accessing them. This can help mitigate the risk of session hijacking.\n\n```http\nSet-Cookie: sessionId=abc123; HttpOnly;\n```\n\n#### Regularly update dependencies\n\nKeep your libraries and frameworks up to date to ensure you have the latest security patches and features.\n\n## Further reading\n\n- [OWASP XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)\n- [MDN Web Docs: Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n- [Google Web Fundamentals: Preventing XSS](https://developers.google.com/web/fundamentals/security/csp)\n"
  },
  {
    "path": "questions/what-is-cross-site-scripting-xss-and-how-can-you-prevent-it/metadata.json",
    "content": "{\n  \"slug\": \"what-is-cross-site-scripting-xss-and-how-can-you-prevent-it\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"security\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Security\"\n}\n"
  },
  {
    "path": "questions/what-is-cross-site-scripting-xss-and-how-can-you-prevent-it/zh-CN.mdx",
    "content": "---\ntitle: 什么是跨站脚本 (XSS) 以及如何防止它？\n---\n\n## TL;DR\n\n跨站脚本 (XSS) 是一种安全漏洞，它允许攻击者将恶意脚本注入到其他用户查看的网页中。这可能导致数据盗窃、会话劫持和其他恶意活动。为了防止 XSS，您应该验证和清理用户输入，使用内容安全策略 (CSP)，并在浏览器中渲染数据之前转义它。\n\n***\n\n## 什么是跨站脚本 (XSS) 以及如何防止它？\n\n### 什么是跨站脚本 (XSS)？\n\n跨站脚本 (XSS) 是一种通常在 Web 应用程序中发现的安全漏洞。它允许攻击者将恶意脚本注入到来自其他可信网站的内容中。然后，这些脚本可以在用户浏览器的上下文中执行，从而导致各种恶意活动，例如：\n\n* 窃取 cookie 和会话令牌\n* 篡改网站\n* 将用户重定向到恶意网站\n* 记录击键\n\nXSS 攻击主要有三种类型：\n\n1. **存储型 XSS**：恶意脚本永久存储在目标服务器上，例如数据库、评论字段或论坛帖子中。\n2. **反射型 XSS**：恶意脚本从 Web 服务器反射出来，例如在错误消息、搜索结果或任何其他包含发送到服务器的部分或全部输入的响应中。\n3. **基于 DOM 的 XSS**：漏洞存在于客户端代码中，而不是服务器端代码中。恶意脚本由于修改受害者浏览器中的 DOM 环境而执行。\n\n### 如何防止 XSS？\n\n#### 验证和清理用户输入\n\n始终验证和清理用户输入，以确保它们不包含恶意代码。使用提供用于输入验证和清理的内置功能的库和框架。\n\n```js\nconst sanitizeHtml = require('sanitize-html');\n\nconst cleanInput = sanitizeHtml(userInput);\n```\n\n#### 使用内容安全策略 (CSP)\n\n内容安全策略 (CSP) 是一项安全功能，它通过指定允许加载哪些动态资源来帮助防止 XSS 攻击。这可以通过设置 HTTP 标头来完成。\n\n```http\nContent-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com;\n```\n\n#### 渲染前转义数据\n\n在浏览器中渲染数据之前，请务必转义数据，以防止恶意脚本的执行。使用框架或库提供的函数来转义 HTML、JavaScript 和其他内容。\n\n```js\nconst escapeHtml = (str) => {\n  return str\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;')\n    .replace(/'/g, '&#039;');\n};\n\nconst safeOutput = escapeHtml(userInput);\n```\n\n#### 使用 HTTP-only Cookie\n\n将 Cookie 设置为 HTTP-only，以防止客户端脚本访问它们。这有助于降低会话劫持的风险。\n\n```http\nSet-Cookie: sessionId=abc123; HttpOnly;\n```\n\n#### 定期更新依赖项\n\n保持您的库和框架为最新状态，以确保您拥有最新的安全补丁和功能。\n\n## 延伸阅读\n\n* [OWASP XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)\n* [MDN Web Docs: Content Security Policy (CSP)](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)\n* [Google Web Fundamentals: Preventing XSS](https://developers.google.com/web/fundamentals/security/csp)\n"
  },
  {
    "path": "questions/what-is-currying-and-how-does-it-work/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"2b23906f\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"22f638\",\n        \"5bb10ab8\",\n        \"2a7816d0\",\n        \"7308c54e\",\n        \"25841bc3\",\n        \"b10bb752\",\n        \"4e8ede6c\",\n        \"50bb31e2\",\n        \"8bd49e92\",\n        \"d7958ab6\",\n        \"5c367c22\",\n        \"5ae28d01\",\n        \"e9625e0d\",\n        \"5e8a7e51\",\n        \"60551088\",\n        \"63278240\",\n        \"84cdaeec\",\n        \"3c9d8ac8\",\n        \"1150d83c\",\n        \"1f4770e5\",\n        \"222c7cdf\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"22f638\",\n        \"5bb10ab8\",\n        \"2a7816d0\",\n        \"7308c54e\",\n        \"25841bc3\",\n        \"b10bb752\",\n        \"4e8ede6c\",\n        \"50bb31e2\",\n        \"8bd49e92\",\n        \"d7958ab6\",\n        \"5c367c22\",\n        \"5ae28d01\",\n        \"e9625e0d\",\n        \"5e8a7e51\",\n        \"60551088\",\n        \"63278240\",\n        \"84cdaeec\",\n        \"3c9d8ac8\",\n        \"1150d83c\",\n        \"1f4770e5\",\n        \"222c7cdf\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-currying-and-how-does-it-work/en-US.mdx",
    "content": "---\ntitle: What is currying and how does it work?\n---\n\n## TL;DR\n\nCurrying is a technique in functional programming where a function that takes multiple arguments is transformed into a series of functions that each take a single argument. This allows for partial application of functions. For example, a function `f(a, b, c)` can be curried into `f(a)(b)(c)`. Here's a simple example in JavaScript:\n\n```js live\nfunction add(a) {\n  return function (b) {\n    return function (c) {\n      return a + b + c;\n    };\n  };\n}\n\nconst addOne = add(1);\nconsole.log(addOne); // function object\n\nconst addOneAndTwo = addOne(2);\nconsole.log(addOneAndTwo); // function object\n\nconst result = addOneAndTwo(3);\nconsole.log(result); // Output: 6\n```\n\n---\n\n## What is currying and how does it work?\n\n### Definition\n\nCurrying is a functional programming technique where a function with multiple arguments is decomposed into a sequence of functions, each taking a single argument. This allows for the partial application of functions, enabling more flexible and reusable code.\n\n### How it works\n\n1. **Transformation**: A function that takes multiple arguments is transformed into a series of nested functions, each taking one argument.\n2. **Partial application**: You can call the curried function with fewer arguments than it expects, and it will return a new function that takes the remaining arguments.\n\n### Example in JavaScript\n\nHere's a simple example to illustrate currying in JavaScript:\n\n```js live\n// Non-curried function\nfunction add(a, b, c) {\n  return a + b + c;\n}\n\n// Curried version of the same function\nfunction curriedAdd(a) {\n  return function (b) {\n    return function (c) {\n      return a + b + c;\n    };\n  };\n}\n\n// Using the curried function\nconst addOne = curriedAdd(1);\nconsole.log(addOne); // function object\n\nconst addOneAndTwo = addOne(2);\nconsole.log(addOneAndTwo); // function object\n\nconst result = addOneAndTwo(3);\nconsole.log(result); // Output: 6\n```\n\n### Benefits of currying\n\n1. **Reusability**: Curried functions can be reused with different sets of arguments.\n2. **Partial application**: You can create new functions by fixing some arguments of the original function.\n3. **Function composition**: Currying makes it easier to compose functions, leading to more readable and maintainable code.\n\n### Practical example\n\nConsider a function that calculates the volume of a rectangular prism:\n\n```js live\nfunction volume(length, width, height) {\n  return length * width * height;\n}\n\n// Curried version\nfunction curriedVolume(length) {\n  return function (width) {\n    return function (height) {\n      return length * width * height;\n    };\n  };\n}\n\n// Using the curried function\nconst volumeWithLength5 = curriedVolume(5);\nconst volumeWithLength5AndWidth4 = volumeWithLength5(4);\nconst result = volumeWithLength5AndWidth4(3);\nconsole.log(result); // Output: 60\n```\n\n### Currying with arrow functions\n\nYou can also use arrow functions to make the syntax more concise:\n\n```js live\nconst curriedAdd = (a) => (b) => (c) => a + b + c;\n\nconst addOne = curriedAdd(1);\nconst addOneAndTwo = addOne(2);\nconst result = addOneAndTwo(3);\nconsole.log(result); // Output: 6\n```\n\n## Further reading\n\n- [JavaScript.info: Currying](https://javascript.info/currying-partials)\n- [Functional Programming in JavaScript: Currying](https://www.sitepoint.com/currying-in-functional-javascript/)\n"
  },
  {
    "path": "questions/what-is-currying-and-how-does-it-work/metadata.json",
    "content": "{\n  \"slug\": \"what-is-currying-and-how-does-it-work\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"closure\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Currying & Partial Application\"\n}\n"
  },
  {
    "path": "questions/what-is-currying-and-how-does-it-work/zh-CN.mdx",
    "content": "---\ntitle: 什么是柯里化以及它如何工作？\n---\n\n## TL;DR\n\n柯里化是函数式编程中的一种技术，它将接受多个参数的函数转换为一系列只接受单个参数的函数。这允许函数的局部应用。例如，函数 `f(a, b, c)` 可以柯里化为 `f(a)(b)(c)`。以下是 JavaScript 中的一个简单示例：\n\n```js live\nfunction add(a) {\n  return function (b) {\n    return function (c) {\n      return a + b + c;\n    };\n  };\n}\n\nconst addOne = add(1);\nconsole.log(addOne); // function object\n\nconst addOneAndTwo = addOne(2);\nconsole.log(addOneAndTwo); // function object\n\nconst result = addOneAndTwo(3);\nconsole.log(result); // Output: 6\n```\n\n***\n\n## 什么是柯里化以及它如何工作？\n\n### 定义\n\n柯里化是一种函数式编程技术，其中具有多个参数的函数被分解为一系列函数，每个函数接受一个参数。这允许函数的局部应用，从而实现更灵活和可重用的代码。\n\n### 工作原理\n\n1. **转换**：接受多个参数的函数被转换为一系列嵌套函数，每个函数接受一个参数。\n2. **局部应用**：你可以使用比预期更少的参数来调用柯里化函数，它将返回一个接受剩余参数的新函数。\n\n### JavaScript 示例\n\n这是一个简单的例子，说明了 JavaScript 中的柯里化：\n\n```js live\n// Non-curried function\nfunction add(a, b, c) {\n  return a + b + c;\n}\n\n// Curried version of the same function\nfunction curriedAdd(a) {\n  return function (b) {\n    return function (c) {\n      return a + b + c;\n    };\n  };\n}\n\n// Using the curried function\nconst addOne = curriedAdd(1);\nconsole.log(addOne); // function object\n\nconst addOneAndTwo = addOne(2);\nconsole.log(addOneAndTwo); // function object\n\nconst result = addOneAndTwo(3);\nconsole.log(result); // Output: 6\n```\n\n### 柯里化的好处\n\n1. **可重用性**：柯里化函数可以与不同的参数集一起重用。\n2. **局部应用**：你可以通过修复原始函数的某些参数来创建新函数。\n3. **函数组合**：柯里化使组合函数更容易，从而使代码更具可读性和可维护性。\n\n### 实际例子\n\n考虑一个计算长方体体积的函数：\n\n```js live\nfunction volume(length, width, height) {\n  return length * width * height;\n}\n\n// Curried version\nfunction curriedVolume(length) {\n  return function (width) {\n    return function (height) {\n      return length * width * height;\n    };\n  };\n}\n\n// Using the curried function\nconst volumeWithLength5 = curriedVolume(5);\nconst volumeWithLength5AndWidth4 = volumeWithLength5(4);\nconst result = volumeWithLength5AndWidth4(3);\nconsole.log(result); // Output: 60\n```\n\n### 使用箭头函数的柯里化\n\n你也可以使用箭头函数使语法更简洁：\n\n```js live\nconst curriedAdd = (a) => (b) => (c) => a + b + c;\n\nconst addOne = curriedAdd(1);\nconst addOneAndTwo = addOne(2);\nconst result = addOneAndTwo(3);\nconsole.log(result); // Output: 6\n```\n\n## 延伸阅读\n\n* [JavaScript.info: Currying](https://javascript.info/currying-partials)\n* [Functional Programming in JavaScript: Currying](https://www.sitepoint.com/currying-in-functional-javascript/)\n"
  },
  {
    "path": "questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"6e248f9d\",\n    \"subtitle\": \"f876ddcf\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"4c4ebaf7\",\n        \"def8dd56\",\n        \"2b3223fd\",\n        \"5060e7da\",\n        \"910dc689\",\n        \"2a7816d0\",\n        \"ffd9a88\",\n        \"64f1c549\",\n        \"c2d9aba1\",\n        \"15825e2b\",\n        \"899e50f3\",\n        \"a105fc91\",\n        \"45224a96\",\n        \"99faad6d\",\n        \"db9d9907\",\n        \"6947fcaa\",\n        \"a9aad61d\",\n        \"64d5eaa4\",\n        \"45d5f59e\",\n        \"2291669d\",\n        \"9b5019f0\",\n        \"6d42a6f4\",\n        \"62c85188\",\n        \"1cab2f63\",\n        \"a83e4e49\",\n        \"1a302627\",\n        \"2a5e83d7\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4c4ebaf7\",\n        \"def8dd56\",\n        \"2b3223fd\",\n        \"5060e7da\",\n        \"910dc689\",\n        \"2a7816d0\",\n        \"ffd9a88\",\n        \"64f1c549\",\n        \"c2d9aba1\",\n        \"15825e2b\",\n        \"899e50f3\",\n        \"a105fc91\",\n        \"45224a96\",\n        \"99faad6d\",\n        \"db9d9907\",\n        \"6947fcaa\",\n        \"a9aad61d\",\n        \"64d5eaa4\",\n        \"45d5f59e\",\n        \"2291669d\",\n        \"9b5019f0\",\n        \"6d42a6f4\",\n        \"62c85188\",\n        \"1cab2f63\",\n        \"a83e4e49\",\n        \"1a302627\",\n        \"2a5e83d7\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/en-US.mdx",
    "content": "---\ntitle: What is the event loop in JavaScript runtimes?\nsubtitle: What is the difference between call stack and task queue?\n---\n\n## TL;DR\n\nThe event loop is a concept within the JavaScript runtime environment regarding how asynchronous operations are executed within JavaScript engines. It works as such:\n\n1. The JavaScript engine starts executing scripts, placing synchronous operations on the call stack.\n2. When an asynchronous operation is encountered (e.g., `setTimeout()`, HTTP request), it is offloaded to the respective Web API or Node.js API to handle the operation in the background.\n3. Once the asynchronous operation completes, its callback function is placed in the respective queues – task queues (also known as macrotask queues / callback queues) or microtask queues. We will refer to \"task queue\" as \"macrotask queue\" from here on to better differentiate from the microtask queue.\n4. The event loop continuously monitors the call stack and executes items on the call stack. If/when the call stack is empty:\n   1. Microtask queue is processed. Microtasks include promise callbacks (`then`, `catch`, `finally`), `MutationObserver` callbacks, and calls to `queueMicrotask()`. The event loop takes the first callback from the microtask queue and pushes it to the call stack for execution. This repeats until the microtask queue is empty.\n   2. Macrotask queue is processed. Macrotasks include web APIs like `setTimeout()`, HTTP requests, user interface event handlers like clicks, scrolls, etc. The event loop dequeues the first callback from the macrotask queue and pushes it onto the call stack for execution. However, after a macrotask queue callback is processed, the event loop does not proceed with the next macrotask yet! The event loop first checks the microtask queue. Checking the microtask queue is necessary as microtasks have higher priority than macrotask queue callbacks. The macrotask queue callback that was just executed could have added more microtasks!\n      1. If the microtask queue is non-empty, process them as per the previous step.\n      2. If the microtask queue is empty, the next macrotask queue callback is processed. This repeats until the macrotask queue is empty.\n5. This process continues indefinitely, allowing the JavaScript engine to handle both synchronous and asynchronous operations efficiently without blocking the call stack.\n\nThe unfortunate truth is that it is extremely hard to explain the event loop well using only text. We recommend checking out one of the following excellent videos explaining the event loop:\n\n- [JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue](https://www.youtube.com/watch?v=eiC58R16hb8) (2024): Lydia Hallie is a popular educator on JavaScript and this is the best recent video explaining the event loop. There's also an [accompanying blog post](https://www.lydiahallie.com/blog/event-loop) for those who prefer detailed text-based explanations.\n- [In the Loop](https://www.youtube.com/watch?v=cCOL7MC4Pl0) (2018): Jake Archibald previously from the Chrome team provides a visual demonstration of the event loop during JSConf 2018, accounting for different types of tasks.\n- [What the heck is the event loop anyway?](https://www.youtube.com/watch?v=8aGhZQkoFbQ) (2014): Philip Robert's gave this epic talk at JSConf 2014 and it is one of the most viewed JavaScript videos on YouTube.\n\nWe recommend watching [Lydia's video](https://www.youtube.com/watch?v=eiC58R16hb8) as it is the most modern and concise explanation standing at only 13 minutes long whereas the other videos are at least 30 minutes long. Her video is sufficient for the purpose of interviews.\n\n---\n\n## Event loop in JavaScript\n\nThe event loop is the heart of JavaScript's asynchronous operation. It is a mechanism that handles the execution of code, allowing for asynchronous operations and ensuring that the single-threaded nature of JavaScript engines does not block the execution of the program.\n\n### Parts of the event loop\n\nTo understand it better we need to understand about all the parts of the system. These components are part of the event loop:\n\n#### Call stack\n\nCall stack keeps track of the functions being executed in a program. When a function is called, it is added to the top of the call stack. When the function completes, it is removed from the call stack. This allows the program to keep track of where it is in the execution of a function and return to the correct location when the function completes. As the name suggests it is a Stack data structure which follows last-in-first-out.\n\n#### Web APIs/Node.js APIs\n\nAsynchronous operations like `setTimeout()`, HTTP requests, file I/O, etc., are handled by Web APIs (in the browser) or C++ APIs (in Node.js). These APIs are not part of the JavaScript engine and run on separate threads, allowing them to execute concurrently without blocking the call stack.\n\n#### Task queue / Macrotask queue / Callback queue\n\nThe task queue, also known as the macrotask queue / callback queue / event queue, is a queue that holds tasks that need to be executed. These tasks are typically asynchronous operations, such as callbacks passed to web APIs (`setTimeout()`, `setInterval()`, HTTP requests, etc.), and user interface event handlers like clicks, scrolls, etc.\n\n#### Microtasks queue\n\nMicrotasks are tasks that have a higher priority than macrotasks and are executed immediately after the currently executing script is completed and before the next macrotask is executed. Microtasks are usually used for more immediate, lightweight operations that should be executed as soon as possible after the current operation completes. There is a dedicated microtask queue for microtasks. Microtasks include promises callbacks (`then()`, `catch()`, and `finally()`), `await` statements, `queueMicrotask()`, and `MutationObserver` callbacks.\n\n### Event loop order\n\n1. The JavaScript engine starts executing scripts, placing synchronous operations on the call stack.\n2. When an asynchronous operation is encountered (e.g., `setTimeout()`, HTTP request), it is offloaded to the respective Web API or Node.js API to handle the operation in the background.\n3. Once the asynchronous operation completes, its callback function is placed in the respective queues – task queues (also known as macrotask queues / callback queues) or microtask queues. We will refer to \"task queue\" as \"macrotask queue\" from here on to better differentiate from the microtask queue.\n4. The event loop continuously monitors the call stack and executes items on the call stack. If/when the call stack is empty:\n   1. Microtask queue is processed. The event loop takes the first callback from the microtask queue and pushes it to the call stack for execution. This repeats until the microtask queue is empty.\n   2. Macrotask queue is processed. The event loop dequeues the first callback from the macrotask queue and pushes it onto the call stack for execution. However, after a macrotask queue callback is processed, the event loop does not proceed with the next macrotask yet! The event loop first checks the microtask queue. Checking the microtask queue is necessary as microtasks have higher priority than macrotask queue callbacks. The macrotask queue callback that was just executed could have added more microtasks!\n      1. If the microtask queue is non-empty, process them as per the previous step.\n      2. If the microtask queue is empty, the next macrotask queue callback is processed. This repeats until the macrotask queue is empty.\n5. This process continues indefinitely, allowing the JavaScript engine to handle both synchronous and asynchronous operations efficiently without blocking the call stack.\n\n### Example\n\nThe following code logs some statements using a combination of normal execution, macrotasks, and microtasks.\n\n```js live\nconsole.log('Start');\n\nsetTimeout(() => {\n  console.log('Timeout 1');\n}, 0);\n\nPromise.resolve().then(() => {\n  console.log('Promise 1');\n});\n\nsetTimeout(() => {\n  console.log('Timeout 2');\n}, 0);\n\nconsole.log('End');\n\n// Console output:\n// Start\n// End\n// Promise 1\n// Timeout 1\n// Timeout 2\n```\n\nExplanation of the output:\n\n1. `Start` and `End` are logged first because they are part of the initial script.\n1. `Promise 1` is logged next because promises are microtasks and microtasks are executed immediately after the items on the call stack.\n1. `Timeout 1` and `Timeout 2` are logged last because they are macrotasks and are processed after the microtasks.\n\n## Further reading and resources\n\n- [The event loop - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop)\n- [The Node.js Event Loop](https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick)\n- [Event loop: microtasks and macrotasks](https://javascript.info/event-loop)\n- [JavaScript Visualized: Event Loop by Lydia Hallie](https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif)\n- [\"JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue\" by Lydia Hallie](https://www.lydiahallie.com/blog/event-loop)\n- [\"What the heck is the event loop anyway?\" by Philip Robert](https://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html)\n- [\"In The Loop\" by Jake Archibald](https://www.youtube.com/watch?v=cCOL7MC4Pl0)\n"
  },
  {
    "path": "questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/metadata.json",
    "content": "{\n  \"slug\": \"what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue\",\n  \"languages\": [],\n  \"companies\": [\"amazon\", \"salesforce\", \"google\", \"tiktok\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 40,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/pt-BR.mdx",
    "content": "---\ntitle: O que é o loop de eventos?\nsubtitle: Qual é a diferença entre call stack e task queue?\n---\n\nO loop de eventos é um laço de execução única (single-threaded) que monitora a pilha de chamadas e verifica se há algum trabalho a ser feito na fila de tarefas. Se a pilha de chamadas estiver vazia e houver funções de retorno de chamada (callback) na fila de tarefas, uma função é desenfileirada e colocada na pilha de chamadas para ser executada.\n\nSe você ainda não conferiu as [palestras sobre o loop de eventos](https://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-heck-is-the-event-loop-anyway.html), você deveria. É um dos vídeos mais vistos de JavaScript.\n"
  },
  {
    "path": "questions/what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 运行时中的事件循环是什么？\nsubtitle: call stack 和 task queue 之间有什么区别？\n---\n\n## TL;DR\n\n事件循环是JavaScript运行时环境中的一个概念，涉及异步操作如何在JavaScript引擎中执行。它的工作原理如下：\n\n1. JavaScript 引擎开始执行脚本，将同步操作放在调用堆栈上。\n2. 当遇到异步操作（例如，`setTimeout()`、HTTP 请求）时，它会被卸载到相应的 Web API 或 Node.js API，以在后台处理该操作。\n3. 一旦异步操作完成，其回调函数将被放置在相应的队列中——任务队列（也称为宏任务队列/回调队列）或微任务队列。从这里开始，我们将“任务队列”称为“宏任务队列”，以便更好地与微任务队列区分开来。\n4. 事件循环持续监视调用堆栈并执行调用堆栈上的项目。如果/当调用堆栈为空时：\n   1. 处理微任务队列。微任务包括 promise 回调（`then`、`catch`、`finally`）、`MutationObserver` 回调和对 `queueMicrotask()` 的调用。事件循环从微任务队列中获取第一个回调并将其推送到调用堆栈以供执行。重复此操作，直到微任务队列为空。\n   2. 处理宏任务队列。宏任务包括 Web API，如 `setTimeout()`、HTTP 请求、用户界面事件处理程序，如点击、滚动等。事件循环从宏任务队列中出列第一个回调并将其推送到调用堆栈以供执行。但是，在处理完宏任务队列回调后，事件循环不会继续处理下一个宏任务！事件循环首先检查微任务队列。检查微任务队列是必要的，因为微任务的优先级高于宏任务队列回调。刚刚执行的宏任务队列回调可能添加了更多微任务！\n      1. 如果微任务队列非空，则按上一步处理它们。\n      2. 如果微任务队列为空，则处理下一个宏任务队列回调。重复此操作，直到宏任务队列为空。\n5. 此过程无限期地持续进行，允许 JavaScript 引擎高效地处理同步和异步操作，而不会阻塞调用堆栈。\n\n不幸的是，仅使用文本很难很好地解释事件循环。我们建议查看以下优秀的视频之一，解释事件循环：\n\n* [JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue](https://www.youtube.com/watch?v=eiC58R16hb8) (2024): Lydia Hallie 是一个受欢迎的 JavaScript 教育者，这是最近解释事件循环的最佳视频。对于那些喜欢详细的基于文本的解释的人，还有一个[随附的博客文章](https://www.lydiahallie.com/blog/event-loop)。\n* [In the Loop](https://www.youtube.com/watch?v=cCOL7MC4Pl0) (2018): 来自 Chrome 团队的 Jake Archibald 在 JSConf 2018 期间提供了事件循环的视觉演示，解释了不同类型的任务。\n* [What the heck is the event loop anyway?](https://www.youtube.com/watch?v=8aGhZQkoFbQ) (2014): Philip Robert 在 JSConf 2014 上发表了这次史诗般的演讲，这是 YouTube 上观看次数最多的 JavaScript 视频之一。\n\n我们建议观看 [Lydia 的视频](https://www.youtube.com/watch?v=eiC58R16hb8)，因为它是最现代和简洁的解释，时长仅为 13 分钟，而其他视频至少需要 30 分钟。她的视频足以满足面试的目的。\n\n***\n\n## JavaScript 中的事件循环\n\n事件循环是 JavaScript 异步操作的核心。它是一种处理代码执行的机制，允许异步操作并确保 JavaScript 引擎的单线程性质不会阻塞程序的执行。\n\n### 事件循环的组成部分\n\n为了更好地理解它，我们需要了解系统的所有组成部分。这些组件是事件循环的一部分：\n\n#### 调用堆栈\n\n调用堆栈跟踪程序中正在执行的函数。当调用一个函数时，它被添加到调用堆栈的顶部。当函数完成时，它将从调用堆栈中删除。这允许程序跟踪它在函数执行中的位置，并在函数完成时返回到正确的位置。顾名思义，它是一个遵循后进先出的堆栈数据结构。\n\n#### Web API/Node.js API\n\n异步操作，如 `setTimeout()`、HTTP 请求、文件 I/O 等，由 Web API（在浏览器中）或 C++ API（在 Node.js 中）处理。这些 API 不是 JavaScript 引擎的一部分，并且在单独的线程上运行，允许它们并发执行而不会阻塞调用堆栈。\n\n#### 任务队列 / 宏任务队列 / 回调队列\n\n任务队列，也称为宏任务队列/回调队列/事件队列，是一个保存需要执行的任务的队列。这些任务通常是异步操作，例如传递给 Web API 的回调（`setTimeout()`、`setInterval()`、HTTP 请求等）以及用户界面事件处理程序，如点击、滚动等。\n\n#### 微任务队列\n\nMicrotasks 是比 macrotasks 具有更高优先级的任务，它们在当前执行的脚本完成之后、下一个 macrotask 执行之前立即执行。Microtasks 通常用于更即时、轻量级的操作，这些操作应在当前操作完成后尽快执行。有一个专门用于 microtasks 的 microtask 队列。Microtasks 包括 promise 回调（`then()`、`catch()` 和 `finally()`）、`await` 语句、`queueMicrotask()` 和 `MutationObserver` 回调。\n\n### 事件循环顺序\n\n1. JavaScript 引擎开始执行脚本，将同步操作放在调用堆栈上。\n2. 当遇到异步操作（例如，`setTimeout()`、HTTP 请求）时，它会被卸载到相应的 Web API 或 Node.js API，以在后台处理该操作。\n3. 一旦异步操作完成，其回调函数将被放置在相应的队列中——任务队列（也称为 macrotask 队列/回调队列）或 microtask 队列。从这里开始，我们将“任务队列”称为“macrotask 队列”，以便更好地与 microtask 队列区分开来。\n4. 事件循环持续监视调用堆栈并执行调用堆栈上的项目。如果/当调用堆栈为空时：\n   1. microtask 队列被处理。事件循环从 microtask 队列中获取第一个回调，并将其推送到调用堆栈以供执行。这将重复进行，直到 microtask 队列为空。\n   2. macrotask 队列被处理。事件循环从 macrotask 队列中取出第一个回调，并将其推送到调用堆栈上以供执行。但是，在处理完 macrotask 队列回调之后，事件循环不会继续处理下一个 macrotask！事件循环首先检查 microtask 队列。检查 microtask 队列是必要的，因为 microtasks 的优先级高于 macrotask 队列回调。刚刚执行的 macrotask 队列回调可能添加了更多 microtasks！\n      1. 如果 microtask 队列非空，则按上一步处理它们。\n      2. 如果 microtask 队列为空，则处理下一个 macrotask 队列回调。这将重复进行，直到 macrotask 队列为空。\n5. 此过程无限期地持续进行，允许 JavaScript 引擎高效地处理同步和异步操作，而不会阻塞调用堆栈。\n\n### 示例\n\n以下代码使用正常执行、macrotasks 和 microtasks 的组合来记录一些语句。\n\n```js live\nconsole.log('Start');\n\nsetTimeout(() => {\n  console.log('Timeout 1');\n}, 0);\n\nPromise.resolve().then(() => {\n  console.log('Promise 1');\n});\n\nsetTimeout(() => {\n  console.log('Timeout 2');\n}, 0);\n\nconsole.log('End');\n\n// Console output:\n// Start\n// End\n// Promise 1\n// Timeout 1\n// Timeout 2\n```\n\n输出说明：\n\n1. `Start` 和 `End` 首先被记录，因为它们是初始脚本的一部分。\n2. `Promise 1` 接下来被记录，因为 promises 是 microtasks，并且 microtasks 在调用堆栈上的项目之后立即执行。\n3. `Timeout 1` 和 `Timeout 2` 最后被记录，因为它们是 macrotasks，并且在 microtasks 之后被处理。\n\n## 延伸阅读和资源\n\n* [事件循环 - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop)\n* [Node.js 事件循环](https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick)\n* [事件循环：microtasks 和 macrotasks](https://javascript.info/event-loop)\n* [JavaScript 可视化：Lydia Hallie 的事件循环](https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif)\n* [Lydia Hallie 的“JavaScript 可视化 - 事件循环、Web API、（Micro）任务队列”](https://www.lydiahallie.com/blog/event-loop)\n* [Philip Robert 的“到底什么是事件循环？”](https://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html)\n* [Jake Archibald 的“In The Loop”](https://www.youtube.com/watch?v=cCOL7MC4Pl0)\n"
  },
  {
    "path": "questions/what-is-objectfreeze-for/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"387067ab\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"6fc051ad\",\n        \"89292305\",\n        \"2a7816d0\",\n        \"d0fe993e\",\n        \"8782f836\",\n        \"ce03d00f\",\n        \"76b63abf\",\n        \"c455986b\",\n        \"ff2f44b9\",\n        \"48645dc2\",\n        \"fdf8df7d\",\n        \"5c47d964\",\n        \"5fedbc8e\",\n        \"d0b0f464\",\n        \"31c4eae4\",\n        \"1f4770e5\",\n        \"bb864a58\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"6fc051ad\",\n        \"89292305\",\n        \"2a7816d0\",\n        \"d0fe993e\",\n        \"8782f836\",\n        \"ce03d00f\",\n        \"76b63abf\",\n        \"c455986b\",\n        \"ff2f44b9\",\n        \"48645dc2\",\n        \"fdf8df7d\",\n        \"5c47d964\",\n        \"5fedbc8e\",\n        \"d0b0f464\",\n        \"31c4eae4\",\n        \"1f4770e5\",\n        \"bb864a58\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-objectfreeze-for/en-US.mdx",
    "content": "---\ntitle: What is `Object.freeze()` for?\n---\n\n## TL;DR\n\n`Object.freeze()` is used to make an object immutable. Once an object is frozen, you cannot add, remove, or modify its properties. This is useful for creating constants or ensuring that an object remains unchanged throughout the program.\n\n```js live\nconst obj = { name: 'John' };\nObject.freeze(obj);\nobj.name = 'Doe'; // This will not change the name property\n\nconsole.log(obj); // { name: 'John' }\n```\n\n---\n\n## What is `Object.freeze()` for?\n\n`Object.freeze()` is a method in JavaScript that prevents modification of existing property values and the addition or removal of properties from an object. This method is useful for creating immutable objects, which can help in maintaining the integrity of data and avoiding unintended side effects.\n\n### How to use `Object.freeze()`\n\nTo use `Object.freeze()`, simply pass the object you want to freeze as an argument to the method. Here is a basic example:\n\n```js live\nconst obj = {\n  name: 'John',\n  age: 30,\n};\n\nObject.freeze(obj);\n\nobj.name = 'Doe'; // This will not change the name property\nobj.gender = 'male'; // This will not add a new property\ndelete obj.age; // This will not delete the age property\n\nconsole.log(obj); // Output: { name: \"John\", age: 30 }\n```\n\n### Characteristics of a frozen object\n\n1. **Immutability**: Once an object is frozen, its properties cannot be changed, added, or removed.\n2. **Non-extensible**: A frozen object is also non-extensible, meaning you cannot add new properties to it.\n3. **Non-configurable**: The properties of a frozen object become non-configurable, meaning you cannot change property descriptors.\n\n### Use cases for `Object.freeze()`\n\n1. **Constants**: When you want to create a constant object that should not be modified.\n2. **Data integrity**: Ensuring that an object remains unchanged throughout the lifecycle of an application.\n3. **Security**: Preventing accidental or malicious changes to critical objects.\n\n### Limitations\n\n- `Object.freeze()` only makes the object itself immutable. If the object contains nested objects, those nested objects are not frozen and can still be modified.\n- To deeply freeze an object, you would need to recursively apply `Object.freeze()` to all nested objects.\n\n```js live\nconst deepFreeze = (obj) => {\n  Object.keys(obj).forEach((key) => {\n    if (typeof obj[key] === 'object' && obj[key] !== null) {\n      deepFreeze(obj[key]);\n    }\n  });\n  return Object.freeze(obj);\n};\n\nconst nestedObj = {\n  name: 'John',\n  details: {\n    age: 30,\n    address: '123 Street',\n  },\n};\n\ndeepFreeze(nestedObj);\n\nnestedObj.details.age = 31; // This will not change the age property\nconsole.log(nestedObj); // Output: { name: \"John\", details: { age: 30, address: \"123 Street\" } }\n```\n\n## Further reading\n\n- [MDN Web Docs on Object.freeze()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)\n- [JavaScript.info on property flags and descriptors](https://javascript.info/property-descriptors)\n- [Deep freezing objects in JavaScript](https://medium.com/@saranshkataria/deep-freezing-objects-in-javascript-637f3d4d7d7)\n"
  },
  {
    "path": "questions/what-is-objectfreeze-for/metadata.json",
    "content": "{\n  \"slug\": \"what-is-objectfreeze-for\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/what-is-objectfreeze-for/zh-CN.mdx",
    "content": "---\ntitle: 什么是 `Object.freeze()`？\n---\n\n## TL;DR\n\n`Object.freeze()` 用于使对象不可变。一旦对象被冻结，您就不能添加、删除或修改其属性。这对于创建常量或确保对象在整个程序中保持不变非常有用。\n\n```js live\nconst obj = { name: 'John' };\nObject.freeze(obj);\nobj.name = 'Doe'; // This will not change the name property\n\nconsole.log(obj); // { name: 'John' }\n```\n\n***\n\n## 什么是 `Object.freeze()`？\n\n`Object.freeze()` 是 JavaScript 中的一种方法，它阻止修改现有属性值以及向对象添加或删除属性。此方法对于创建不可变对象非常有用，这有助于维护数据的完整性并避免意外的副作用。\n\n### 如何使用 `Object.freeze()`\n\n要使用 `Object.freeze()`，只需将要冻结的对象作为参数传递给该方法。这是一个基本示例：\n\n```js live\nconst obj = {\n  name: 'John',\n  age: 30,\n};\n\nObject.freeze(obj);\n\nobj.name = 'Doe'; // This will not change the name property\nobj.gender = 'male'; // This will not add a new property\ndelete obj.age; // This will not delete the age property\n\nconsole.log(obj); // Output: { name: \"John\", age: 30 }\n```\n\n### 冻结对象的特征\n\n1. **不可变性**：一旦对象被冻结，其属性就不能被更改、添加或删除。\n2. **不可扩展性**：冻结对象也是不可扩展的，这意味着您不能向其添加新属性。\n3. **不可配置性**：冻结对象的属性变为不可配置，这意味着您不能更改属性描述符。\n\n### `Object.freeze()` 的用例\n\n1. **常量**：当您想要创建一个不应被修改的常量对象时。\n2. **数据完整性**：确保对象在应用程序的整个生命周期中保持不变。\n3. **安全性**：防止对关键对象的意外或恶意更改。\n\n### 局限性\n\n* `Object.freeze()` 仅使对象本身不可变。如果对象包含嵌套对象，则这些嵌套对象不会被冻结，并且仍然可以被修改。\n* 要深度冻结一个对象，您需要递归地将 `Object.freeze()` 应用于所有嵌套对象。\n\n```js live\nconst deepFreeze = (obj) => {\n  Object.keys(obj).forEach((key) => {\n    if (typeof obj[key] === 'object' && obj[key] !== null) {\n      deepFreeze(obj[key]);\n    }\n  });\n  return Object.freeze(obj);\n};\n\nconst nestedObj = {\n  name: 'John',\n  details: {\n    age: 30,\n    address: '123 Street',\n  },\n};\n\ndeepFreeze(nestedObj);\n\nnestedObj.details.age = 31; // This will not change the age property\nconsole.log(nestedObj); // Output: { name: \"John\", details: { age: 30, address: \"123 Street\" } }\n```\n\n## 延伸阅读\n\n* [MDN Web Docs on Object.freeze()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)\n* [JavaScript.info on property flags and descriptors](https://javascript.info/property-descriptors)\n* [Deep freezing objects in JavaScript](https://medium.com/@saranshkataria/deep-freezing-objects-in-javascript-637f3d4d7d7)\n"
  },
  {
    "path": "questions/what-is-objectpreventextensions-for/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"cb95f296\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3ab63977\",\n        \"f1d4bfb5\",\n        \"2a7816d0\",\n        \"63511b89\",\n        \"84f5ef47\",\n        \"eea083fa\",\n        \"9fc52d61\",\n        \"8e3d9efb\",\n        \"7cd5becb\",\n        \"12fde400\",\n        \"9b5019f0\",\n        \"20ba114f\",\n        \"6c218584\",\n        \"c0fd2f59\",\n        \"5b03ae9a\",\n        \"6dd3b324\",\n        \"b938c573\",\n        \"1f4770e5\",\n        \"f80b8521\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3ab63977\",\n        \"f1d4bfb5\",\n        \"2a7816d0\",\n        \"63511b89\",\n        \"84f5ef47\",\n        \"eea083fa\",\n        \"9fc52d61\",\n        \"8e3d9efb\",\n        \"7cd5becb\",\n        \"12fde400\",\n        \"9b5019f0\",\n        \"20ba114f\",\n        \"6c218584\",\n        \"c0fd2f59\",\n        \"5b03ae9a\",\n        \"6dd3b324\",\n        \"b938c573\",\n        \"1f4770e5\",\n        \"f80b8521\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-objectpreventextensions-for/en-US.mdx",
    "content": "---\ntitle: What is `Object.preventExtensions()` for?\n---\n\n## TL;DR\n\n`Object.preventExtensions()` is a method in JavaScript that prevents new properties from being added to an object. However, it does not affect the deletion or modification of existing properties. This method is useful when you want to ensure that an object remains in a certain shape and no additional properties can be added to it.\n\n```js live\nconst obj = { name: 'John' };\nObject.preventExtensions(obj);\n\nobj.age = 30; // This will not work, as the object is not extensible\nconsole.log(obj.age); // undefined\n```\n\n---\n\n## What is `Object.preventExtensions()` for?\n\n`Object.preventExtensions()` is a method in JavaScript that is used to prevent new properties from being added to an object. This method is part of the ECMAScript 5 specification and is useful for maintaining the integrity of an object by ensuring that its structure cannot be altered by adding new properties.\n\n### Syntax\n\n```js\nObject.preventExtensions(obj);\n```\n\n- `obj`: The object which should be made non-extensible.\n\n### Behavior\n\n- Once an object is made non-extensible, you cannot add new properties to it.\n- Existing properties can still be modified or deleted.\n- The method returns the object that was passed to it.\n\n### Example\n\n```js live\nconst obj = { name: 'John' };\nObject.preventExtensions(obj);\n\nobj.age = 30; // This will not work, as the object is not extensible\nconsole.log(obj.age); // undefined\n\nobj.name = 'Jane'; // This will work, as existing properties can be modified\nconsole.log(obj.name); // 'Jane'\n\ndelete obj.name; // This will work, as existing properties can be deleted\nconsole.log(obj.name); // undefined\n```\n\n### Checking if an object is extensible\n\nYou can check if an object is extensible using the `Object.isExtensible()` method.\n\n```js live\nconst obj = { name: 'John' };\nconsole.log(Object.isExtensible(obj)); // true\n\nObject.preventExtensions(obj);\nconsole.log(Object.isExtensible(obj)); // false\n```\n\n### Use cases\n\n- **Immutable object structure**: When you want to ensure that the structure of an object remains unchanged, you can use `Object.preventExtensions()`.\n- **Security**: Preventing extensions can be useful in scenarios where you want to avoid accidental or malicious addition of properties to an object.\n\n## Further reading\n\n- [MDN Web Docs: Object.preventExtensions()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions)\n- [MDN Web Docs: Object.isExtensible()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible)\n- [ECMAScript 5 Specification](https://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.10)\n"
  },
  {
    "path": "questions/what-is-objectpreventextensions-for/metadata.json",
    "content": "{\n  \"slug\": \"what-is-objectpreventextensions-for\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/what-is-objectpreventextensions-for/zh-CN.mdx",
    "content": "---\ntitle: 什么是 `Object.preventExtensions()`？\n---\n\n## TL;DR\n\n`Object.preventExtensions()` 是 JavaScript 中的一个方法，用于阻止向对象添加新属性。但是，它不会影响现有属性的删除或修改。当您希望确保对象保持特定形状并且不能向其添加其他属性时，此方法非常有用。\n\n```js live\nconst obj = { name: 'John' };\nObject.preventExtensions(obj);\n\nobj.age = 30; // 这将不起作用，因为该对象不可扩展\nconsole.log(obj.age); // undefined\n```\n\n***\n\n## 什么是 `Object.preventExtensions()`？\n\n`Object.preventExtensions()` 是 JavaScript 中用于阻止向对象添加新属性的方法。此方法是 ECMAScript 5 规范的一部分，通过确保其结构不能通过添加新属性来更改，从而有助于维护对象的完整性。\n\n### 语法\n\n```js\nObject.preventExtensions(obj);\n```\n\n* `obj`：应该设置为不可扩展的对象。\n\n### 行为\n\n* 一旦对象设置为不可扩展，您就无法向其添加新属性。\n* 现有属性仍然可以被修改或删除。\n* 该方法返回传递给它的对象。\n\n### 示例\n\n```js live\nconst obj = { name: 'John' };\nObject.preventExtensions(obj);\n\nobj.age = 30; // 这将不起作用，因为该对象不可扩展\nconsole.log(obj.age); // undefined\n\nobj.name = 'Jane'; // 这将起作用，因为现有属性可以被修改\nconsole.log(obj.name); // 'Jane'\n\ndelete obj.name; // 这将起作用，因为现有属性可以被删除\nconsole.log(obj.name); // undefined\n```\n\n### 检查对象是否可扩展\n\n您可以使用 `Object.isExtensible()` 方法检查对象是否可扩展。\n\n```js live\nconst obj = { name: 'John' };\nconsole.log(Object.isExtensible(obj)); // true\n\nObject.preventExtensions(obj);\nconsole.log(Object.isExtensible(obj)); // false\n```\n\n### 用例\n\n* **不可变对象结构**：当您希望确保对象的结构保持不变时，可以使用 `Object.preventExtensions()`。\n* **安全性**：在您希望避免意外或恶意向对象添加属性的情况下，阻止扩展可能很有用。\n\n## 延伸阅读\n\n* [MDN Web 文档：Object.preventExtensions()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions)\n* [MDN Web 文档：Object.isExtensible()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible)\n* [ECMAScript 5 规范](https://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.10)\n"
  },
  {
    "path": "questions/what-is-objectseal-for/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"68a2c348\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"d8480c8e\",\n        \"c24c2894\",\n        \"2a7816d0\",\n        \"e396005b\",\n        \"57b87a82\",\n        \"eea083fa\",\n        \"a930a435\",\n        \"d78264ca\",\n        \"7cd5becb\",\n        \"77dc1f43\",\n        \"9b5019f0\",\n        \"6e070efe\",\n        \"6dd3b324\",\n        \"3709738\",\n        \"66d14e8c\",\n        \"2d01636c\",\n        \"3c810770\",\n        \"1f4770e5\",\n        \"db716abf\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d8480c8e\",\n        \"c24c2894\",\n        \"2a7816d0\",\n        \"e396005b\",\n        \"57b87a82\",\n        \"eea083fa\",\n        \"a930a435\",\n        \"d78264ca\",\n        \"7cd5becb\",\n        \"77dc1f43\",\n        \"9b5019f0\",\n        \"6e070efe\",\n        \"6dd3b324\",\n        \"3709738\",\n        \"66d14e8c\",\n        \"2d01636c\",\n        \"3c810770\",\n        \"1f4770e5\",\n        \"db716abf\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-objectseal-for/en-US.mdx",
    "content": "---\ntitle: What is `Object.seal()` for?\n---\n\n## TL;DR\n\n`Object.seal()` is used to prevent new properties from being added to an object and to mark all existing properties as non-configurable. This means you can still modify the values of existing properties, but you cannot delete them or add new ones. Doing so will throw errors in strict mode but fail silently in non-strict mode. In the following examples, you can uncomment the 'use strict' comment to see this.\n\n```js live\n// 'use strict'\n\nconst obj = { name: 'John' };\nObject.seal(obj);\n\nobj.name = 'Jane'; // Allowed\nobj.age = 30; // Not allowed, throws an error in strict mode\ndelete obj.name; // Not allowed, throws an error in strict mode\n\nconsole.log(obj); // { name: 'Jane } (unchanged)\n```\n\n---\n\n## What is `Object.seal()` for?\n\n`Object.seal()` is a method in JavaScript that seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. This means that while you can still modify the values of existing properties, you cannot delete them or add new properties.\n\n### Syntax\n\n```js\nObject.seal(obj);\n```\n\n- `obj`: The object to be sealed.\n\n### Behavior\n\n1. **Preventing new properties**: Once an object is sealed, you cannot add new properties to it.\n2. **Non-configurable properties**: All existing properties become non-configurable, meaning you cannot delete them or change their property descriptors (e.g., making them non-writable).\n3. **Modifiable values**: You can still change the values of existing properties as long as they are writable.\n\n### Example\n\n```js live\n// 'use strict'\n\nconst person = {\n  name: 'Alice',\n  age: 25,\n};\n\nObject.seal(person);\n\nperson.name = 'Bob'; // Allowed\nperson.age = 30; // Allowed\n\nperson.gender = 'female'; // Not allowed, throws an error in strict mode\ndelete person.name; // Not allowed, throws an error in strict mode\n\nconsole.log(person); // { name: 'Bob', age: 30 } (unchanged)\n```\n\n### Use cases\n\n- **Data integrity**: Ensuring that an object structure remains unchanged, which can be useful in scenarios where the object represents a fixed schema.\n- **Security**: Preventing accidental or malicious modifications to an object, especially in shared or global contexts.\n\n### Checking if an object is sealed\n\nYou can check if an object is sealed using the `Object.isSealed()` method.\n\n```js live\nconst obj = { name: 'John' };\nObject.seal(obj);\n\nconsole.log(Object.isSealed(obj)); // true\n```\n\n## Further reading\n\n- [MDN Web Docs on Object.seal()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)\n- [MDN Web Docs on Object.isSealed()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed)\n- [JavaScript.info on property flags and descriptors](https://javascript.info/property-descriptors)\n"
  },
  {
    "path": "questions/what-is-objectseal-for/metadata.json",
    "content": "{\n  \"slug\": \"what-is-objectseal-for\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Objects & Arrays\"\n}\n"
  },
  {
    "path": "questions/what-is-objectseal-for/zh-CN.mdx",
    "content": "---\ntitle: 什么是 `Object.seal()`？\n---\n\n## 总结\n\n`Object.seal()` 用于防止向对象添加新属性，并将所有现有属性标记为不可配置。这意味着您仍然可以修改现有属性的值，但不能删除它们或添加新属性。这样做会在严格模式下抛出错误，但在非严格模式下会静默失败。在以下示例中，您可以取消注释 'use strict' 注释以查看此情况。\n\n```js live\n// 'use strict'\n\nconst obj = { name: 'John' };\nObject.seal(obj);\n\nobj.name = 'Jane'; // 允许\nobj.age = 30; // 不允许，在严格模式下抛出错误\ndelete obj.name; // 不允许，在严格模式下抛出错误\n\nconsole.log(obj); // { name: 'Jane } (未更改)\n```\n\n***\n\n## 什么是 `Object.seal()`？\n\n`Object.seal()` 是 JavaScript 中的一个方法，用于密封一个对象，防止向其添加新属性，并将所有现有属性标记为不可配置。这意味着虽然您仍然可以修改现有属性的值，但您不能删除它们或添加新属性。\n\n### 语法\n\n```js\nObject.seal(obj);\n```\n\n* `obj`：要密封的对象。\n\n### 行为\n\n1. **防止新属性**：一旦对象被密封，您就不能向其添加新属性。\n2. **不可配置的属性**：所有现有属性都变为不可配置，这意味着您不能删除它们或更改它们的属性描述符（例如，使它们不可写）。\n3. **可修改的值**：只要现有属性是可写的，您仍然可以更改它们的值。\n\n### 示例\n\n```js live\n// 'use strict'\n\nconst person = {\n  name: 'Alice',\n  age: 25,\n};\n\nObject.seal(person);\n\nperson.name = 'Bob'; // 允许\nperson.age = 30; // 允许\n\nperson.gender = 'female'; // 不允许，在严格模式下抛出错误\ndelete person.name; // 不允许，在严格模式下抛出错误\n\nconsole.log(person); // { name: 'Bob', age: 30 } (未更改)\n```\n\n### 用例\n\n* **数据完整性**：确保对象结构保持不变，这在对象表示固定模式的情况下非常有用。\n* **安全性**：防止对对象的意外或恶意修改，尤其是在共享或全局上下文中。\n\n### 检查对象是否被密封\n\n您可以使用 `Object.isSealed()` 方法检查对象是否被密封。\n\n```js live\nconst obj = { name: 'John' };\nObject.seal(obj);\n\nconsole.log(Object.isSealed(obj)); // true\n```\n\n## 延伸阅读\n\n* [MDN Web Docs on Object.seal()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)\n* [MDN Web Docs on Object.isSealed()](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed)\n* [JavaScript.info on property flags and descriptors](https://zh.javascript.info/property-descriptors)\n"
  },
  {
    "path": "questions/what-is-recursion-and-how-is-it-used-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"3415acfd\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"f8a354e7\",\n        \"dd6bfbb1\",\n        \"2a7816d0\",\n        \"f71bd92b\",\n        \"577bd600\",\n        \"b6f1cf0a\",\n        \"f2830112\",\n        \"d0921512\",\n        \"25e35290\",\n        \"2486e3d8\",\n        \"f7047d85\",\n        \"9ec2712c\",\n        \"d7d7f5a4\",\n        \"d6f9cc4f\",\n        \"8cb0f0b3\",\n        \"f7047d85\",\n        \"bb5db012\",\n        \"2426fa10\",\n        \"294c83f9\",\n        \"7e555b3a\",\n        \"8dc0d887\",\n        \"7010e576\",\n        \"1f4770e5\",\n        \"931c8614\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"f8a354e7\",\n        \"dd6bfbb1\",\n        \"2a7816d0\",\n        \"f71bd92b\",\n        \"577bd600\",\n        \"b6f1cf0a\",\n        \"f2830112\",\n        \"d0921512\",\n        \"25e35290\",\n        \"2486e3d8\",\n        \"f7047d85\",\n        \"9ec2712c\",\n        \"d7d7f5a4\",\n        \"d6f9cc4f\",\n        \"8cb0f0b3\",\n        \"f7047d85\",\n        \"bb5db012\",\n        \"2426fa10\",\n        \"294c83f9\",\n        \"7e555b3a\",\n        \"8dc0d887\",\n        \"7010e576\",\n        \"1f4770e5\",\n        \"931c8614\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-recursion-and-how-is-it-used-in-javascript/en-US.mdx",
    "content": "---\ntitle: What is recursion and how is it used in JavaScript?\n---\n\n## TL;DR\n\nRecursion is a programming technique where a function calls itself to solve a problem. In JavaScript, recursion is used to solve problems that can be broken down into smaller, similar sub-problems. A base case is essential to stop the recursive calls and prevent infinite loops. For example, calculating the factorial of a number can be done using recursion:\n\n```js live\nfunction factorial(n) {\n  if (n === 0) {\n    return 1;\n  }\n  return n * factorial(n - 1);\n}\n\nconsole.log(factorial(4)); // Output: 24\n```\n\n---\n\n## What is recursion and how is it used in JavaScript?\n\n### Definition of recursion\n\nRecursion is a technique in programming where a function calls itself in order to solve a problem. This approach is particularly useful for problems that can be divided into smaller, similar sub-problems. The key components of a recursive function are:\n\n- **Base case**: The condition under which the function stops calling itself, preventing an infinite loop.\n- **Recursive case**: The part of the function where it calls itself with a modified argument, moving towards the base case.\n\n### Example: Calculating factorial\n\nThe factorial of a number `n` (denoted as `n!`) is the product of all positive integers less than or equal to `n`. It can be defined recursively as:\n\n- `0! = 1` (base case)\n- `n! = n * (n - 1)!` for `n > 0` (recursive case)\n\nHere is how you can implement this in JavaScript:\n\n```js live\nfunction factorial(n) {\n  if (n === 0) {\n    // base case\n    return 1;\n  }\n  return n * factorial(n - 1); // recursive case\n}\n\nconsole.log(factorial(4)); // Output: 24\n```\n\n### Example: Fibonacci sequence\n\nThe Fibonacci sequence is another classic example of recursion. Each number in the sequence is the sum of the two preceding ones, usually starting with 0 and 1. The sequence can be defined recursively as:\n\n- `fib(0) = 0` (base case)\n- `fib(1) = 1` (base case)\n- `fib(n) = fib(n - 1) + fib(n - 2)` for `n > 1` (recursive case)\n\nHere is how you can implement this in JavaScript:\n\n```js live\nfunction fibonacci(n) {\n  if (n === 0) {\n    // base case\n    return 0;\n  }\n  if (n === 1) {\n    // base case\n    return 1;\n  }\n  return fibonacci(n - 1) + fibonacci(n - 2); // recursive case\n}\n\nconsole.log(fibonacci(6)); // Output: 8\n```\n\n### Tail recursion\n\nTail recursion is a special form of recursion where the recursive call is the last operation in the function. This can be optimized by some JavaScript engines to improve performance and prevent stack overflow. Here is an example of a tail-recursive factorial function:\n\n```js live\nfunction factorial(n, acc = 1) {\n  if (n === 0) {\n    return acc;\n  }\n  return factorial(n - 1, n * acc);\n}\n\nconsole.log(factorial(4)); // Output: 24\n```\n\n### Use cases for recursion\n\n- **Tree traversal**: Recursion is often used to traverse tree structures, such as the DOM or binary trees.\n- **Divide and conquer algorithms**: Algorithms like quicksort and mergesort use recursion to divide the problem into smaller sub-problems.\n- **Dynamic programming**: Problems like the knapsack problem and certain graph algorithms can be solved using recursion.\n\n## Further reading\n\n- [MDN Web Docs: Recursion](https://developer.mozilla.org/en-US/docs/Glossary/Recursion)\n- [JavaScript.info: Recursion and stack](https://javascript.info/recursion)\n- [Eloquent JavaScript: Recursion](https://eloquentjavascript.net/03_functions.html#h_recursion)\n"
  },
  {
    "path": "questions/what-is-recursion-and-how-is-it-used-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"what-is-recursion-and-how-is-it-used-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"recursion\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Functions\"\n}\n"
  },
  {
    "path": "questions/what-is-recursion-and-how-is-it-used-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: 什么是递归以及它在 JavaScript 中如何使用？\n---\n\n## TL;DR\n\n递归是一种编程技术，其中一个函数调用自身来解决问题。在 JavaScript 中，递归用于解决可以分解为更小、相似的子问题的问题。基本情况对于停止递归调用和防止无限循环至关重要。例如，可以使用递归计算一个数的阶乘：\n\n```js live\nfunction factorial(n) {\n  if (n === 0) {\n    return 1;\n  }\n  return n * factorial(n - 1);\n}\n\nconsole.log(factorial(4)); // Output: 24\n```\n\n***\n\n## 什么是递归以及它在 JavaScript 中如何使用？\n\n### 递归的定义\n\n递归是一种编程技术，其中一个函数调用自身来解决问题。这种方法对于可以分解为更小、相似的子问题的问题特别有用。递归函数的主要组成部分是：\n\n* **基本情况**：函数停止调用自身的条件，防止无限循环。\n* **递归情况**：函数调用自身并使用修改后的参数的部分，向基本情况移动。\n\n### 示例：计算阶乘\n\n一个数 `n` 的阶乘（表示为 `n!`）是所有小于或等于 `n` 的正整数的乘积。它可以递归定义为：\n\n* `0! = 1`（基本情况）\n* `n! = n * (n - 1)!` 对于 `n > 0`（递归情况）\n\n以下是如何在 JavaScript 中实现此功能：\n\n```js live\nfunction factorial(n) {\n  if (n === 0) {\n    // base case\n    return 1;\n  }\n  return n * factorial(n - 1); // recursive case\n}\n\nconsole.log(factorial(4)); // Output: 24\n```\n\n### 示例：斐波那契数列\n\n斐波那契数列是递归的另一个经典例子。该数列中的每个数字都是前两个数字的和，通常从 0 和 1 开始。该数列可以递归定义为：\n\n* `fib(0) = 0`（基本情况）\n* `fib(1) = 1`（基本情况）\n* `fib(n) = fib(n - 1) + fib(n - 2)` 对于 `n > 1`（递归情况）\n\n以下是如何在 JavaScript 中实现此功能：\n\n```js live\nfunction fibonacci(n) {\n  if (n === 0) {\n    // base case\n    return 0;\n  }\n  if (n === 1) {\n    // base case\n    return 1;\n  }\n  return fibonacci(n - 1) + fibonacci(n - 2); // recursive case\n}\n\nconsole.log(fibonacci(6)); // Output: 8\n```\n\n### 尾递归\n\n尾递归是一种特殊形式的递归，其中递归调用是函数中的最后一个操作。这可以被一些 JavaScript 引擎优化，以提高性能并防止堆栈溢出。这是一个尾递归阶乘函数的示例：\n\n```js live\nfunction factorial(n, acc = 1) {\n  if (n === 0) {\n    return acc;\n  }\n  return factorial(n - 1, n * acc);\n}\n\nconsole.log(factorial(4)); // Output: 24\n```\n\n### 递归的用例\n\n* **树遍历**：递归常用于遍历树结构，例如 DOM 或二叉树。\n* **分治算法**：诸如快速排序和归并排序之类的算法使用递归将问题分解为更小的子问题。\n* **动态规划**：诸如背包问题和某些图算法之类的问题可以使用递归来解决。\n\n## 延伸阅读\n\n* [MDN Web Docs: 递归](https://developer.mozilla.org/zh-CN/docs/Glossary/Recursion)\n* [JavaScript.info: 递归和栈](https://zh.javascript.info/recursion)\n* [Eloquent JavaScript: 递归](https://eloquentjavascript.net/03_functions.html#h_recursion)\n"
  },
  {
    "path": "questions/what-is-the-command-pattern-and-how-is-it-used/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"773666df\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"aeec3705\",\n        \"2c945c94\",\n        \"2a7816d0\",\n        \"b0fbedf5\",\n        \"25841bc3\",\n        \"e6b0392c\",\n        \"eb32a928\",\n        \"4a4ea3d5\",\n        \"30fcf78\",\n        \"5205b570\",\n        \"6dd3b324\",\n        \"bf9b4501\",\n        \"1f4770e5\",\n        \"418dcc26\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"aeec3705\",\n        \"2c945c94\",\n        \"2a7816d0\",\n        \"b0fbedf5\",\n        \"25841bc3\",\n        \"e6b0392c\",\n        \"eb32a928\",\n        \"4a4ea3d5\",\n        \"30fcf78\",\n        \"5205b570\",\n        \"6dd3b324\",\n        \"bf9b4501\",\n        \"1f4770e5\",\n        \"418dcc26\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-command-pattern-and-how-is-it-used/en-US.mdx",
    "content": "---\ntitle: What is the Command pattern and how is it used?\n---\n\n## TL;DR\n\nThe Command pattern is a behavioral design pattern that turns a request into a stand-alone object containing all information about the request. This transformation allows for parameterization of methods with different requests, queuing of requests, and logging of the requests. It also supports undoable operations. In JavaScript, it can be implemented by creating command objects with `execute` and `undo` methods.\n\n```js live\nclass Command {\n  execute() {}\n  undo() {}\n}\n\nclass LightOnCommand extends Command {\n  constructor(light) {\n    super();\n    this.light = light;\n  }\n  execute() {\n    this.light.on();\n  }\n  undo() {\n    this.light.off();\n  }\n}\n\nclass Light {\n  on() {\n    console.log('Light is on');\n  }\n  off() {\n    console.log('Light is off');\n  }\n}\n\nconst light = new Light();\nconst lightOnCommand = new LightOnCommand(light);\nlightOnCommand.execute(); // Light is on\nlightOnCommand.undo(); // Light is off\n```\n\n---\n\n## What is the Command pattern and how is it used?\n\n### Definition\n\nThe Command pattern is a behavioral design pattern that encapsulates a request as an object, thereby allowing for the parameterization of clients with queues, requests, and operations. It also provides support for undoable operations.\n\n### Components\n\n1. **Command**: Declares an interface for executing an operation.\n2. **ConcreteCommand**: Implements the `execute` method by invoking the corresponding operation(s) on `Receiver`.\n3. **Receiver**: Knows how to perform the operations associated with carrying out a request.\n4. **Invoker**: Asks the command to carry out the request.\n5. **Client**: Creates a `ConcreteCommand` object and sets its receiver.\n\n### Implementation in JavaScript\n\n```js live\n// Step 1: Define the Command interface\n\nclass Command {\n  execute() {}\n  undo() {}\n}\n\n// Step 2: Create ConcreteCommand classes\n\nclass LightOnCommand extends Command {\n  constructor(light) {\n    super();\n    this.light = light;\n  }\n  execute() {\n    this.light.on();\n  }\n  undo() {\n    this.light.off();\n  }\n}\n\nclass LightOffCommand extends Command {\n  constructor(light) {\n    super();\n    this.light = light;\n  }\n  execute() {\n    this.light.off();\n  }\n  undo() {\n    this.light.on();\n  }\n}\n\n// Step 3: Define the Receiver\n\nclass Light {\n  on() {\n    console.log('Light is on');\n  }\n  off() {\n    console.log('Light is off');\n  }\n}\n\n// Step 4: Create the Invoker\n\nclass RemoteControl {\n  setCommand(command) {\n    this.command = command;\n  }\n  pressButton() {\n    this.command.execute();\n  }\n  pressUndo() {\n    this.command.undo();\n  }\n}\n\n// Step 5: Client code\n\nconst light = new Light();\nconst lightOnCommand = new LightOnCommand(light);\nconst lightOffCommand = new LightOffCommand(light);\n\nconst remote = new RemoteControl();\nremote.setCommand(lightOnCommand);\nremote.pressButton(); // Light is on\nremote.pressUndo(); // Light is off\n\nremote.setCommand(lightOffCommand);\nremote.pressButton(); // Light is off\nremote.pressUndo(); // Light is on\n```\n\n### Use cases\n\n- **Undo/Redo functionality**: The Command pattern is ideal for implementing undo and redo operations.\n- **Macro commands**: It can be used to implement a sequence of commands.\n- **Logging changes**: It helps in logging changes and auditing them later.\n- **GUI buttons and menu items**: It is useful for implementing actions triggered by GUI elements.\n\n## Further reading\n\n- [Refactoring Guru: Command Pattern](https://refactoring.guru/design-patterns/command)\n- [JavaScript Design Patterns: Command](https://www.dofactory.com/javascript/design-patterns/command)\n- [Patterns.dev: Command Pattern](https://www.patterns.dev/vanilla/command-pattern/)\n"
  },
  {
    "path": "questions/what-is-the-command-pattern-and-how-is-it-used/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-command-pattern-and-how-is-it-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Design Patterns\"\n}\n"
  },
  {
    "path": "questions/what-is-the-command-pattern-and-how-is-it-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是命令模式以及如何使用它？\n---\n\n## TL;DR\n\n命令模式是一种行为型设计模式，它将请求转化为一个独立的包含关于请求所有信息的对象。这种转换允许使用不同的请求对方法进行参数化、请求排队和请求日志记录。它还支持可撤销操作。在 JavaScript 中，可以通过创建具有 `execute` 和 `undo` 方法的命令对象来实现。\n\n```js live\nclass Command {\n  execute() {}\n  undo() {}\n}\n\nclass LightOnCommand extends Command {\n  constructor(light) {\n    super();\n    this.light = light;\n  }\n  execute() {\n    this.light.on();\n  }\n  undo() {\n    this.light.off();\n  }\n}\n\nclass Light {\n  on() {\n    console.log('Light is on');\n  }\n  off() {\n    console.log('Light is off');\n  }\n}\n\nconst light = new Light();\nconst lightOnCommand = new LightOnCommand(light);\nlightOnCommand.execute(); // Light is on\nlightOnCommand.undo(); // Light is off\n```\n\n***\n\n## 什么是命令模式以及如何使用它？\n\n### 定义\n\n命令模式是一种行为型设计模式，它将请求封装成一个对象，从而允许使用队列、请求和操作对客户端进行参数化。它还支持可撤销操作。\n\n### 组件\n\n1. **Command**：声明用于执行操作的接口。\n2. **ConcreteCommand**：通过在 `Receiver` 上调用相应的操作来实现 `execute` 方法。\n3. **Receiver**：知道如何执行与执行请求相关的操作。\n4. **Invoker**：要求命令执行请求。\n5. **Client**：创建一个 `ConcreteCommand` 对象并设置其接收者。\n\n### 在 JavaScript 中的实现\n\n```js live\n// Step 1: Define the Command interface\n\nclass Command {\n  execute() {}\n  undo() {}\n}\n\n// Step 2: Create ConcreteCommand classes\n\nclass LightOnCommand extends Command {\n  constructor(light) {\n    super();\n    this.light = light;\n  }\n  execute() {\n    this.light.on();\n  }\n  undo() {\n    this.light.off();\n  }\n}\n\nclass LightOffCommand extends Command {\n  constructor(light) {\n    super();\n    this.light = light;\n  }\n  execute() {\n    this.light.off();\n  }\n  undo() {\n    this.light.on();\n  }\n}\n\n// Step 3: Define the Receiver\n\nclass Light {\n  on() {\n    console.log('Light is on');\n  }\n  off() {\n    console.log('Light is off');\n  }\n}\n\n// Step 4: Create the Invoker\n\nclass RemoteControl {\n  setCommand(command) {\n    this.command = command;\n  }\n  pressButton() {\n    this.command.execute();\n  }\n  pressUndo() {\n    this.command.undo();\n  }\n}\n\n// Step 5: Client code\n\nconst light = new Light();\nconst lightOnCommand = new LightOnCommand(light);\nconst lightOffCommand = new LightOffCommand(light);\n\nconst remote = new RemoteControl();\nremote.setCommand(lightOnCommand);\nremote.pressButton(); // Light is on\nremote.pressUndo(); // Light is off\n\nremote.setCommand(lightOffCommand);\nremote.pressButton(); // Light is off\nremote.pressUndo(); // Light is on\n```\n\n### 用例\n\n* **撤销/重做功能**：命令模式是实现撤销和重做操作的理想选择。\n* **宏命令**：它可用于实现一系列命令。\n* **记录更改**：它有助于记录更改并稍后进行审计。\n* **GUI 按钮和菜单项**：它对于实现由 GUI 元素触发的操作很有用。\n\n## 延伸阅读\n\n* [Refactoring Guru: Command Pattern](https://refactoring.guru/design-patterns/command)\n* [JavaScript Design Patterns: Command](https://www.dofactory.com/javascript/design-patterns/command)\n* [Patterns.dev: Command Pattern](https://www.patterns.dev/vanilla/command-pattern/)\n"
  },
  {
    "path": "questions/what-is-the-decorator-pattern-and-how-is-it-used/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"306f38eb\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"39f41f1e\",\n        \"775fc2cc\",\n        \"a43ec72e\",\n        \"2a7816d0\",\n        \"eb40dd52\",\n        \"25841bc3\",\n        \"24adf477\",\n        \"6dd3b324\",\n        \"adff366c\",\n        \"30fcf78\",\n        \"5448b0df\",\n        \"d8ee2797\",\n        \"8984aa69\",\n        \"3bc60c64\",\n        \"697c9777\",\n        \"4d76b730\",\n        \"852195c\",\n        \"af89cf01\",\n        \"82c3077\",\n        \"9f3eeda4\",\n        \"1f4770e5\",\n        \"84539399\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"39f41f1e\",\n        \"775fc2cc\",\n        \"a43ec72e\",\n        \"2a7816d0\",\n        \"eb40dd52\",\n        \"25841bc3\",\n        \"24adf477\",\n        \"6dd3b324\",\n        \"adff366c\",\n        \"30fcf78\",\n        \"5448b0df\",\n        \"d8ee2797\",\n        \"8984aa69\",\n        \"3bc60c64\",\n        \"697c9777\",\n        \"4d76b730\",\n        \"852195c\",\n        \"af89cf01\",\n        \"82c3077\",\n        \"9f3eeda4\",\n        \"1f4770e5\",\n        \"84539399\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-decorator-pattern-and-how-is-it-used/en-US.mdx",
    "content": "---\ntitle: What is the Decorator pattern and how is it used?\n---\n\n## TL;DR\n\nThe Decorator pattern is a structural design pattern that allows behavior to be added to individual objects, dynamically, without affecting the behavior of other objects from the same class. It is used to extend the functionalities of objects by wrapping them with additional behavior. In JavaScript, this can be achieved using higher-order functions or classes.\n\nFor example, if you have a `Car` class and you want to add features like `GPS` or `Sunroof` without modifying the `Car` class itself, you can create decorators for these features.\n\n```js live\nclass Car {\n  drive() {\n    return 'Driving';\n  }\n}\n\nclass CarDecorator {\n  constructor(car) {\n    this.car = car;\n  }\n\n  drive() {\n    return this.car.drive();\n  }\n}\n\nclass GPSDecorator extends CarDecorator {\n  drive() {\n    return `${super.drive()} with GPS`;\n  }\n}\n\nconst myCar = new Car();\nconst myCarWithGPS = new GPSDecorator(myCar);\nconsole.log(myCarWithGPS.drive()); // \"Driving with GPS\"\n```\n\n---\n\n## What is the Decorator pattern and how is it used?\n\n### Definition\n\nThe Decorator pattern is a structural design pattern that allows you to dynamically add behavior and responsibilities to objects without modifying their code. This pattern creates a set of decorator classes that are used to wrap concrete components.\n\n### Use cases\n\n- **Adding functionalities**: When you need to add functionalities to objects without altering their structure.\n- **Flexible and reusable code**: When you want to create flexible and reusable code by composing behaviors.\n- **Single Responsibility Principle**: When you want to adhere to the Single Responsibility Principle by dividing functionalities into different classes.\n\n### Implementation in JavaScript\n\n#### Using classes\n\nIn JavaScript, the Decorator pattern can be implemented using classes. Here is an example:\n\n```js live\nclass Car {\n  drive() {\n    return 'Driving';\n  }\n}\n\nclass CarDecorator {\n  constructor(car) {\n    this.car = car;\n  }\n\n  drive() {\n    return this.car.drive();\n  }\n}\n\nclass GPSDecorator extends CarDecorator {\n  drive() {\n    return `${super.drive()} with GPS`;\n  }\n}\n\nclass SunroofDecorator extends CarDecorator {\n  drive() {\n    return `${super.drive()} with Sunroof`;\n  }\n}\n\nconst myCar = new Car();\nconst myCarWithGPS = new GPSDecorator(myCar);\nconst myCarWithGPSAndSunroof = new SunroofDecorator(myCarWithGPS);\n\nconsole.log(myCarWithGPSAndSunroof.drive()); // \"Driving with GPS with Sunroof\"\n```\n\n#### Using higher-order functions\n\nAnother way to implement the Decorator pattern in JavaScript is by using higher-order functions:\n\n```js live\nfunction car() {\n  return {\n    drive: () => 'Driving',\n  };\n}\n\nfunction gpsDecorator(car) {\n  return {\n    drive: () => `${car.drive()} with GPS`,\n  };\n}\n\nfunction sunroofDecorator(car) {\n  return {\n    drive: () => `${car.drive()} with Sunroof`,\n  };\n}\n\nlet myCar = car();\nmyCar = gpsDecorator(myCar);\nmyCar = sunroofDecorator(myCar);\n\nconsole.log(myCar.drive()); // \"Driving with GPS with Sunroof\"\n```\n\n### Advantages\n\n- **Open/Closed Principle**: Classes are open for extension but closed for modification.\n- **Flexible**: Allows for the dynamic composition of behaviors.\n- **Reusable**: Decorators can be reused across different objects.\n\n### Disadvantages\n\n- **Complexity**: Can lead to a large number of small classes or functions.\n- **Debugging**: Can be harder to debug due to the added layers of abstraction.\n\n## Further reading\n\n- [Decorator Pattern on Wikipedia](https://en.wikipedia.org/wiki/Decorator_pattern)\n- [MDN Web Docs: Decorators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#class_decorators)\n- [Refactoring Guru: Decorator Pattern](https://refactoring.guru/design-patterns/decorator)\n"
  },
  {
    "path": "questions/what-is-the-decorator-pattern-and-how-is-it-used/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-decorator-pattern-and-how-is-it-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Design Patterns\"\n}\n"
  },
  {
    "path": "questions/what-is-the-decorator-pattern-and-how-is-it-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是装饰器模式以及如何使用它？\n---\n\n## TL;DR\n\n装饰器模式是一种结构型设计模式，它允许将行为动态地添加到单个对象中，而不会影响来自同一类的其他对象的行为。它用于通过用附加行为包装对象来扩展对象的功能。在 JavaScript 中，这可以使用高阶函数或类来实现。\n\n例如，如果您有一个 `Car` 类，并且您想添加 `GPS` 或 `Sunroof` 等功能，而无需修改 `Car` 类本身，您可以为这些功能创建装饰器。\n\n```js live\nclass Car {\n  drive() {\n    return 'Driving';\n  }\n}\n\nclass CarDecorator {\n  constructor(car) {\n    this.car = car;\n  }\n\n  drive() {\n    return this.car.drive();\n  }\n}\n\nclass GPSDecorator extends CarDecorator {\n  drive() {\n    return `${super.drive()} with GPS`;\n  }\n}\n\nconst myCar = new Car();\nconst myCarWithGPS = new GPSDecorator(myCar);\nconsole.log(myCarWithGPS.drive()); // \"Driving with GPS\"\n```\n\n***\n\n## 什么是装饰器模式以及如何使用它？\n\n### 定义\n\n装饰器模式是一种结构型设计模式，它允许您动态地向对象添加行为和责任，而无需修改其代码。此模式创建一组用于包装具体组件的装饰器类。\n\n### 用例\n\n* **添加功能**: 当您需要向对象添加功能而不更改其结构时。\n* **灵活且可重用的代码**: 当您希望通过组合行为来创建灵活且可重用的代码时。\n* **单一责任原则**: 当您希望通过将功能划分为不同的类来遵守单一责任原则时。\n\n### 在 JavaScript 中的实现\n\n#### 使用类\n\n在 JavaScript 中，可以使用类来实现装饰器模式。 这是一个例子：\n\n```js live\nclass Car {\n  drive() {\n    return 'Driving';\n  }\n}\n\nclass CarDecorator {\n  constructor(car) {\n    this.car = car;\n  }\n\n  drive() {\n    return this.car.drive();\n  }\n}\n\nclass GPSDecorator extends CarDecorator {\n  drive() {\n    return `${super.drive()} with GPS`;\n  }\n}\n\nclass SunroofDecorator extends CarDecorator {\n  drive() {\n    return `${super.drive()} with Sunroof`;\n  }\n}\n\nconst myCar = new Car();\nconst myCarWithGPS = new GPSDecorator(myCar);\nconst myCarWithGPSAndSunroof = new SunroofDecorator(myCarWithGPS);\n\nconsole.log(myCarWithGPSAndSunroof.drive()); // \"Driving with GPS with Sunroof\"\n```\n\n#### 使用高阶函数\n\n在 JavaScript 中实现装饰器模式的另一种方法是使用高阶函数：\n\n```js live\nfunction car() {\n  return {\n    drive: () => 'Driving',\n  };\n}\n\nfunction gpsDecorator(car) {\n  return {\n    drive: () => `${car.drive()} with GPS`,\n  };\n}\n\nfunction sunroofDecorator(car) {\n  return {\n    drive: () => `${car.drive()} with Sunroof`,\n  };\n}\n\nlet myCar = car();\nmyCar = gpsDecorator(myCar);\nmyCar = sunroofDecorator(myCar);\n\nconsole.log(myCar.drive()); // \"Driving with GPS with Sunroof\"\n```\n\n### 优点\n\n* **开闭原则**：类对扩展开放，对修改关闭。\n* **灵活**：允许动态组合行为。\n* **可重用**：装饰器可以在不同的对象之间重用。\n\n### 缺点\n\n* **复杂性**：可能导致大量的小类或函数。\n* **调试**：由于增加了抽象层，可能更难调试。\n\n## 延伸阅读\n\n* [维基百科上的装饰器模式](https://en.wikipedia.org/wiki/Decorator_pattern)\n* [MDN Web Docs：装饰器](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#class_decorators)\n* [Refactoring Guru：装饰器模式](https://refactoring.guru/design-patterns/decorator)\n"
  },
  {
    "path": "questions/what-is-the-definition-of-a-higher-order-function/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"538c201d\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"e2f1480c\",\n        \"252cf2d4\",\n        \"91b30ab8\",\n        \"3d9ba8e\",\n        \"9285ca78\",\n        \"dc4af68b\",\n        \"2a7816d0\",\n        \"e5905283\",\n        \"1c8275d1\",\n        \"d5c9d2f\",\n        \"1fea7ba6\",\n        \"2d5f215d\",\n        \"a842f05d\",\n        \"349ff728\",\n        \"6699d554\",\n        \"e0446ef0\",\n        \"779d3f45\",\n        \"d2d23896\",\n        \"7698af58\",\n        \"d23713ca\",\n        \"f6aaa6a2\",\n        \"5f7469d0\",\n        \"527eef15\",\n        \"1604dd98\",\n        \"17095e66\",\n        \"6eab352a\",\n        \"1f4770e5\",\n        \"fa5c2d6a\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"e2f1480c\",\n        \"252cf2d4\",\n        \"91b30ab8\",\n        \"3d9ba8e\",\n        \"9285ca78\",\n        \"dc4af68b\",\n        \"2a7816d0\",\n        \"e5905283\",\n        \"1c8275d1\",\n        \"d5c9d2f\",\n        \"1fea7ba6\",\n        \"2d5f215d\",\n        \"a842f05d\",\n        \"349ff728\",\n        \"6699d554\",\n        \"e0446ef0\",\n        \"779d3f45\",\n        \"d2d23896\",\n        \"7698af58\",\n        \"d23713ca\",\n        \"f6aaa6a2\",\n        \"5f7469d0\",\n        \"527eef15\",\n        \"1604dd98\",\n        \"17095e66\",\n        \"6eab352a\",\n        \"1f4770e5\",\n        \"fa5c2d6a\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-definition-of-a-higher-order-function/en-US.mdx",
    "content": "---\ntitle: What is the definition of a higher-order function in JavaScript?\n---\n\n## TL;DR\n\nA higher-order function is any function that takes one or more functions as arguments, which it uses to operate on some data, and/or returns a function as a result.\n\nHigher-order functions are meant to abstract some operation that is performed repeatedly. The classic example of this is `Array.prototype.map()`, which takes an array and a function as arguments. `Array.prototype.map()` then uses this function to transform each item in the array, returning a new array with the transformed data. Other popular examples in JavaScript are `Array.prototype.forEach()`, `Array.prototype.filter()`, and `Array.prototype.reduce()`. A higher-order function doesn't just need to be manipulating arrays as there are many use cases for returning a function from another function. `Function.prototype.bind()` is an example that returns another function.\n\nImagine a scenario where we have an array of names that we need to transform to uppercase. The imperative way will be as such:\n\n```js live\nconst names = ['irish', 'daisy', 'anna'];\n\nfunction transformNamesToUppercase(names) {\n  const results = [];\n  for (let i = 0; i < names.length; i++) {\n    results.push(names[i].toUpperCase());\n  }\n  return results;\n}\n\nconsole.log(transformNamesToUppercase(names)); // ['IRISH', 'DAISY', 'ANNA']\n```\n\nUsing `Array.prototype.map(transformerFn)` makes the code shorter and more declarative.\n\n```js live\nconst names = ['irish', 'daisy', 'anna'];\n\nfunction transformNamesToUppercase(names) {\n  return names.map((name) => name.toUpperCase());\n}\n\nconsole.log(transformNamesToUppercase(names)); // ['IRISH', 'DAISY', 'ANNA']\n```\n\n---\n\n## Higher order functions\n\nA higher-order function is a function that takes another function as an argument or returns a function as its result.\n\n### Functions as arguments\n\nA higher-order function can take another function as an argument and execute it.\n\n```js live\nfunction greet(name) {\n  return `Hello, ${name}!`;\n}\n\nfunction greetName(greeter, name) {\n  console.log(greeter(name));\n}\n\ngreetName(greet, 'Alice'); // Output: Hello, Alice!\n```\n\nIn this example, the `greetName` function is higher-order function because it takes another function (`greet`) as an argument and uses it to generate a greeting for the given name.\n\n### Functions as return values\n\nA higher-order function can return another function.\n\n```js live\nfunction multiplier(factor) {\n  return function (num) {\n    return num * factor;\n  };\n}\n\nconst double = multiplier(2);\nconst triple = multiplier(3);\n\nconsole.log(double(5)); // Output: 10\nconsole.log(triple(5)); // Output: 15\n```\n\nIn this example, the `multiplier` function returns a new function that multiplies any number by the specified factor. The returned function is a closure that remembers the `factor` value from the outer function. The `multiplier` function is a higher-order function because it returns another function.\n\n### Practical examples\n\n1. **Logging decorator**: A higher-order function that adds logging functionality to another function:\n\n```js live\nfunction withLogging(fn) {\n  return function (...args) {\n    console.log(`Calling ${fn.name} with arguments`, args);\n    return fn.apply(this, args);\n  };\n}\n\nfunction add(a, b) {\n  return a + b;\n}\n\nconst loggedAdd = withLogging(add);\nconsole.log(loggedAdd(2, 3));\n// Output:\n// Calling add with arguments [2, 3]\n// 5\n```\n\nThe `withLogging` function is a higher-order function that takes a function fn as an argument and returns a new function that logs the function call before executing the original function\n\n2. **Memoization**: A higher-order function that caches the results of a function to avoid redundant computations:\n\n```js live\nfunction memoize(fn) {\n  const cache = new Map();\n  return function (...args) {\n    const key = JSON.stringify(args);\n    if (cache.has(key)) {\n      return cache.get(key);\n    }\n    const result = fn.apply(this, args);\n    cache.set(key, result);\n    return result;\n  };\n}\n\nfunction fibonacci(n) {\n  if (n <= 1) return n;\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nconst memoizedFibonacci = memoize(fibonacci);\nconsole.log(memoizedFibonacci(10)); // Output: 55\n```\n\nThe `memoize` function is a higher-order function that takes a function `fn` as an argument and returns a new function that caches the results of the original function based on its arguments.\n\n1. **Lodash**: Lodash is a utility library that provides a wide range of functions for working with arrays, objects, strings, and more, most of which are higher-order functions.\n\n```js\nimport _ from 'lodash';\n\nconst numbers = [1, 2, 3, 4, 5];\n\n// Filter array\nconst evenNumbers = _.filter(numbers, (n) => n % 2 === 0); // [2, 4]\n\n// Map array\nconst doubledNumbers = _.map(numbers, (n) => n * 2); // [2, 4, 6, 8, 10]\n\n// Find the maximum value\nconst maxValue = _.max(numbers); // 5\n\n// Sum all values\nconst sum = _.sum(numbers); // 15\n```\n\n## Further reading\n\n- [Higher-Order Functions](https://eloquentjavascript.net/05_higher_order.html)\n- [Understanding Higher-Order Functions in JavaScript](https://blog.bitsrc.io/understanding-higher-order-functions-in-javascript-75461803bad)\n- [Higher Order Functions: How to Use Filter, Map and Reduce for More Maintainable Code](https://www.freecodecamp.org/news/higher-order-functions-in-javascript-d9101f9cf528/)\n"
  },
  {
    "path": "questions/what-is-the-definition-of-a-higher-order-function/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-definition-of-a-higher-order-function\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 190,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-is-the-definition-of-a-higher-order-function/pt-BR.mdx",
    "content": "---\ntitle: Qual é a definição de uma função de ordem superior?\n---\n\nUma função de ordem superior é qualquer função que recebe uma ou mais funções como argumentos, que ela usa para operar em algum dado e/ou retorna uma função como resultado. As funções de ordem superior têm como objetivo abstrair alguma operação que é realizada repetidamente. O exemplo clássico disso é o map, que recebe como argumentos um array e uma função. O map então usa essa função para transformar cada item no array, retornando um novo array com os dados transformados. Outros exemplos populares em JavaScript são `forEach`, `filter` e `reduce`. Uma função de ordem superior não precisa apenas manipular arrays, pois há muitos casos de uso para retornar uma função de outra função. `Function.prototype.bind` é um exemplo desse tipo em JavaScript.\n\n## Map\n\nVamos supor que temos um array de nomes no qual precisamos transformar cada string em maiúsculas.\n\n```js\nconst names = ['irish', 'daisy', 'anna'];\n```\n\nA maneira imperativa seria assim:\n\n```js\nconst transformNamesToUppercase = function (names) {\n  const results = [];\n  for (let i = 0; i < names.length; i++) {\n    results.push(names[i].toUpperCase());\n  }\n  return results;\n};\ntransformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA']\n```\n\nUse `.map(transformerFn)` torna o código mais curto e mais declarativo.\n\n```js\nconst transformNamesToUppercase = function (names) {\n  return names.map((name) => name.toUpperCase());\n};\ntransformNamesToUppercase(names); // ['IRISH', 'DAISY', 'ANNA']\n```\n"
  },
  {
    "path": "questions/what-is-the-definition-of-a-higher-order-function/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中高阶函数的定义是什么？\n---\n\n## TL;DR\n\n高阶函数是指将一个或多个函数作为参数的函数，它使用这些函数对某些数据进行操作，和/或返回一个函数作为结果。\n\n高阶函数旨在抽象一些重复执行的操作。 典型的例子是 `Array.prototype.map()`，它接受一个数组和一个函数作为参数。 然后，`Array.prototype.map()` 使用此函数转换数组中的每个项目，返回一个包含转换后的数据的新数组。 JavaScript 中其他常见的例子是 `Array.prototype.forEach()`、`Array.prototype.filter()` 和 `Array.prototype.reduce()`。 高阶函数不仅仅需要操作数组，因为从另一个函数返回一个函数有很多用例。 `Function.prototype.bind()` 就是一个返回另一个函数的例子。\n\n想象一下，我们有一个需要转换为大写的名称数组。 命令式方法如下：\n\n```js live\nconst names = ['irish', 'daisy', 'anna'];\n\nfunction transformNamesToUppercase(names) {\n  const results = [];\n  for (let i = 0; i < names.length; i++) {\n    results.push(names[i].toUpperCase());\n  }\n  return results;\n}\n\nconsole.log(transformNamesToUppercase(names)); // ['IRISH', 'DAISY', 'ANNA']\n```\n\n使用 `Array.prototype.map(transformerFn)` 使代码更短、更具声明性。\n\n```js live\nconst names = ['irish', 'daisy', 'anna'];\n\nfunction transformNamesToUppercase(names) {\n  return names.map((name) => name.toUpperCase());\n}\n\nconsole.log(transformNamesToUppercase(names)); // ['IRISH', 'DAISY', 'ANNA']\n```\n\n***\n\n## 高阶函数\n\n高阶函数是一个将另一个函数作为参数或返回一个函数作为其结果的函数。\n\n### 函数作为参数\n\n高阶函数可以将另一个函数作为参数并执行它。\n\n```js live\nfunction greet(name) {\n  return `Hello, ${name}!`;\n}\n\nfunction greetName(greeter, name) {\n  console.log(greeter(name));\n}\n\ngreetName(greet, 'Alice'); // Output: Hello, Alice!\n```\n\n在这个例子中，`greetName`函数是高阶函数，因为它将另一个函数(`greet`)作为参数，并使用它为给定的名称生成问候语。\n\n### 函数作为返回值\n\n高阶函数可以返回另一个函数。\n\n```js live\nfunction multiplier(factor) {\n  return function (num) {\n    return num * factor;\n  };\n}\n\nconst double = multiplier(2);\nconst triple = multiplier(3);\n\nconsole.log(double(5)); // Output: 10\nconsole.log(triple(5)); // Output: 15\n```\n\n在此示例中，`multiplier` 函数返回一个新函数，该函数将任何数字乘以指定的因子。 返回的函数是一个闭包，它记住外部函数中的 `factor` 值。 `multiplier` 函数是一个高阶函数，因为它返回另一个函数。\n\n### 实际例子\n\n1. **日志装饰器**：一个高阶函数，它向另一个函数添加日志记录功能：\n\n```js live\nfunction withLogging(fn) {\n  return function (...args) {\n    console.log(`Calling ${fn.name} with arguments`, args);\n    return fn.apply(this, args);\n  };\n}\n\nfunction add(a, b) {\n  return a + b;\n}\n\nconst loggedAdd = withLogging(add);\nconsole.log(loggedAdd(2, 3));\n// Output:\n// Calling add with arguments [2, 3]\n// 5\n```\n\n`withLogging` 函数是一个高阶函数，它接受一个函数 fn 作为参数，并返回一个新函数，该函数在执行原始函数之前记录函数调用\n\n2. **记忆化**：一个高阶函数，它缓存函数的计算结果以避免冗余计算：\n\n```js live\nfunction memoize(fn) {\n  const cache = new Map();\n  return function (...args) {\n    const key = JSON.stringify(args);\n    if (cache.has(key)) {\n      return cache.get(key);\n    }\n    const result = fn.apply(this, args);\n    cache.set(key, result);\n    return result;\n  };\n}\n\nfunction fibonacci(n) {\n  if (n <= 1) return n;\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\nconst memoizedFibonacci = memoize(fibonacci);\nconsole.log(memoizedFibonacci(10)); // Output: 55\n```\n\n`memoize` 函数是一个高阶函数，它接受一个函数 `fn` 作为参数，并返回一个新函数，该函数根据原始函数的参数缓存其结果。\n\n1. **Lodash**：Lodash 是一个实用程序库，它提供了广泛的函数，用于处理数组、对象、字符串等，其中大多数是高阶函数。\n\n```js\nimport _ from 'lodash';\n\nconst numbers = [1, 2, 3, 4, 5];\n\n// Filter array\nconst evenNumbers = _.filter(numbers, (n) => n % 2 === 0); // [2, 4]\n\n// Map array\nconst doubledNumbers = _.map(numbers, (n) => n * 2); // [2, 4, 6, 8, 10]\n\n// Find the maximum value\nconst maxValue = _.max(numbers); // 5\n\n// Sum all values\nconst sum = _.sum(numbers); // 15\n```\n\n## 延伸阅读\n\n* [高阶函数](https://eloquentjavascript.net/05_higher_order.html)\n* [理解 JavaScript 中的高阶函数](https://blog.bitsrc.io/understanding-higher-order-functions-in-javascript-75461803bad)\n* [高阶函数：如何使用 Filter、Map 和 Reduce 来获得更易于维护的代码](https://www.freecodecamp.org/news/higher-order-functions-in-javascript-d9101f9cf528/)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"18c1cb80\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"fbb7b48d\",\n        \"3383d41f\",\n        \"2a7816d0\",\n        \"f5e5b7e3\",\n        \"989ab262\",\n        \"c249d17a\",\n        \"a89e0135\",\n        \"9f785c25\",\n        \"4c08665\",\n        \"dc494df1\",\n        \"6698593c\",\n        \"657a3b69\",\n        \"8fea578c\",\n        \"54d39bdf\",\n        \"4f31d776\",\n        \"170fb4bf\",\n        \"9d306db\",\n        \"4eb2474e\",\n        \"691e343b\",\n        \"968fb34d\",\n        \"add698fb\",\n        \"3d45e41\",\n        \"1f4770e5\",\n        \"36ed4d00\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"fbb7b48d\",\n        \"3383d41f\",\n        \"2a7816d0\",\n        \"f5e5b7e3\",\n        \"989ab262\",\n        \"c249d17a\",\n        \"a89e0135\",\n        \"9f785c25\",\n        \"4c08665\",\n        \"dc494df1\",\n        \"6698593c\",\n        \"657a3b69\",\n        \"8fea578c\",\n        \"54d39bdf\",\n        \"4f31d776\",\n        \"170fb4bf\",\n        \"9d306db\",\n        \"4eb2474e\",\n        \"691e343b\",\n        \"968fb34d\",\n        \"add698fb\",\n        \"3d45e41\",\n        \"1f4770e5\",\n        \"36ed4d00\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/en-US.mdx",
    "content": "---\ntitle: What is the difference between a `Map` object and a plain object in JavaScript?\n---\n\n## TL;DR\n\nBoth `Map` objects and plain objects in JavaScript can store key-value pairs, but they have several key differences:\n\n| Feature | `Map` | Plain object |\n| --- | --- | --- |\n| Key type | Any data type | String (or Symbol) |\n| Key order | Maintained | Not guaranteed |\n| Size property | Yes (`size`) | None |\n| Iteration | `forEach`, `keys()`, `values()`, `entries()` | `for...in`, `Object.keys()`, etc. |\n| Inheritance | No | Yes |\n| Performance | Generally better for larger datasets and frequent additions/deletions | Faster for small datasets and simple operations |\n| Serializable | No | Yes |\n\n---\n\n## `Map` vs plain JavaScript objects\n\nIn JavaScript, `Map` objects and a plain object (also known as a \"POJO\" or \"plain old JavaScript object\") are both used to store key-value pairs, but they have different characteristics, use cases, and behaviors.\n\n### Plain JavaScript objects (POJO)\n\nA plain object is a basic JavaScript object created using the `{}` syntax. It is a collection of key-value pairs, where each key is a string (or a symbol, in modern JavaScript) and each value can be any type of value, including strings, numbers, booleans, arrays, objects, and more.\n\n```js live\nconst person = { name: 'John', age: 30, occupation: 'Developer' };\nconsole.log(person);\n```\n\n### `Map` objects\n\nA `Map` object, introduced in ECMAScript 2015 (ES6), is a more advanced data structure that allows you to store key-value pairs with additional features. A `Map` is an iterable, which means you can use it with `for...of` loops, and it provides methods for common operations like `get`, `set`, `has`, and `delete`.\n\n```js live\nconst person = new Map([\n  ['name', 'John'],\n  ['age', 30],\n  ['occupation', 'Developer'],\n]);\nconsole.log(person);\n```\n\n## Key differences\n\nHere are the main differences between a `Map` object and a plain object:\n\n1. **Key types**: In a plain object, keys are always strings (or symbols). In a `Map`, keys can be any type of value, including objects, arrays, and even other `Map`s.\n2. **Key ordering**: In a plain object, the order of keys is not guaranteed. In a `Map`, the order of keys is preserved, and you can iterate over them in the order they were inserted.\n3. **Iteration**: A `Map` is iterable, which means you can use `for...of` loops to iterate over its key-value pairs. A plain object is not iterable by default, but you can use `Object.keys()` or `Object.entries()` to iterate over its properties.\n4. **Performance**: `Map` objects are generally faster and more efficient than plain objects, especially when dealing with large datasets.\n5. **Methods**: A `Map` object provides additional methods, such as `get`, `set`, `has`, and `delete`, which make it easier to work with key-value pairs.\n6. **Serialization**: When serializing a `Map` object to JSON, it will be converted to an object but the existing `Map` properties might be lost in the conversion. A plain object, on the other hand, is serialized to a JSON object with the same structure.\n\n## When to use which\n\nUse a plain object (POJO) when:\n\n- You need a simple, lightweight object with string keys.\n- You're working with a small dataset.\n- You need to serialize the object to JSON (e.g. to send over the network).\n\nUse a `Map` object when:\n\n- You need to store key-value pairs with non-string keys (e.g., objects, arrays).\n- You need to preserve the order of key-value pairs.\n- You need to iterate over the key-value pairs in a specific order.\n- You're working with a large dataset and need better performance.\n\nIn summary, while both plain objects and `Map` objects can be used to store key-value pairs, `Map` objects offer more advanced features, better performance, and additional methods, making them a better choice for more complex use cases.\n\n## Notes\n\n`Map` objects cannot be serialized to be sent in HTTP requests, but libraries like [superjson](https://github.com/blitz-js/superjson) allow them to be serialized and deserialized.\n\n## Further reading\n\n- [Map - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n- [Object - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 400,\n  \"difficulty\": \"easy\"\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中 `Map` 对象和普通对象有什么区别？\n---\n\n## TL;DR\n\nJavaScript 中的 `Map` 对象和普通对象都可以存储键值对，但它们有几个关键的区别：\n\n| 特性 | `Map` | 普通对象 |\n| --- | --- | --- |\n| 键类型 | 任何数据类型 | 字符串（或 Symbol） |\n| 键顺序 | 保持 | 不保证 |\n| 大小属性 | 是 (`size`) | 无 |\n| 迭代 | `forEach`、`keys()`、`values()`、`entries()` | `for...in`、`Object.keys()` 等 |\n| 继承 | 否 | 是 |\n| 性能 | 通常更适合大型数据集和频繁的添加/删除 | 适用于小型数据集和简单操作 |\n| 可序列化 | 否 | 是 |\n\n***\n\n## `Map` vs 普通 JavaScript 对象\n\n在 JavaScript 中，`Map` 对象和普通对象（也称为“POJO”或“普通旧 JavaScript 对象”）都用于存储键值对，但它们具有不同的特性、用例和行为。\n\n### 普通 JavaScript 对象 (POJO)\n\n普通对象是使用 `{}` 语法创建的基本 JavaScript 对象。它是一个键值对的集合，其中每个键都是一个字符串（或现代 JavaScript 中的符号），每个值可以是任何类型的值，包括字符串、数字、布尔值、数组、对象等。\n\n```js live\nconst person = { name: 'John', age: 30, occupation: 'Developer' };\nconsole.log(person);\n```\n\n### `Map` 对象\n\n在 ECMAScript 2015 (ES6) 中引入的 `Map` 对象是一种更高级的数据结构，它允许您存储具有附加功能的键值对。`Map` 是可迭代的，这意味着您可以在 `for...of` 循环中使用它，并且它提供了用于常见操作（如 `get`、`set`、`has` 和 `delete`）的方法。\n\n```js live\nconst person = new Map([\n  ['name', 'John'],\n  ['age', 30],\n  ['occupation', 'Developer'],\n]);\nconsole.log(person);\n```\n\n## 关键区别\n\n以下是 `Map` 对象和普通对象之间的主要区别：\n\n1. **键类型**：在普通对象中，键始终是字符串（或符号）。在 `Map` 中，键可以是任何类型的值，包括对象、数组，甚至其他 `Map`。\n2. **键顺序**：在普通对象中，键的顺序不保证。在 `Map` 中，键的顺序被保留，您可以按照它们插入的顺序进行迭代。\n3. **迭代**：`Map` 是可迭代的，这意味着您可以使用 `for...of` 循环来迭代其键值对。默认情况下，普通对象不可迭代，但您可以使用 `Object.keys()` 或 `Object.entries()` 来迭代其属性。\n4. **性能**：`Map` 对象通常比普通对象更快、更高效，尤其是在处理大型数据集时。\n5. **方法**：`Map` 对象提供了其他方法，例如 `get`、`set`、`has` 和 `delete`，这使得处理键值对更容易。\n6. **序列化**：将 `Map` 对象序列化为 JSON 时，它将被转换为一个对象，但现有的 `Map` 属性可能会在转换过程中丢失。另一方面，普通对象被序列化为具有相同结构的 JSON 对象。\n\n## 何时使用哪个\n\n当您需要时使用普通对象 (POJO)：\n\n* 您需要一个具有字符串键的简单、轻量级对象。\n* 您正在处理小型数据集。\n* 您需要将对象序列化为 JSON（例如，通过网络发送）。\n\n当您需要时使用 `Map` 对象：\n\n* 您需要使用非字符串键（例如对象、数组）存储键值对。\n* 您需要保留键值对的顺序。\n* 您需要按特定顺序迭代键值对。\n* 您正在处理大型数据集，需要更好的性能。\n\n总而言之，虽然普通对象和 `Map` 对象都可以用来存储键值对，但 `Map` 对象提供了更高级的功能、更好的性能和额外的方法，使其成为更复杂用例的更好选择。\n\n## 注意事项\n\n`Map` 对象无法被序列化以在 HTTP 请求中发送，但像 [superjson](https://github.com/blitz-js/superjson) 这样的库允许它们被序列化和反序列化。\n\n## 延伸阅读\n\n* [Map - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n* [Object - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-a-parameter-and-an-argument/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"e2609fb\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"297cddc8\",\n        \"2a7816d0\",\n        \"2e21371\",\n        \"7004ebec\",\n        \"9d4fabcb\",\n        \"e76b9a8\",\n        \"c47cc2d0\",\n        \"f65e2ec9\",\n        \"663d45fa\",\n        \"f0c40a6a\",\n        \"e76b9a8\",\n        \"19d3ff59\",\n        \"d5926284\",\n        \"67423e0a\",\n        \"a997c350\",\n        \"b05beef9\",\n        \"7c6bff94\",\n        \"1f4770e5\",\n        \"3706ac88\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"297cddc8\",\n        \"2a7816d0\",\n        \"2e21371\",\n        \"7004ebec\",\n        \"9d4fabcb\",\n        \"e76b9a8\",\n        \"c47cc2d0\",\n        \"f65e2ec9\",\n        \"663d45fa\",\n        \"f0c40a6a\",\n        \"e76b9a8\",\n        \"19d3ff59\",\n        \"d5926284\",\n        \"67423e0a\",\n        \"a997c350\",\n        \"b05beef9\",\n        \"7c6bff94\",\n        \"1f4770e5\",\n        \"3706ac88\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-a-parameter-and-an-argument/en-US.mdx",
    "content": "---\ntitle: What is the difference between a parameter and an argument?\n---\n\n## TL;DR\n\nA parameter is a variable in the declaration of a function, while an argument is the actual value passed to the function when it is called. For example, in the function `function add(a, b) { return a + b; }`, `a` and `b` are parameters. When you call `add(2, 3)`, `2` and `3` are arguments.\n\n---\n\n## Difference between a parameter and an argument\n\n### Parameters\n\nParameters are variables listed as part of a function's definition. They act as placeholders for the values that will be passed to the function when it is called.\n\nExample:\n\n```js\nfunction greet(name) {\n  console.log('Hello, ' + name);\n}\n```\n\nIn this example, `name` is a parameter.\n\n### Arguments\n\nArguments are the actual values that are passed to the function when it is invoked. These values are assigned to the corresponding parameters in the function definition.\n\nExample:\n\n```js live\nfunction greet(name) {\n  console.log('Hello, ' + name);\n}\ngreet('Alice'); // Output: \"Hello, Alice\"\n```\n\nIn this example, `\"Alice\"` is an argument.\n\n### Key differences\n\n- Parameters are part of the function's signature, while arguments are the actual values supplied to the function.\n- Parameters are used to define the function, whereas arguments are used to call the function.\n\n### Example combining both\n\n```js live\nfunction add(a, b) {\n  // a and b are parameters\n  return a + b;\n}\n\nconst result = add(2, 3); // 2 and 3 are arguments\nconsole.log(result); // Output: 5\n```\n\n## Further reading\n\n- [MDN Web Docs: Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)\n- [JavaScript.info: Function basics](https://javascript.info/function-basics)\n- [W3Schools: JavaScript Function Parameters](https://www.w3schools.com/js/js_function_parameters.asp)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-a-parameter-and-an-argument/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-difference-between-a-parameter-and-an-argument\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Functions\"\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-a-parameter-and-an-argument/zh-CN.mdx",
    "content": "---\ntitle: 参数和参数的区别是什么？\n---\n\n## TL;DR\n\n参数是函数声明中的变量，而参数是调用函数时传递给函数的实际值。例如，在函数 `function add(a, b) { return a + b; }` 中，`a` 和 `b` 是参数。当您调用 `add(2, 3)` 时，`2` 和 `3` 是参数。\n\n***\n\n## 参数和参数的区别\n\n### 参数\n\n参数是作为函数定义的一部分列出的变量。它们充当在调用函数时将传递给函数的值的占位符。\n\n示例：\n\n```js\nfunction greet(name) {\n  console.log('Hello, ' + name);\n}\n```\n\n在此示例中，`name` 是一个参数。\n\n### 参数\n\n参数是调用函数时传递给函数的实际值。这些值被分配给函数定义中相应的参数。\n\n示例：\n\n```js live\nfunction greet(name) {\n  console.log('Hello, ' + name);\n}\ngreet('Alice'); // Output: \"Hello, Alice\"\n```\n\n在此示例中，`\"Alice\"` 是一个参数。\n\n### 主要区别\n\n* 参数是函数签名的一部分，而参数是提供给函数的实际值。\n* 参数用于定义函数，而参数用于调用函数。\n\n### 结合两者的例子\n\n```js live\nfunction add(a, b) {\n  // a and b are parameters\n  return a + b;\n}\n\nconst result = add(2, 3); // 2 and 3 are arguments\nconsole.log(result); // Output: 5\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)\n* [JavaScript.info: Function basics](https://javascript.info/function-basics)\n* [W3Schools: JavaScript Function Parameters](https://www.w3schools.com/js/js_function_parameters.asp)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"fabb8486\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"92e96c24\",\n        \"d6b48599\",\n        \"2a7816d0\",\n        \"28b218c7\",\n        \"a4cd1620\",\n        \"3789e3d9\",\n        \"8208c153\",\n        \"a95d9bcb\",\n        \"ec404585\",\n        \"8f2c02f1\",\n        \"e22c0b95\",\n        \"c61f0bed\",\n        \"bf740616\",\n        \"b3ecb149\",\n        \"eea0fdee\",\n        \"adead66c\",\n        \"a90cc1eb\",\n        \"26f7b6ac\",\n        \"e1468f22\",\n        \"32e4700e\",\n        \"40808d83\",\n        \"6f62bec8\",\n        \"79360ef1\",\n        \"1dac807a\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"92e96c24\",\n        \"d6b48599\",\n        \"2a7816d0\",\n        \"28b218c7\",\n        \"a4cd1620\",\n        \"3789e3d9\",\n        \"8208c153\",\n        \"a95d9bcb\",\n        \"ec404585\",\n        \"8f2c02f1\",\n        \"e22c0b95\",\n        \"c61f0bed\",\n        \"bf740616\",\n        \"b3ecb149\",\n        \"eea0fdee\",\n        \"adead66c\",\n        \"a90cc1eb\",\n        \"26f7b6ac\",\n        \"e1468f22\",\n        \"32e4700e\",\n        \"40808d83\",\n        \"6f62bec8\",\n        \"79360ef1\",\n        \"1dac807a\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-double-equal-and-triple-equal/en-US.mdx",
    "content": "---\ntitle: What is the difference between `==` and `===` in JavaScript?\n---\n\n## TL;DR\n\n`==` is the abstract equality operator while `===` is the strict equality operator. The `==` operator will compare for equality after doing any necessary type conversions. The `===` operator will not do type conversion, so if two values are not the same type `===` will simply return `false`.\n\n| Operator | `==` | `===` |\n| --- | --- | --- |\n| Name | (Loose) Equality operator | Strict equality operator |\n| Type coercion | Yes | No |\n| Compares value and type | No | Yes |\n\n---\n\n### Equality operator (`==`)\n\nThe `==` operator checks for equality between two values but performs type coercion if the values are of different types. This means that JavaScript will attempt to convert the values to a common type before making the comparison.\n\n```js live\nconsole.log(42 == '42'); // true\nconsole.log(0 == false); // true\nconsole.log(null == undefined); // true\nconsole.log([] == false); // true\nconsole.log('' == false); // true\n```\n\nIn these examples, JavaScript converts the operands to the same type before making the comparison. For example, `42 == '42'` is true because the string `'42'` is converted to the number `42` before comparison.\n\nHowever, when using `==`, unintuitive results can happen:\n\n```js live\nconsole.log(1 == [1]); // true\nconsole.log(0 == ''); // true\nconsole.log(0 == '0'); // true\nconsole.log('' == '0'); // false\n```\n\nAs a general rule of thumb, never use the `==` operator, except for convenience when comparing against `null` or `undefined`, where `a == null` will return `true` if `a` is `null` or `undefined`.\n\n```js live\nvar a = null;\nconsole.log(a == null); // true\nconsole.log(a == undefined); // true\n```\n\n### Strict equality operator (`===`)\n\nThe `===` operator, also known as the strict equality operator, checks for equality between two values without performing type coercion. This means that both the value and the type must be the same for the comparison to return true.\n\n```js live\nconsole.log(42 === '42'); // false\nconsole.log(0 === false); // false\nconsole.log(null === undefined); // false\nconsole.log([] === false); // false\nconsole.log('' === false); // false\n```\n\nFor these comparisons, no type conversion is performed, so the statement returns `false` if the types are different. For instance, `42 === '42'` is `false` because the types (number and string) are different.\n\n```js live\n// Comparison with type coercion (==)\nconsole.log(42 == '42'); // true\nconsole.log(0 == false); // true\nconsole.log(null == undefined); // true\n\n// Strict comparison without type coercion (===)\nconsole.log(42 === '42'); // false\nconsole.log(0 === false); // false\nconsole.log(null === undefined); // false\n```\n\n### Bonus: `Object.is()`\n\nThere's one final value-comparison operation within JavaScript, that is the [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) static method. The only difference between `Object.is()` and `===` is how they treat of signed zeros and `NaN` values. The `===` operator (and the `==` operator) treats the number values `-0` and `+0` as equal, but treats `NaN` as not equal to each other.\n\n## Conclusion\n\n- Use `==` when you want to compare values with type coercion (and understand the implications of it). In practice, the only reasonable use case for the equality operator is to check for both `null` and `undefined` in a single comparison for convenience.\n- Use `===` when you want to ensure both the value and the type are the same, which is the safer and more predictable choice in most cases.\n\n### Notes\n\n- Using `===` (strict equality) is generally recommended to avoid the pitfalls of type coercion, which can lead to unexpected behavior and bugs in your code. It makes the intent of your comparisons clearer and ensures that you are comparing both the value and the type.\n- ESLint's [`eqeqeq`](https://eslint.org/docs/latest/rules/eqeqeq) rule enforces the use of strict equality operators `===` and `!==` and even provides an option to always enforce strict equality except when comparing with the `null` literal.\n\n### Further reading\n\n- [Equality (==) | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality)\n- [Strict equality (===) | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-double-equal-and-triple-equal/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-difference-between-double-equal-and-triple-equal\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 30,\n  \"difficulty\": \"easy\"\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-double-equal-and-triple-equal/pt-BR.mdx",
    "content": "---\ntitle: Qual é a diferença entre `==` e `===`?\n---\n\n`==` é o operador de igualdade abstrato enquanto `===` é o operador de igualdade rigoroso. O operador `==` será comparado para a igualdade após fazer quaisquer conversões de tipo necessárias. O operador `===` não fará conversão de tipo, então se dois valores não forem do mesmo tipo `===` simplesmente retornará `false`. Ao usar `==`, coisas engraçadas podem acontecer, tais como:\n\n```js\n1 == '1'; // true\n1 == [1]; // true\n1 == true; // true\n0 == ''; // true\n0 == '0'; // true\n0 == false; // true\n```\n\nComo regra geral, nunca use o operador `==`, exceto por conveniência ao comparar com `null` ou `undefined`, onde `a == null` retornará `true` se a for `null` ou undefined.\n\n```js\nvar a = null;\nconsole.log(a == null); // true\nconsole.log(a == undefined); // true\n```\n"
  },
  {
    "path": "questions/what-is-the-difference-between-double-equal-and-triple-equal/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中 `==` 和 `===` 的区别是什么？\n---\n\n## TL;DR\n\n`==` 是抽象相等运算符，而 `===` 是严格相等运算符。`==` 运算符会在进行任何必要的类型转换后比较是否相等。`===` 运算符不会进行类型转换，因此如果两个值不是同一类型，`===` 将直接返回 `false`。\n\n| 运算符 | `==` | `===` |\n| --- | --- | --- |\n| 名称 | （宽松）相等运算符 | 严格相等运算符 |\n| 类型转换 | 是 | 否 |\n| 比较值和类型 | 否 | 是 |\n\n***\n\n### 相等运算符 (`==`)\n\n`==` 运算符检查两个值是否相等，但如果这些值的类型不同，则会执行类型转换。这意味着 JavaScript 将尝试在进行比较之前将这些值转换为通用类型。\n\n```js live\nconsole.log(42 == '42'); // true\nconsole.log(0 == false); // true\nconsole.log(null == undefined); // true\nconsole.log([] == false); // true\nconsole.log('' == false); // true\n```\n\n在这些示例中，JavaScript 在进行比较之前将操作数转换为相同的类型。例如，`42 == '42'` 为 true，因为字符串 `'42'` 在比较之前被转换为数字 `42`。\n\n但是，当使用 `==` 时，可能会发生不直观的结果：\n\n```js live\nconsole.log(1 == [1]); // true\nconsole.log(0 == ''); // true\nconsole.log(0 == '0'); // true\nconsole.log('' == '0'); // false\n```\n\n作为一般经验法则，永远不要使用 `==` 运算符，除非为了方便与 `null` 或 `undefined` 进行比较，其中 `a == null` 将在 `a` 为 `null` 或 `undefined` 时返回 `true`。\n\n```js live\nvar a = null;\nconsole.log(a == null); // true\nconsole.log(a == undefined); // true\n```\n\n### 严格相等运算符 (`===`)\n\n`===` 运算符，也称为严格相等运算符，检查两个值是否相等，而不执行类型转换。这意味着，只有当值和类型都相同时，比较才会返回 true。\n\n```js live\nconsole.log(42 === '42'); // false\nconsole.log(0 === false); // false\nconsole.log(null === undefined); // false\nconsole.log([] === false); // false\nconsole.log('' === false); // false\n```\n\n对于这些比较，不执行类型转换，因此如果类型不同，该语句将返回 `false`。例如，`42 === '42'` 为 `false`，因为类型（数字和字符串）不同。\n\n```js live\n// 带有类型转换的比较 (==)\nconsole.log(42 == '42'); // true\nconsole.log(0 == false); // true\nconsole.log(null == undefined); // true\n\n// 不带类型转换的严格比较 (===)\nconsole.log(42 === '42'); // false\nconsole.log(0 === false); // false\nconsole.log(null === undefined); // false\n```\n\n### 额外内容：`Object.is()`\n\nJavaScript 中最后一个值比较操作是 [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) 静态方法。`Object.is()` 和 `===` 之间唯一的区别在于它们如何处理带符号的零和 `NaN` 值。`===` 运算符（和 `==` 运算符）将数字值 `-0` 和 `+0` 视为相等，但将 `NaN` 视为彼此不相等。\n\n## 结论\n\n* 当您希望通过类型转换比较值（并了解其含义）时，请使用`==`。 实际上，相等运算符的唯一合理用例是在单个比较中同时检查`null`和`undefined`以方便使用。\n* 当您希望确保值和类型都相同时，请使用`===`，这在大多数情况下是更安全、更可预测的选择。\n\n### 笔记\n\n* 建议使用 `===`（严格相等）以避免类型强制转换的缺陷，这可能导致代码中出现意外行为和错误。它使您的比较意图更清晰，并确保您同时比较值和类型。\n* ESLint 的 [`eqeqeq`](https://eslint.org/docs/latest/rules/eqeqeq) 规则强制使用严格相等运算符 `===` 和 `!==`，甚至提供了一个选项，始终强制使用严格相等，除非与 `null` 字面量进行比较。\n\n### 延伸阅读\n\n* [Equality (==) | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality)\n* [Strict equality (===) | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"8e3a1486\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"3a1cd423\",\n        \"2a7816d0\",\n        \"95bc1126\",\n        \"e8f9c722\",\n        \"d76b64b6\",\n        \"e9ed9cff\",\n        \"a3b47899\",\n        \"911913c9\",\n        \"f083b215\",\n        \"67423e0a\",\n        \"9f15ca73\",\n        \"6dd3b324\",\n        \"82b755f9\",\n        \"1f4770e5\",\n        \"84b5d54e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"3a1cd423\",\n        \"2a7816d0\",\n        \"95bc1126\",\n        \"e8f9c722\",\n        \"d76b64b6\",\n        \"e9ed9cff\",\n        \"a3b47899\",\n        \"911913c9\",\n        \"f083b215\",\n        \"67423e0a\",\n        \"9f15ca73\",\n        \"6dd3b324\",\n        \"82b755f9\",\n        \"1f4770e5\",\n        \"84b5d54e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation/en-US.mdx",
    "content": "---\ntitle: What is the difference between `event.preventDefault()` and `event.stopPropagation()`?\n---\n\n## TL;DR\n\n`event.preventDefault()` is used to prevent the default action that belongs to the event, such as preventing a form from submitting. `event.stopPropagation()` is used to stop the event from bubbling up to parent elements, preventing any parent event handlers from being executed.\n\n---\n\n## What is the difference between `event.preventDefault()` and `event.stopPropagation()`?\n\n### `event.preventDefault()`\n\n`event.preventDefault()` is a method that cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be used to prevent a form from being submitted:\n\n```js\ndocument.querySelector('form').addEventListener('submit', function (event) {\n  event.preventDefault();\n  // Form submission is prevented\n});\n```\n\n### `event.stopPropagation()`\n\n`event.stopPropagation()` is a method that prevents the event from bubbling up the DOM tree, stopping any parent handlers from being notified of the event. This is useful when you want to handle an event at a specific level and do not want it to trigger handlers on parent elements:\n\n```js\ndocument.querySelector('.child').addEventListener('click', function (event) {\n  event.stopPropagation();\n  // Click event will not propagate to parent elements\n});\n```\n\n### Key differences\n\n- `event.preventDefault()` stops the default action associated with the event.\n- `event.stopPropagation()` stops the event from propagating (bubbling) up to parent elements.\n\n### Use cases\n\n- Use `event.preventDefault()` when you want to prevent the default behavior of an element, such as preventing a link from navigating or a form from submitting.\n- Use `event.stopPropagation()` when you want to prevent an event from reaching parent elements, which can be useful in complex UIs where multiple elements have event listeners.\n\n## Further reading\n\n- [MDN Web Docs: event.preventDefault()](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n- [MDN Web Docs: event.stopPropagation()](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)\n- [JavaScript Event Propagation](https://javascript.info/bubbling-and-capturing)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"web-api\", \"html\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"DOM Manipulation & Events\"\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-eventpreventdefault-and-eventstoppropagation/zh-CN.mdx",
    "content": "---\ntitle: event.preventDefault() 和 event.stopPropagation() 有什么区别？\n---\n\n## TL;DR\n\n<code>event.preventDefault()</code> 用于阻止属于该事件的默认操作，例如阻止表单提交。<code>event.stopPropagation()</code> 用于阻止事件冒泡到父元素，从而阻止任何父事件处理程序被执行。\n\n***\n\n## event.preventDefault() 和 event.stopPropagation() 有什么区别？\n\n### event.preventDefault()\n\n<code>event.preventDefault()</code> 是一种方法，如果事件是可取消的，则取消该事件，这意味着属于该事件的默认操作将不会发生。例如，这可以用于阻止表单提交：\n\n```js\ndocument.querySelector('form').addEventListener('submit', function (event) {\n  event.preventDefault();\n  // Form submission is prevented\n});\n```\n\n### event.stopPropagation()\n\n<code>event.stopPropagation()</code> 是一种方法，可防止事件在 DOM 树中冒泡，从而阻止任何父处理程序收到该事件的通知。当您希望在特定级别处理事件并且不希望它触发父元素上的处理程序时，这很有用：\n\n```js\ndocument.querySelector('.child').addEventListener('click', function (event) {\n  event.stopPropagation();\n  // Click event will not propagate to parent elements\n});\n```\n\n### 关键区别\n\n* <code>event.preventDefault()</code> 停止与事件关联的默认操作。\n* <code>event.stopPropagation()</code> 阻止事件传播（冒泡）到父元素。\n\n### 用例\n\n* 当您想阻止元素的默认行为时，请使用 <code>event.preventDefault()</code>，例如阻止链接导航或表单提交。\n* 当您想阻止事件到达父元素时，请使用 <code>event.stopPropagation()</code>，这在多个元素具有事件侦听器的复杂 UI 中很有用。\n\n## 延伸阅读\n\n* [MDN Web 文档：event.preventDefault()](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)\n* [MDN Web 文档：event.stopPropagation()](https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation)\n* [JavaScript 事件传播](https://javascript.info/bubbling-and-capturing)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-innerhtml-and-textcontent/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"cf1cdef8\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"497ccde1\",\n        \"f5ad7c8a\",\n        \"2a7816d0\",\n        \"2d138cd\",\n        \"2390c653\",\n        \"e463af2c\",\n        \"748ffe75\",\n        \"aa1dd641\",\n        \"f47a7738\",\n        \"f15ab52\",\n        \"ea670d32\",\n        \"e43b4de0\",\n        \"e0393ea\",\n        \"95cea882\",\n        \"748ffe75\",\n        \"5d45bc88\",\n        \"f47a7738\",\n        \"caa2416f\",\n        \"962c70b5\",\n        \"71c2cd48\",\n        \"1f4770e5\",\n        \"b9a087d\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"497ccde1\",\n        \"f5ad7c8a\",\n        \"2a7816d0\",\n        \"2d138cd\",\n        \"2390c653\",\n        \"e463af2c\",\n        \"748ffe75\",\n        \"aa1dd641\",\n        \"f47a7738\",\n        \"f15ab52\",\n        \"ea670d32\",\n        \"e43b4de0\",\n        \"e0393ea\",\n        \"95cea882\",\n        \"748ffe75\",\n        \"5d45bc88\",\n        \"f47a7738\",\n        \"caa2416f\",\n        \"962c70b5\",\n        \"71c2cd48\",\n        \"1f4770e5\",\n        \"b9a087d\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-innerhtml-and-textcontent/en-US.mdx",
    "content": "---\ntitle: What is the difference between `innerHTML` and `textContent`?\n---\n\n## TL;DR\n\n`innerHTML` and `textContent` are both properties used to get or set the content of an HTML element, but they serve different purposes. `innerHTML` returns or sets the HTML markup contained within the element, which means it can parse and render HTML tags. On the other hand, `textContent` returns or sets the text content of the element, ignoring any HTML tags and rendering them as plain text.\n\n```js\n// Example of innerHTML\nelement.innerHTML = '<strong>Bold Text</strong>'; // Renders as bold text\n\n// Example of textContent\nelement.textContent = '<strong>Bold Text</strong>'; // Renders as plain text: <strong>Bold Text</strong>\n```\n\n---\n\n## Difference between `innerHTML` and `textContent`\n\n### `innerHTML`\n\n`innerHTML` is a property that allows you to get or set the HTML markup contained within an element. It can parse and render HTML tags, making it useful for dynamically updating the structure of a webpage.\n\n#### Example\n\n```js\nconst element = document.getElementById('example');\nelement.innerHTML = '<strong>Bold Text</strong>'; // This will render as bold text\n```\n\n#### Use cases\n\n- Dynamically adding or updating HTML content\n- Rendering HTML tags and elements\n\n#### Security considerations\n\nUsing `innerHTML` can expose your application to Cross-Site Scripting (XSS) attacks if you insert untrusted content. Always sanitize any user input before setting it as `innerHTML`.\n\n### `textContent`\n\n`textContent` is a property that allows you to get or set the text content of an element. It ignores any HTML tags and renders them as plain text, making it safer for inserting user-generated content.\n\n#### Example\n\n```js\nconst element = document.getElementById('example');\nelement.textContent = '<strong>Bold Text</strong>'; // This will render as plain text: <strong>Bold Text</strong>\n```\n\n#### Use cases\n\n- Safely inserting user-generated content\n- Stripping HTML tags from a string\n\n#### Performance considerations\n\n`textContent` is generally faster than `innerHTML` because it does not parse and render HTML tags. It simply updates the text content of the element.\n\n## Further reading\n\n- [MDN Web Docs: innerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML)\n- [MDN Web Docs: textContent](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent)\n- [Cross-Site Scripting (XSS)](https://owasp.org/www-community/attacks/xss/)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-innerhtml-and-textcontent/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-difference-between-innerhtml-and-textcontent\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"web-api\", \"html\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"DOM Manipulation & Events\"\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-innerhtml-and-textcontent/zh-CN.mdx",
    "content": "---\ntitle: innerHTML 和 textContent 有什么区别？\n---\n\n## TL;DR\n\n `innerHTML` 和 `textContent` 都是用于获取或设置 HTML 元素内容的属性，但它们的作用不同。 `innerHTML` 返回或设置元素中包含的 HTML 标记，这意味着它可以解析和呈现 HTML 标签。 另一方面，`textContent` 返回或设置元素的文本内容，忽略任何 HTML 标签并将它们呈现为纯文本。\n\n```js\n// Example of innerHTML\nelement.innerHTML = '<strong>Bold Text</strong>'; // Renders as bold text\n\n// Example of textContent\nelement.textContent = '<strong>Bold Text</strong>'; // Renders as plain text: <strong>Bold Text</strong>\n```\n\n***\n\n## `innerHTML` 和 `textContent` 的区别\n\n### `innerHTML`\n\n`innerHTML` 是一种属性，允许您获取或设置元素中包含的 HTML 标记。 它可以解析和呈现 HTML 标签，使其可用于动态更新网页的结构。\n\n#### 示例\n\n```js\nconst element = document.getElementById('example');\nelement.innerHTML = '<strong>Bold Text</strong>'; // This will render as bold text\n```\n\n#### 用例\n\n* 动态添加或更新 HTML 内容\n* 渲染 HTML 标签和元素\n\n#### 安全注意事项\n\n如果插入不受信任的内容，使用 `innerHTML` 可能会使您的应用程序暴露于跨站点脚本 (XSS) 攻击。 在将任何用户输入设置为 `innerHTML` 之前，请务必对其进行清理。\n\n### `textContent`\n\n`textContent` 是一种属性，允许您获取或设置元素的文本内容。 它会忽略任何 HTML 标签并将它们呈现为纯文本，这使得它更安全地插入用户生成的内容。\n\n#### 示例\n\n```js\nconst element = document.getElementById('example');\nelement.textContent = '<strong>Bold Text</strong>'; // This will render as plain text: <strong>Bold Text</strong>\n```\n\n#### 用例\n\n* 安全地插入用户生成的内容\n* 从字符串中删除 HTML 标签\n\n#### 性能注意事项\n\n`textContent` 通常比 `innerHTML` 快，因为它不会解析和呈现 HTML 标签。 它只是更新元素的文本内容。\n\n## 延伸阅读\n\n* [MDN Web 文档：innerHTML](https://developer.mozilla.org/zh-CN/docs/Web/API/Element/innerHTML)\n* [MDN Web 文档：textContent](https://developer.mozilla.org/zh-CN/docs/Web/API/Node/textContent)\n* [跨站脚本 (XSS)](https://owasp.org/www-community/attacks/xss/)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-mouseenter-and-mouseover-event/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"79b293f8\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"2de3e97b\",\n        \"b5333c4d\",\n        \"791e2d5f\",\n        \"e77b99ec\",\n        \"2a7816d0\",\n        \"270f1eda\",\n        \"15becfee\",\n        \"33e977c9\",\n        \"633a235d\",\n        \"dc50850b\",\n        \"fa1cfeab\",\n        \"9b5019f0\",\n        \"a544941c\",\n        \"305c5970\",\n        \"54360c44\",\n        \"636857ef\",\n        \"1f4770e5\",\n        \"1930cce0\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"2de3e97b\",\n        \"b5333c4d\",\n        \"791e2d5f\",\n        \"e77b99ec\",\n        \"2a7816d0\",\n        \"270f1eda\",\n        \"15becfee\",\n        \"33e977c9\",\n        \"633a235d\",\n        \"dc50850b\",\n        \"fa1cfeab\",\n        \"9b5019f0\",\n        \"a544941c\",\n        \"305c5970\",\n        \"54360c44\",\n        \"636857ef\",\n        \"1f4770e5\",\n        \"1930cce0\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-mouseenter-and-mouseover-event/en-US.mdx",
    "content": "---\ntitle: What is the difference between `mouseenter` and `mouseover` event in JavaScript and browsers?\n---\n\n## TL;DR\n\nThe main difference lies in the bubbling behavior of `mouseenter` and `mouseover` events. `mouseenter` does not bubble while `mouseover` bubbles.\n\n`mouseenter` events do not bubble. The `mouseenter` event is triggered only when the mouse pointer enters the element itself, not its descendants. If a parent element has child elements, and the mouse pointer enters child elements, the `mouseenter` event will not be triggered on the parent element again, it's only triggered once upon entry of parent element without regard for its contents. If both parent and child have `mouseenter` listeners attached and the mouse pointer moves from the parent element to the child element, `mouseenter` will only fire for the child.\n\n`mouseover` events bubble up the DOM tree. The `mouseover` event is triggered when the mouse pointer enters the element or one of its descendants. If a parent element has child elements, and the mouse pointer enters child elements, the `mouseover` event will be triggered on the parent element again as well. If the parent element has multiple child elements, this can result in multiple event callbacks fired. If there are child elements, and the mouse pointer moves from the parent element to the child element, `mouseover` will fire for both the parent and the child.\n\n| Property | `mouseenter` | `mouseover` |\n| --- | --- | --- |\n| Bubbling | No | Yes |\n| Trigger | Only when entering itself | When entering itself and when entering descendants |\n\n---\n\n### `mouseenter` event:\n\n- **Does not bubble**: The `mouseenter` event does not bubble. It is only triggered when the mouse pointer enters the element to which the event listener is attached, not when it enters any child elements.\n- **Triggered once**: The `mouseenter` event is triggered only once when the mouse pointer enters the element, making it more predictable and easier to manage in certain scenarios.\n\nA use case for `mouseenter` is when you want to detect the mouse entering an element without worrying about child elements triggering the event multiple times.\n\n### `mouseover` Event:\n\n- **Bubbles up the DOM**: The `mouseover` event bubbles up through the DOM. This means that if you have an event listener on a parent element, it will also trigger when the mouse pointer moves over any child elements.\n- **Triggered multiple times**: The `mouseover` event is triggered every time the mouse pointer moves over an element or any of its child elements. This can lead to multiple triggers if you have nested elements.\n\nA use case for `mouseover` is when you want to detect when the mouse enters an element or any of its children and are okay with the events triggering multiple times.\n\n### Example\n\nHere's an example demonstrating the difference between `mouseover` and `mouseenter` events:\n\n```html\n<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Mouse Events Example</title>\n    <style>\n      .parent {\n        width: 200px;\n        height: 200px;\n        background-color: lightblue;\n        padding: 20px;\n      }\n      .child {\n        width: 100px;\n        height: 100px;\n        background-color: lightcoral;\n      }\n    </style>\n  </head>\n  <body>\n    <div class=\"parent\">\n      Parent Element\n      <div class=\"child\">Child Element</div>\n    </div>\n\n    <script>\n      const parent = document.querySelector('.parent');\n      const child = document.querySelector('.child');\n\n      // Mouseover event on parent.\n      parent.addEventListener('mouseover', () => {\n        console.log('Mouseover on parent');\n      });\n\n      // Mouseenter event on parent.\n      parent.addEventListener('mouseenter', () => {\n        console.log('Mouseenter on parent');\n      });\n\n      // Mouseover event on child.\n      child.addEventListener('mouseover', () => {\n        console.log('Mouseover on child');\n      });\n\n      // Mouseenter event on child.\n      child.addEventListener('mouseenter', () => {\n        console.log('Mouseenter on child');\n      });\n    </script>\n  </body>\n</html>\n```\n\n**Expected behavior**\n\n- When the mouse enters the parent element:\n  - The `mouseover` event on the parent will trigger.\n  - The `mouseenter` event on the parent will trigger.\n- When the mouse enters the child element:\n  - The `mouseover` event on the parent will trigger again because `mouseover` bubbles up from the child.\n  - The `mouseover` event on the child will trigger.\n  - The `mouseenter` event on the child will trigger.\n  - The `mouseenter` event on the parent will **not** trigger again because `mouseenter` does not bubble.\n\n## Further reading\n\n- [Element: mouseenter event - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event)\n- [Element: mouseover event - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-mouseenter-and-mouseover-event/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-difference-between-mouseenter-and-mouseover-event\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"web-api\", \"html\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 230,\n  \"difficulty\": \"easy\"\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-mouseenter-and-mouseover-event/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 和浏览器中 `mouseenter` 和 `mouseover` 事件有什么区别？\n---\n\n## TL;DR\n\n主要区别在于 `mouseenter` 和 `mouseover` 事件的冒泡行为。`mouseenter` 不冒泡，而 `mouseover` 冒泡。\n\n`mouseenter` 事件不冒泡。`mouseenter` 事件仅在鼠标指针进入元素本身时触发，而不是其后代元素。如果父元素有子元素，并且鼠标指针进入子元素，则不会再次在父元素上触发 `mouseenter` 事件，它仅在进入父元素时触发一次，而不考虑其内容。如果父元素和子元素都附加了 `mouseenter` 侦听器，并且鼠标指针从父元素移动到子元素，则 `mouseenter` 将仅为子元素触发。\n\n`mouseover` 事件会在 DOM 树中冒泡。当鼠标指针进入元素或其后代时，会触发 `mouseover` 事件。如果父元素有子元素，并且鼠标指针进入子元素，则父元素也会再次触发 `mouseover` 事件。如果父元素有多个子元素，这可能导致多次触发事件回调。如果有子元素，并且鼠标指针从父元素移动到子元素，则 `mouseover` 将同时为父元素和子元素触发。\n\n| 属性 | `mouseenter` | `mouseover` |\n| --- | --- | --- |\n| 冒泡 | 否 | 是 |\n| 触发 | 仅在进入自身时 | 进入自身和进入后代时 |\n\n***\n\n### `mouseenter` 事件：\n\n* **不冒泡**：`mouseenter` 事件不冒泡。它仅在鼠标指针进入附加了事件侦听器的元素时触发，而不是进入任何子元素时触发。\n* **触发一次**：当鼠标指针进入元素时，`mouseenter` 事件仅触发一次，这使得它在某些情况下更可预测且更易于管理。\n\n`mouseenter` 的一个用例是，当您希望检测鼠标进入元素而无需担心子元素多次触发事件时。\n\n### `mouseover` 事件：\n\n* **在 DOM 中冒泡**：`mouseover` 事件通过 DOM 冒泡。这意味着，如果您在父元素上有一个事件侦听器，当鼠标指针移动到任何子元素上时，它也会触发。\n* **多次触发**：每次鼠标指针移动到元素或其任何子元素上时，都会触发 `mouseover` 事件。如果您有嵌套元素，这可能导致多次触发。\n\n`mouseover` 的一个用例是，当您希望检测鼠标进入元素或其任何子元素，并且可以接受事件多次触发时。\n\n### 示例\n\n这是一个演示 `mouseover` 和 `mouseenter` 事件之间区别的示例：\n\n```html\n<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Mouse Events Example</title>\n    <style>\n      .parent {\n        width: 200px;\n        height: 200px;\n        background-color: lightblue;\n        padding: 20px;\n      }\n      .child {\n        width: 100px;\n        height: 100px;\n        background-color: lightcoral;\n      }\n    </style>\n  </head>\n  <body>\n    <div class=\"parent\">\n      Parent Element\n      <div class=\"child\">Child Element</div>\n    </div>\n\n    <script>\n      const parent = document.querySelector('.parent');\n      const child = document.querySelector('.child');\n\n      // Mouseover event on parent.\n      parent.addEventListener('mouseover', () => {\n        console.log('Mouseover on parent');\n      });\n\n      // Mouseenter event on parent.\n      parent.addEventListener('mouseenter', () => {\n        console.log('Mouseenter on parent');\n      });\n\n      // Mouseover event on child.\n      child.addEventListener('mouseover', () => {\n        console.log('Mouseover on child');\n      });\n\n      // Mouseenter event on child.\n      child.addEventListener('mouseenter', () => {\n        console.log('Mouseenter on child');\n      });\n    </script>\n  </body>\n</html>\n```\n\n**预期行为**\n\n* 当鼠标进入父元素时：\n  * 父元素上的 `mouseover` 事件将触发。\n  * 父元素上的 `mouseenter` 事件将触发。\n* 当鼠标进入子元素时：\n  * 父元素上的 `mouseover` 事件将再次触发，因为 `mouseover` 从子元素冒泡。\n  * 子元素上的 `mouseover` 事件将触发。\n  * 子元素上的 `mouseenter` 事件将触发。\n  * 父元素上的 `mouseenter` 事件将**不会**再次触发，因为 `mouseenter` 不冒泡。\n\n## 延伸阅读\n\n* [Element: mouseenter event - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event)\n* [Element: mouseover event - Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-settimeout-setimmediate-and-processnexttick/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"df127c7c\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"277d9f70\",\n        \"66c413e4\",\n        \"f51eaf48\",\n        \"2a7816d0\",\n        \"786a2222\",\n        \"48bcd9c\",\n        \"62ec2530\",\n        \"25a433ea\",\n        \"1a1c3da8\",\n        \"13435741\",\n        \"c15c4d27\",\n        \"9bc26348\",\n        \"93392d1a\",\n        \"519d95a7\",\n        \"b0fcbe8f\",\n        \"de4f9547\",\n        \"66c413e4\",\n        \"e1716c84\",\n        \"b2b5e879\",\n        \"58a1990d\",\n        \"1f4770e5\",\n        \"db801614\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"277d9f70\",\n        \"66c413e4\",\n        \"f51eaf48\",\n        \"2a7816d0\",\n        \"786a2222\",\n        \"48bcd9c\",\n        \"62ec2530\",\n        \"25a433ea\",\n        \"1a1c3da8\",\n        \"13435741\",\n        \"c15c4d27\",\n        \"9bc26348\",\n        \"93392d1a\",\n        \"519d95a7\",\n        \"b0fcbe8f\",\n        \"de4f9547\",\n        \"66c413e4\",\n        \"e1716c84\",\n        \"b2b5e879\",\n        \"58a1990d\",\n        \"1f4770e5\",\n        \"db801614\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-settimeout-setimmediate-and-processnexttick/en-US.mdx",
    "content": "---\ntitle: What is the difference between `setTimeout()`, `setImmediate()`, and `process.nextTick()`?\n---\n\n## TL;DR\n\n`setTimeout()` schedules a callback to run after a minimum delay. `setImmediate()` schedules a callback to run after the current event loop completes. `process.nextTick()` schedules a callback to run before the next event loop iteration begins.\n\n```js\nsetTimeout(() => console.log('setTimeout'), 0);\nsetImmediate(() => console.log('setImmediate'));\nprocess.nextTick(() => console.log('nextTick'));\n```\n\nIn this example, `process.nextTick()` will execute first, followed by either `setTimeout()` or `setImmediate()` depending on the environment.\n\n---\n\n## Difference between `setTimeout()`, `setImmediate()`, and `process.nextTick()`\n\n### `setTimeout()`\n\n`setTimeout()` is a function that schedules a callback to be executed after a specified delay in milliseconds. The minimum delay is approximately 4ms in modern browsers and Node.js.\n\n```js live\nsetTimeout(() => {\n  console.log('Executed after at least 1000 milliseconds');\n}, 1000);\n```\n\n### `setImmediate()`\n\n`setImmediate()` is a function available in Node.js that schedules a callback to be executed immediately after the current event loop phase completes. It is similar to `setTimeout()` with a delay of 0, but it is more efficient for immediate execution.\n\n```js\nsetImmediate(() => {\n  console.log('Executed after the current event loop phase');\n});\n```\n\n### `process.nextTick()`\n\n`process.nextTick()` is a function available in Node.js that schedules a callback to be executed before the next event loop iteration begins. It is used for deferring the execution of a function until the current operation completes.\n\n```js\nprocess.nextTick(() => {\n  console.log('Executed before the next event loop iteration');\n});\n```\n\n### Execution order\n\nThe execution order of these functions can be demonstrated with the following example:\n\n```js\nsetTimeout(() => console.log('setTimeout'), 0);\nsetImmediate(() => console.log('setImmediate'));\nprocess.nextTick(() => console.log('nextTick'));\n```\n\nIn this example, the output will be:\n\n```\nnextTick\nsetTimeout or setImmediate (order may vary)\nsetImmediate or setTimeout (order may vary)\n```\n\n`process.nextTick()` will always execute first, followed by either `setTimeout()` or `setImmediate()`, depending on the environment.\n\n## Further reading\n\n- [Node.js Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/)\n- [MDN Web Docs: setTimeout()](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout)\n- [Node.js Documentation: setImmediate()](https://nodejs.org/api/timers.html#timers_setimmediate_callback_args)\n- [Node.js Documentation: process.nextTick()](https://nodejs.org/api/process.html#process_process_nexttick_callback_args)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-settimeout-setimmediate-and-processnexttick/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-difference-between-settimeout-setimmediate-and-processnexttick\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Asynchronous JavaScript\"\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-settimeout-setimmediate-and-processnexttick/zh-CN.mdx",
    "content": "---\ntitle: setTimeout()、setImmediate() 和 process.nextTick() 之间有什么区别？\n---\n\n## TL;DR\n\n`setTimeout()` 安排在最短延迟后运行回调。`setImmediate()` 安排在当前事件循环完成后运行回调。`process.nextTick()` 安排在下一个事件循环迭代开始之前运行回调。\n\n```js\nsetTimeout(() => console.log('setTimeout'), 0);\nsetImmediate(() => console.log('setImmediate'));\nprocess.nextTick(() => console.log('nextTick'));\n```\n\n在此示例中，`process.nextTick()` 将首先执行，然后是 `setTimeout()` 或 `setImmediate()`，具体取决于环境。\n\n***\n\n## `setTimeout()`、`setImmediate()` 和 `process.nextTick()` 之间的区别\n\n### `setTimeout()`\n\n`setTimeout()` 是一个函数，它安排在指定的延迟（以毫秒为单位）后执行回调。在现代浏览器和 Node.js 中，最短延迟大约为 4 毫秒。\n\n```js live\nsetTimeout(() => {\n  console.log('Executed after at least 1000 milliseconds');\n}, 1000);\n```\n\n### `setImmediate()`\n\n`setImmediate()` 是 Node.js 中可用的一个函数，它安排在当前事件循环阶段完成后立即执行回调。它类似于延迟为 0 的 `setTimeout()`，但对于立即执行，它更有效。\n\n```js\nsetImmediate(() => {\n  console.log('Executed after the current event loop phase');\n});\n```\n\n### `process.nextTick()`\n\n`process.nextTick()` 是 Node.js 中可用的一个函数，它安排在下一个事件循环迭代开始之前执行回调。它用于将函数的执行推迟到当前操作完成。\n\n```js\nprocess.nextTick(() => {\n  console.log('Executed before the next event loop iteration');\n});\n```\n\n### 执行顺序\n\n以下示例演示了这些函数的执行顺序：\n\n```js\nsetTimeout(() => console.log('setTimeout'), 0);\nsetImmediate(() => console.log('setImmediate'));\nprocess.nextTick(() => console.log('nextTick'));\n```\n\n在此示例中，输出将是：\n\n```\nnextTick\nsetTimeout or setImmediate (order may vary)\nsetImmediate or setTimeout (order may vary)\n```\n\n`process.nextTick()` 将始终首先执行，然后是 `setTimeout()` 或 `setImmediate()`，具体取决于环境。\n\n## 延伸阅读\n\n* [Node.js 事件循环](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/)\n* [MDN Web 文档：setTimeout()](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout)\n* [Node.js 文档：setImmediate()](https://nodejs.org/api/timers.html#timers_setimmediate_callback_args)\n* [Node.js 文档：process.nextTick()](https://nodejs.org/api/process.html#process_process_nexttick_callback_args)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-the-window-object-and-the-document-object/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"5a9941fb\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"97b56856\",\n        \"2a7816d0\",\n        \"44496016\",\n        \"73ffffa8\",\n        \"895ab4e1\",\n        \"cc66c4ee\",\n        \"e76b9a8\",\n        \"e52cdd02\",\n        \"e8978390\",\n        \"a75bdefc\",\n        \"269d4ef6\",\n        \"e76b9a8\",\n        \"78d9b000\",\n        \"67423e0a\",\n        \"aa7e5699\",\n        \"1f4770e5\",\n        \"c892f25c\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"97b56856\",\n        \"2a7816d0\",\n        \"44496016\",\n        \"73ffffa8\",\n        \"895ab4e1\",\n        \"cc66c4ee\",\n        \"e76b9a8\",\n        \"e52cdd02\",\n        \"e8978390\",\n        \"a75bdefc\",\n        \"269d4ef6\",\n        \"e76b9a8\",\n        \"78d9b000\",\n        \"67423e0a\",\n        \"aa7e5699\",\n        \"1f4770e5\",\n        \"c892f25c\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-the-window-object-and-the-document-object/en-US.mdx",
    "content": "---\ntitle: What is the difference between the Window object and the Document object?\n---\n\n## TL;DR\n\nThe `Window` object represents the browser window and provides methods to control it, such as opening new windows or accessing the browser history. The `Document` object represents the content of the web page loaded in the window and provides methods to manipulate the DOM, such as selecting elements or modifying their content.\n\n---\n\n## Difference between the Window object and the Document object\n\n### Window object\n\nThe `Window` object is the global object in a web browser environment. It represents the browser window or frame that contains a DOM document. Here are some key points about the `Window` object:\n\n- It provides methods to control the browser window, such as `window.open()`, `window.close()`, and `window.alert()`.\n- It gives access to the browser's history through `window.history`.\n- It allows interaction with the browser's location (URL) via `window.location`.\n- It can be used to set and clear timers with `window.setTimeout()` and `window.setInterval()`.\n- It is the global execution context, meaning all global variables and functions are properties of the `Window` object.\n\nExample:\n\n```js\n// Open a new window\nwindow.open('https://www.example.com');\n\n// Display an alert\nwindow.alert('Hello, world!');\n```\n\n### Document object\n\nThe `Document` object represents the HTML or XML document loaded in the browser window. It is a property of the `Window` object (`window.document`). Here are some key points about the `Document` object:\n\n- It provides methods to select elements, such as `document.getElementById()`, `document.querySelector()`, and `document.getElementsByClassName()`.\n- It allows manipulation of the DOM, including creating, removing, and modifying elements.\n- It provides properties to access the document's metadata, such as `document.title` and `document.URL`.\n- It can be used to listen for and handle events within the document.\n\nExample:\n\n```js live\n// Create a new element and append it to the document body\nconst newElement = document.createElement('div');\nnewElement.id = 'myDiv';\nnewElement.textContent = 'Hello world';\ndocument.body.appendChild(newElement);\n\n// Select that element by its ID\nconst element = document.getElementById('myDiv');\n\nconsole.log(element);\nconsole.log(document.body);\n```\n\n### Key differences\n\n- The `Window` object represents the browser window, while the `Document` object represents the content of the web page.\n- The `Window` object provides methods to control the browser window and interact with the browser environment, whereas the `Document` object provides methods to manipulate the DOM and interact with the content of the web page.\n- The `Window` object is the global execution context, meaning all global variables and functions are properties of the `Window` object. The `Document` object is a property of the `Window` object.\n\n## Further reading\n\n- [MDN Web Docs: Window](https://developer.mozilla.org/en-US/docs/Web/API/Window)\n- [MDN Web Docs: Document](https://developer.mozilla.org/en-US/docs/Web/API/Document)\n- [JavaScript.info: Browser environment, specs](https://javascript.info/browser-environment)\n"
  },
  {
    "path": "questions/what-is-the-difference-between-the-window-object-and-the-document-object/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-difference-between-the-window-object-and-the-document-object\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"web-api\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/what-is-the-difference-between-the-window-object-and-the-document-object/zh-CN.mdx",
    "content": "---\ntitle: Window 对象和 Document 对象有什么区别？\n---\n\n## 总结\n\n `Window` 对象表示浏览器窗口，并提供控制它的方法，例如打开新窗口或访问浏览器历史记录。 `Document` 对象表示加载在窗口中的网页内容，并提供操作 DOM 的方法，例如选择元素或修改其内容。\n\n***\n\n## Window 对象和 Document 对象的区别\n\n### Window 对象\n\n `Window` 对象是 Web 浏览器环境中的全局对象。它表示包含 DOM 文档的浏览器窗口或框架。以下是关于 `Window` 对象的一些要点：\n\n*  它提供了控制浏览器窗口的方法，例如 `window.open()`、`window.close()` 和 `window.alert()`。\n*  它通过 `window.history` 访问浏览器的历史记录。\n*  它允许通过 `window.location` 与浏览器的位置（URL）进行交互。\n*  它可用于使用 `window.setTimeout()` 和 `window.setInterval()` 设置和清除计时器。\n*  它是全局执行上下文，这意味着所有全局变量和函数都是 `Window` 对象的属性。\n\n示例：\n\n```js\n// 打开一个新窗口\nwindow.open('https://www.example.com');\n\n// 显示一个警告\nwindow.alert('Hello, world!');\n```\n\n### Document 对象\n\n `Document` 对象表示加载在浏览器窗口中的 HTML 或 XML 文档。它是 `Window` 对象的属性 (`window.document`)。以下是关于 `Document` 对象的一些要点：\n\n*  它提供了选择元素的方法，例如 `document.getElementById()`、`document.querySelector()` 和 `document.getElementsByClassName()`。\n*  它允许操作 DOM，包括创建、删除和修改元素。\n*  它提供了访问文档元数据的属性，例如 `document.title` 和 `document.URL`。\n*  它可用于侦听和处理文档中的事件。\n\n示例：\n\n```js live\n// 创建一个新元素并将其附加到文档主体\nconst newElement = document.createElement('div');\nnewElement.id = 'myDiv';\nnewElement.textContent = 'Hello world';\ndocument.body.appendChild(newElement);\n\n// 通过其 ID 选择该元素\nconst element = document.getElementById('myDiv');\n\nconsole.log(element);\nconsole.log(document.body);\n```\n\n### 主要区别\n\n*  `Window` 对象表示浏览器窗口，而 `Document` 对象表示网页的内容。\n*  `Window` 对象提供了控制浏览器窗口和与浏览器环境交互的方法，而 `Document` 对象提供了操作 DOM 和与网页内容交互的方法。\n*  `Window` 对象是全局执行上下文，这意味着所有全局变量和函数都是 `Window` 对象的属性。 `Document` 对象是 `Window` 对象的属性。\n\n## 延伸阅读\n\n*  [MDN Web 文档：Window](https://developer.mozilla.org/en-US/docs/Web/API/Window)\n*  [MDN Web 文档：Document](https://developer.mozilla.org/en-US/docs/Web/API/Document)\n*  [JavaScript.info：浏览器环境，规范](https://javascript.info/browser-environment)\n"
  },
  {
    "path": "questions/what-is-the-dom-and-how-is-it-structured/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"a87e3e6c\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"a5a970b5\",\n        \"2a7816d0\",\n        \"c7ee0fc0\",\n        \"25841bc3\",\n        \"3f2a837d\",\n        \"9ec90fad\",\n        \"2db160c0\",\n        \"a9e18b7\",\n        \"9b5019f0\",\n        \"f52382bc\",\n        \"99d1d243\",\n        \"be4fd612\",\n        \"e6e67161\",\n        \"d31bc3c5\",\n        \"a7304f0f\",\n        \"5f2908ac\",\n        \"e76b9a8\",\n        \"b12b4d33\",\n        \"1f4770e5\",\n        \"ec95ba1b\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"a5a970b5\",\n        \"2a7816d0\",\n        \"c7ee0fc0\",\n        \"25841bc3\",\n        \"3f2a837d\",\n        \"9ec90fad\",\n        \"2db160c0\",\n        \"a9e18b7\",\n        \"9b5019f0\",\n        \"f52382bc\",\n        \"99d1d243\",\n        \"be4fd612\",\n        \"e6e67161\",\n        \"d31bc3c5\",\n        \"a7304f0f\",\n        \"5f2908ac\",\n        \"e76b9a8\",\n        \"b12b4d33\",\n        \"1f4770e5\",\n        \"ec95ba1b\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-dom-and-how-is-it-structured/en-US.mdx",
    "content": "---\ntitle: What is the DOM and how is it structured?\n---\n\n## TL;DR\n\nThe DOM, or Document Object Model, is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM is structured as a tree of objects, where each node represents part of the document, such as elements, attributes, and text.\n\n---\n\n## What is the DOM and how is it structured?\n\n### Definition\n\nThe Document Object Model (DOM) is a cross-platform and language-independent interface that treats an HTML, XHTML, or XML document as a tree structure. Each node in this tree represents a part of the document.\n\n### Structure\n\nThe DOM is structured as a hierarchical tree of nodes. Here are the main types of nodes:\n\n1. **Document node**: The root of the document tree. It represents the entire document.\n2. **Element nodes**: These represent HTML elements and form the bulk of the document tree.\n3. **Attribute nodes**: These are associated with element nodes and represent the attributes of those elements.\n4. **Text nodes**: These represent the text content within elements.\n5. **Comment nodes**: These represent comments in the HTML.\n\n### Example\n\nConsider the following HTML:\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>Document</title>\n  </head>\n  <body>\n    <h1>Hello, World!</h1>\n    <p>This is a paragraph.</p>\n  </body>\n</html>\n```\n\nThe DOM tree for this document would look like this:\n\n```\nDocument\n  └── html\n      ├── head\n      │   └── title\n      │       └── \"Document\"\n      └── body\n          ├── h1\n          │   └── \"Hello, World!\"\n          └── p\n              └── \"This is a paragraph.\"\n```\n\n### Accessing and manipulating the DOM\n\nJavaScript can be used to access and manipulate the DOM. Here are some common methods:\n\n- `document.getElementById(id)`: Selects an element by its ID.\n- `document.querySelector(selector)`: Selects the first element that matches a CSS selector.\n- `element.appendChild(node)`: Adds a new child node to an element.\n- `element.removeChild(node)`: Removes a child node from an element.\n\nExample:\n\n```js live\n// Create an <h1> element and add it to the DOM\nconst newElement = document.createElement('h1');\ndocument.body.appendChild(newElement);\n\n// Get the h1 element using querySelector\nconst heading = document.querySelector('h1');\nheading.textContent = 'Hello, DOM!';\nconsole.log(heading); // <h1>Hello, DOM!</h1>\n```\n\n## Further reading\n\n- [MDN Web Docs: Introduction to the DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction)\n- [W3C DOM Specification](https://www.w3.org/TR/DOM-Level-2-Core/introduction.html)\n- [JavaScript.info: The DOM](https://javascript.info/dom-nodes)\n"
  },
  {
    "path": "questions/what-is-the-dom-and-how-is-it-structured/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-dom-and-how-is-it-structured\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"html\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"DOM Manipulation & Events\"\n}\n"
  },
  {
    "path": "questions/what-is-the-dom-and-how-is-it-structured/zh-CN.mdx",
    "content": "---\ntitle: 什么是 DOM 以及它的结构？\n---\n\n## TL;DR\n\nDOM（文档对象模型）是用于 Web 文档的编程接口。它表示页面，以便程序可以更改文档结构、样式和内容。DOM 结构为对象树，其中每个节点代表文档的一部分，例如元素、属性和文本。\n\n***\n\n## 什么是 DOM 以及它的结构？\n\n### 定义\n\n文档对象模型 (DOM) 是一个跨平台且与语言无关的接口，它将 HTML、XHTML 或 XML 文档视为树结构。此树中的每个节点代表文档的一部分。\n\n### 结构\n\nDOM 结构为节点的分层树。以下是主要类型的节点：\n\n1. **文档节点**：文档树的根。它代表整个文档。\n2. **元素节点**：这些代表 HTML 元素，并构成文档树的大部分。\n3. **属性节点**：这些与元素节点相关联，代表这些元素的属性。\n4. **文本节点**：这些表示元素中的文本内容。\n5. **注释节点**：这些表示 HTML 中的注释。\n\n### 示例\n\n考虑以下 HTML：\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>Document</title>\n  </head>\n  <body>\n    <h1>Hello, World!</h1>\n    <p>This is a paragraph.</p>\n  </body>\n</html>\n```\n\n此文档的 DOM 树将如下所示：\n\n```\nDocument\n  └── html\n      ├── head\n      │   └── title\n      │       └── \"Document\"\n      └── body\n          ├── h1\n          │   └── \"Hello, World!\"\n          └── p\n              └── \"This is a paragraph.\"\n```\n\n### 访问和操作 DOM\n\nJavaScript 可用于访问和操作 DOM。以下是一些常用方法：\n\n* `document.getElementById(id)`：通过其 ID 选择一个元素。\n* `document.querySelector(selector)`：选择与 CSS 选择器匹配的第一个元素。\n* `element.appendChild(node)`：将新的子节点添加到元素。\n* `element.removeChild(node)`：从元素中删除子节点。\n\n示例：\n\n```js live\n// Create an <h1> element and add it to the DOM\nconst newElement = document.createElement('h1');\ndocument.body.appendChild(newElement);\n\n// Get the h1 element using querySelector\nconst heading = document.querySelector('h1');\nheading.textContent = 'Hello, DOM!';\nconsole.log(heading); // <h1>Hello, DOM!</h1>\n```\n\n## 延伸阅读\n\n* [MDN Web 文档：DOM 简介](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction)\n* [W3C DOM 规范](https://www.w3.org/TR/DOM-Level-2-Core/introduction.html)\n* [JavaScript.info：DOM](https://javascript.info/dom-nodes)\n"
  },
  {
    "path": "questions/what-is-the-factory-pattern-and-how-is-it-used/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"86982361\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"7dc2d21f\",\n        \"4d639730\",\n        \"ec0a89b3\",\n        \"2a7816d0\",\n        \"d3adba86\",\n        \"25841bc3\",\n        \"66e149e0\",\n        \"6dd3b324\",\n        \"815be641\",\n        \"30fcf78\",\n        \"d51518e5\",\n        \"53a12fa7\",\n        \"722fd728\",\n        \"4ef36bd7\",\n        \"f94e3976\",\n        \"3875b2b2\",\n        \"e5578aef\",\n        \"2819c383\",\n        \"658e051e\",\n        \"c4e00cf2\",\n        \"a564a20a\",\n        \"1f4770e5\",\n        \"1361313b\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"7dc2d21f\",\n        \"4d639730\",\n        \"ec0a89b3\",\n        \"2a7816d0\",\n        \"d3adba86\",\n        \"25841bc3\",\n        \"66e149e0\",\n        \"6dd3b324\",\n        \"815be641\",\n        \"30fcf78\",\n        \"d51518e5\",\n        \"53a12fa7\",\n        \"722fd728\",\n        \"4ef36bd7\",\n        \"f94e3976\",\n        \"3875b2b2\",\n        \"e5578aef\",\n        \"2819c383\",\n        \"658e051e\",\n        \"c4e00cf2\",\n        \"a564a20a\",\n        \"1f4770e5\",\n        \"1361313b\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-factory-pattern-and-how-is-it-used/en-US.mdx",
    "content": "---\ntitle: What is the Factory pattern and how is it used?\n---\n\n## TL;DR\n\nThe Factory pattern is a design pattern used to create objects without specifying the exact class of the object that will be created. It provides a way to encapsulate the instantiation logic and can be particularly useful when the creation process is complex or when the type of object to be created is determined at runtime.\n\nFor example, in JavaScript, you can use a factory function to create different types of objects:\n\n```js live\nfunction createAnimal(type) {\n  if (type === 'dog') {\n    return { sound: 'woof' };\n  } else if (type === 'cat') {\n    return { sound: 'meow' };\n  }\n}\n\nconst dog = createAnimal('dog');\nconst cat = createAnimal('cat');\n```\n\n---\n\n## What is the Factory pattern and how is it used?\n\n### Definition\n\nThe Factory pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. It encapsulates the object creation process, making the code more modular and easier to manage.\n\n### Use cases\n\n1. **Complex object creation**: When the process of creating an object is complex or involves multiple steps.\n2. **Runtime object determination**: When the type of object to be created is determined at runtime.\n3. **Decoupling**: To decouple the client code from the specific classes it needs to instantiate.\n\n### Implementation in JavaScript\n\nIn JavaScript, the Factory pattern can be implemented using factory functions or classes. Below are examples of both approaches.\n\n#### Factory function\n\nA factory function is a simple function that returns an object. It can contain logic to decide which type of object to create.\n\n```js live\nfunction createAnimal(type) {\n  if (type === 'dog') {\n    return { sound: 'woof' };\n  } else if (type === 'cat') {\n    return { sound: 'meow' };\n  } else {\n    return { sound: 'unknown' };\n  }\n}\n\nconst dog = createAnimal('dog');\nconst cat = createAnimal('cat');\nconsole.log(dog.sound); // Output: woof\nconsole.log(cat.sound); // Output: meow\n```\n\n#### Factory class\n\nA factory class can be used to encapsulate the creation logic within a class structure.\n\n```js live\nclass AnimalFactory {\n  createAnimal(type) {\n    if (type === 'dog') {\n      return new Dog();\n    } else if (type === 'cat') {\n      return new Cat();\n    } else {\n      return new Animal();\n    }\n  }\n}\n\nclass Dog {\n  constructor() {\n    this.sound = 'woof';\n  }\n}\n\nclass Cat {\n  constructor() {\n    this.sound = 'meow';\n  }\n}\n\nclass Animal {\n  constructor() {\n    this.sound = 'unknown';\n  }\n}\n\nconst factory = new AnimalFactory();\nconst dog = factory.createAnimal('dog');\nconst cat = factory.createAnimal('cat');\nconsole.log(dog.sound); // Output: woof\nconsole.log(cat.sound); // Output: meow\n```\n\n### Benefits\n\n1. **Encapsulation**: The creation logic is encapsulated in one place.\n2. **Flexibility**: Easy to add new types of objects without changing the client code.\n3. **Decoupling**: Reduces the dependency of the client code on specific classes.\n\n### Drawbacks\n\n1. **Complexity**: Can add unnecessary complexity if the object creation logic is simple.\n2. **Overhead**: May introduce additional overhead if not used judiciously.\n\n## Further reading\n\n- [Factory Method Pattern on Wikipedia](https://en.wikipedia.org/wiki/Factory_method_pattern)\n- [Factory Pattern in JavaScript](https://www.dofactory.com/javascript/design-patterns/factory)\n- [MDN Web Docs: Object-oriented JavaScript for beginners](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS)\n"
  },
  {
    "path": "questions/what-is-the-factory-pattern-and-how-is-it-used/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-factory-pattern-and-how-is-it-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Design Patterns\"\n}\n"
  },
  {
    "path": "questions/what-is-the-factory-pattern-and-how-is-it-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是工厂模式以及如何使用它？\n---\n\n## TL;DR\n\n工厂模式是一种设计模式，用于创建对象，而无需指定将要创建的对象的确切类。它提供了一种封装实例化逻辑的方法，当创建过程很复杂或当要创建的对象的类型在运行时确定时，它特别有用。\n\n例如，在 JavaScript 中，您可以使用工厂函数来创建不同类型的对象：\n\n```js live\nfunction createAnimal(type) {\n  if (type === 'dog') {\n    return { sound: 'woof' };\n  } else if (type === 'cat') {\n    return { sound: 'meow' };\n  }\n}\n\nconst dog = createAnimal('dog');\nconst cat = createAnimal('cat');\n```\n\n***\n\n## 什么是工厂模式以及如何使用它？\n\n### 定义\n\n工厂模式是一种创建型设计模式，它提供了一个用于在超类中创建对象的接口，但允许子类更改将要创建的对象的类型。它封装了对象创建过程，使代码更模块化，更易于管理。\n\n### 用例\n\n1. **复杂对象创建**：当创建对象的过程很复杂或涉及多个步骤时。\n2. **运行时对象确定**：当要创建的对象的类型在运行时确定时。\n3. **解耦**：将客户端代码与需要实例化的特定类解耦。\n\n### JavaScript 中的实现\n\n在 JavaScript 中，可以使用工厂函数或类来实现工厂模式。以下是这两种方法的示例。\n\n#### 工厂函数\n\n工厂函数是一个返回对象的简单函数。它可以包含决定要创建哪种类型对象的逻辑。\n\n```js live\nfunction createAnimal(type) {\n  if (type === 'dog') {\n    return { sound: 'woof' };\n  } else if (type === 'cat') {\n    return { sound: 'meow' };\n  } else {\n    return { sound: 'unknown' };\n  }\n}\n\nconst dog = createAnimal('dog');\nconst cat = createAnimal('cat');\nconsole.log(dog.sound); // Output: woof\nconsole.log(cat.sound); // Output: meow\n```\n\n#### 工厂类\n\n工厂类可用于将创建逻辑封装在类结构中。\n\n```js live\nclass AnimalFactory {\n  createAnimal(type) {\n    if (type === 'dog') {\n      return new Dog();\n    } else if (type === 'cat') {\n      return new Cat();\n    } else {\n      return new Animal();\n    }\n  }\n}\n\nclass Dog {\n  constructor() {\n    this.sound = 'woof';\n  }\n}\n\nclass Cat {\n  constructor() {\n    this.sound = 'meow';\n  }\n}\n\nclass Animal {\n  constructor() {\n    this.sound = 'unknown';\n  }\n}\n\nconst factory = new AnimalFactory();\nconst dog = factory.createAnimal('dog');\nconst cat = factory.createAnimal('cat');\nconsole.log(dog.sound); // Output: woof\nconsole.log(cat.sound); // Output: meow\n```\n\n### 优点\n\n1. **封装**：创建逻辑封装在一个地方。\n2. **灵活性**：无需更改客户端代码即可轻松添加新类型的对象。\n3. **解耦**：减少客户端代码对特定类的依赖。\n\n### 缺点\n\n1. **复杂性**：如果对象创建逻辑很简单，则会增加不必要的复杂性。\n2. **开销**：如果使用不当，可能会引入额外的开销。\n\n## 延伸阅读\n\n* [维基百科上的工厂方法模式](https://en.wikipedia.org/wiki/Factory_method_pattern)\n* [JavaScript 中的工厂模式](https://www.dofactory.com/javascript/design-patterns/factory)\n* [MDN Web 文档：面向对象的 JavaScript 初学者](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS)\n"
  },
  {
    "path": "questions/what-is-the-intl-namespace-object-for/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"955efbe3\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"2eee7190\",\n        \"cbf465f7\",\n        \"2a7816d0\",\n        \"7bcec0a9\",\n        \"f7acc004\",\n        \"e4c36186\",\n        \"3b1cbe06\",\n        \"7841e5ad\",\n        \"eb7c0ebd\",\n        \"82778e85\",\n        \"c07218a6\",\n        \"959a22a9\",\n        \"1dbadb3a\",\n        \"4e1a068d\",\n        \"581093f7\",\n        \"4c8764bb\",\n        \"a4c7d018\",\n        \"1f4770e5\",\n        \"592a88fd\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"2eee7190\",\n        \"cbf465f7\",\n        \"2a7816d0\",\n        \"7bcec0a9\",\n        \"f7acc004\",\n        \"e4c36186\",\n        \"3b1cbe06\",\n        \"7841e5ad\",\n        \"eb7c0ebd\",\n        \"82778e85\",\n        \"c07218a6\",\n        \"959a22a9\",\n        \"1dbadb3a\",\n        \"4e1a068d\",\n        \"581093f7\",\n        \"4c8764bb\",\n        \"a4c7d018\",\n        \"1f4770e5\",\n        \"592a88fd\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-intl-namespace-object-for/en-US.mdx",
    "content": "---\ntitle: What is the `Intl` namespace object for?\n---\n\n## TL;DR\n\nThe `Intl` namespace object in JavaScript is used for internationalization purposes. It provides language-sensitive string comparison, number formatting, and date and time formatting. For example, you can use `Intl.DateTimeFormat` to format dates according to a specific locale:\n\n```js live\nconst date = new Date();\nconst formatter = new Intl.DateTimeFormat('en-US');\nconsole.log(formatter.format(date)); // Outputs date in 'MM/DD/YYYY' format\n```\n\n---\n\n## What is the `Intl` namespace object for?\n\nThe `Intl` namespace object in JavaScript is a part of the ECMAScript Internationalization API, which provides language-sensitive string comparison, number formatting, and date and time formatting. This is particularly useful for applications that need to support multiple languages and regions.\n\n### Language-sensitive string comparison\n\nThe `Intl.Collator` object is used for comparing strings in a locale-aware manner. This is useful for sorting strings in a way that is consistent with the conventions of a particular language.\n\n```js live\nconst collator = new Intl.Collator('de-DE');\nconsole.log(collator.compare('ä', 'z')); // Outputs a negative number because 'ä' comes before 'z' in German\n```\n\n### Number formatting\n\nThe `Intl.NumberFormat` object is used for formatting numbers according to the conventions of a specific locale. This includes formatting for currency, percentages, and plain numbers.\n\n```js live\nconst number = 1234567.89;\nconst formatter = new Intl.NumberFormat('de-DE', {\n  style: 'currency',\n  currency: 'EUR',\n});\nconsole.log(formatter.format(number)); // Outputs '1.234.567,89 €'\n```\n\n### Date and time formatting\n\nThe `Intl.DateTimeFormat` object is used for formatting dates and times according to the conventions of a specific locale.\n\n```js live\nconst date = new Date();\nconst formatter = new Intl.DateTimeFormat('en-GB', {\n  year: 'numeric',\n  month: 'long',\n  day: 'numeric',\n});\nconsole.log(formatter.format(date)); // Outputs date in 'DD Month YYYY' format\n```\n\n### Plural rules\n\nThe `Intl.PluralRules` object is used to get the plural form of a number in a specific locale. This is useful for correctly pluralizing words in different languages.\n\n```js live\nconst pluralRules = new Intl.PluralRules('en-US');\nconsole.log(pluralRules.select(1)); // Outputs 'one'\nconsole.log(pluralRules.select(2)); // Outputs 'other'\n```\n\n## Further reading\n\n- [MDN Web Docs: Intl](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl)\n- [ECMAScript Internationalization API Specification](https://tc39.es/ecma402/)\n"
  },
  {
    "path": "questions/what-is-the-intl-namespace-object-for/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-intl-namespace-object-for\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"i18n\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Web APIs & Browser APIs\"\n}\n"
  },
  {
    "path": "questions/what-is-the-intl-namespace-object-for/zh-CN.mdx",
    "content": "---\ntitle: '`Intl` 命名空间对象是做什么的？'\n---\n\n## TL;DR\n\nJavaScript 中的 `Intl` 命名空间对象用于国际化目的。它提供了语言敏感的字符串比较、数字格式化以及日期和时间格式化。例如，您可以使用 `Intl.DateTimeFormat` 根据特定区域设置格式化日期：\n\n```js live\nconst date = new Date();\nconst formatter = new Intl.DateTimeFormat('en-US');\nconsole.log(formatter.format(date)); // Outputs date in 'MM/DD/YYYY' format\n```\n\n***\n\n## `Intl` 命名空间对象是做什么的？\n\nJavaScript 中的 `Intl` 命名空间对象是 ECMAScript 国际化 API 的一部分，它提供语言敏感的字符串比较、数字格式化以及日期和时间格式化。这对于需要支持多种语言和地区的应用程序特别有用。\n\n### 语言敏感的字符串比较\n\n`Intl.Collator` 对象用于以区域设置感知的方式比较字符串。这对于以符合特定语言的约定的方式对字符串进行排序非常有用。\n\n```js live\nconst collator = new Intl.Collator('de-DE');\nconsole.log(collator.compare('ä', 'z')); // Outputs a negative number because 'ä' comes before 'z' in German\n```\n\n### 数字格式化\n\n`Intl.NumberFormat` 对象用于根据特定区域设置的约定格式化数字。这包括货币、百分比和纯数字的格式化。\n\n```js live\nconst number = 1234567.89;\nconst formatter = new Intl.NumberFormat('de-DE', {\n  style: 'currency',\n  currency: 'EUR',\n});\nconsole.log(formatter.format(number)); // Outputs '1.234.567,89 €'\n```\n\n### 日期和时间格式化\n\n`Intl.DateTimeFormat` 对象用于根据特定区域设置的约定格式化日期和时间。\n\n```js live\nconst date = new Date();\nconst formatter = new Intl.DateTimeFormat('en-GB', {\n  year: 'numeric',\n  month: 'long',\n  day: 'numeric',\n});\nconsole.log(formatter.format(date)); // Outputs date in 'DD Month YYYY' format\n```\n\n### 复数规则\n\n`Intl.PluralRules` 对象用于获取特定区域设置中数字的复数形式。这对于正确地将不同语言中的单词复数化非常有用。\n\n```js live\nconst pluralRules = new Intl.PluralRules('en-US');\nconsole.log(pluralRules.select(1)); // Outputs 'one'\nconsole.log(pluralRules.select(2)); // Outputs 'other'\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Intl](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl)\n* [ECMAScript Internationalization API Specification](https://tc39.es/ecma402/)\n"
  },
  {
    "path": "questions/what-is-the-module-pattern-and-how-does-it-help-with-encapsulation/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"92c0dcdd\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"1073ce41\",\n        \"d244ccf4\",\n        \"2a7816d0\",\n        \"22086287\",\n        \"134cb0de\",\n        \"1aa567e7\",\n        \"428d15ab\",\n        \"db86390c\",\n        \"cb6e0a30\",\n        \"2a17c1a8\",\n        \"e006cc97\",\n        \"670df17e\",\n        \"1b6c5df2\",\n        \"3d002fe4\",\n        \"753eb59d\",\n        \"931eed51\",\n        \"86f854df\",\n        \"c4ba94cf\",\n        \"7b4594d0\",\n        \"b0c486f8\",\n        \"516563ba\",\n        \"31d3c5b8\",\n        \"1f4770e5\",\n        \"f051dfb4\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"1073ce41\",\n        \"d244ccf4\",\n        \"2a7816d0\",\n        \"22086287\",\n        \"134cb0de\",\n        \"1aa567e7\",\n        \"428d15ab\",\n        \"db86390c\",\n        \"cb6e0a30\",\n        \"2a17c1a8\",\n        \"e006cc97\",\n        \"670df17e\",\n        \"1b6c5df2\",\n        \"3d002fe4\",\n        \"753eb59d\",\n        \"931eed51\",\n        \"86f854df\",\n        \"c4ba94cf\",\n        \"7b4594d0\",\n        \"b0c486f8\",\n        \"516563ba\",\n        \"31d3c5b8\",\n        \"1f4770e5\",\n        \"f051dfb4\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-module-pattern-and-how-does-it-help-with-encapsulation/en-US.mdx",
    "content": "---\ntitle: What is the Module pattern and how does it help with encapsulation?\n---\n\n## TL;DR\n\nThe Module pattern in JavaScript is a design pattern used to create self-contained modules of code. It helps with encapsulation by allowing you to define private and public members within a module. Private members are not accessible from outside the module, while public members are exposed through a returned object. This pattern helps in organizing code, avoiding global namespace pollution, and maintaining a clean separation of concerns.\n\n```js live\nvar myModule = (function () {\n  var privateVar = 'I am private';\n\n  function privateMethod() {\n    console.log(privateVar);\n  }\n\n  return {\n    publicMethod: function () {\n      privateMethod();\n    },\n  };\n})();\n\nmyModule.publicMethod(); // Logs: I am private\n```\n\n---\n\n## What is the Module pattern and how does it help with encapsulation?\n\n### Introduction to the Module pattern\n\nThe Module pattern is a design pattern used in JavaScript to create modules of code that are self-contained. It leverages closures to create private and public members, allowing for better organization and encapsulation of code.\n\n### How the Module pattern works\n\nThe Module pattern typically involves an immediately-invoked function expression (IIFE) that returns an object. This object contains methods and properties that are exposed as the public API of the module. Inside the IIFE, you can define private variables and functions that are not accessible from outside the module.\n\n### Example of the Module pattern\n\nHere is a simple example of the Module pattern:\n\n```js live\nvar myModule = (function () {\n  // Private members\n  var privateVar = 'I am private';\n\n  function privateMethod() {\n    console.log(privateVar);\n  }\n\n  // Public members\n  return {\n    publicMethod: function () {\n      privateMethod();\n    },\n  };\n})();\n\nmyModule.publicMethod(); // Logs: I am private\n```\n\nIn this example:\n\n- `privateVar` and `privateMethod` are private members and cannot be accessed directly from outside the module.\n- `publicMethod` is a public member and can be accessed from outside the module. It can interact with the private members.\n\n### Benefits of using the Module pattern\n\n#### Encapsulation\n\nThe Module pattern helps in encapsulating code by hiding the internal implementation details and exposing only the necessary parts. This makes the code more modular and easier to maintain.\n\n#### Avoiding global namespace pollution\n\nBy using the Module pattern, you can avoid polluting the global namespace with variables and functions. This reduces the risk of naming collisions and makes the code more robust.\n\n#### Separation of concerns\n\nThe Module pattern promotes a clean separation of concerns by allowing you to group related functionality together. This makes the code more organized and easier to understand.\n\n### Conclusion\n\nThe Module pattern is a powerful tool in JavaScript for creating self-contained modules of code. It helps with encapsulation by allowing you to define private and public members, making the code more modular, maintainable, and organized.\n\n## Further reading\n\n- [JavaScript Module Pattern: In-Depth](https://toddmotto.com/mastering-the-module-pattern/)\n- [MDN Web Docs: Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)\n- [Addy Osmani's Learning JavaScript Design Patterns](https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript)\n"
  },
  {
    "path": "questions/what-is-the-module-pattern-and-how-does-it-help-with-encapsulation/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-module-pattern-and-how-does-it-help-with-encapsulation\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Design Patterns\"\n}\n"
  },
  {
    "path": "questions/what-is-the-module-pattern-and-how-does-it-help-with-encapsulation/zh-CN.mdx",
    "content": "---\ntitle: 什么是模块模式？它如何帮助封装？\n---\n\n## TL;DR\n\nJavaScript 中的模块模式是一种设计模式，用于创建自包含的代码模块。它通过允许您在模块内定义私有和公共成员来帮助封装。私有成员无法从模块外部访问，而公共成员通过返回的对象公开。这种模式有助于组织代码、避免全局命名空间污染以及保持关注点的清晰分离。\n\n```js live\nvar myModule = (function () {\n  var privateVar = 'I am private';\n\n  function privateMethod() {\n    console.log(privateVar);\n  }\n\n  return {\n    publicMethod: function () {\n      privateMethod();\n    },\n  };\n})();\n\nmyModule.publicMethod(); // Logs: I am private\n```\n\n***\n\n## 什么是模块模式？它如何帮助封装？\n\n### 模块模式简介\n\n模块模式是一种在 JavaScript 中用于创建自包含代码模块的设计模式。它利用闭包来创建私有和公共成员，从而更好地组织和封装代码。\n\n### 模块模式的工作原理\n\n模块模式通常涉及一个立即调用的函数表达式 (IIFE)，该表达式返回一个对象。此对象包含作为模块公共 API 公开的方法和属性。在 IIFE 内部，您可以定义无法从模块外部访问的私有变量和函数。\n\n### 模块模式示例\n\n这是一个模块模式的简单示例：\n\n```js live\nvar myModule = (function () {\n  // Private members\n  var privateVar = 'I am private';\n\n  function privateMethod() {\n    console.log(privateVar);\n  }\n\n  // Public members\n  return {\n    publicMethod: function () {\n      privateMethod();\n    },\n  };\n})();\n\nmyModule.publicMethod(); // Logs: I am private\n```\n\n在此示例中：\n\n* `privateVar` 和 `privateMethod` 是私有成员，不能直接从模块外部访问。\n* `publicMethod` 是一个公共成员，可以从模块外部访问。它可以与私有成员交互。\n\n### 使用模块模式的好处\n\n#### 封装\n\n模块模式通过隐藏内部实现细节并仅公开必要的部分来帮助封装代码。这使得代码更模块化，更易于维护。\n\n#### 避免全局命名空间污染\n\n通过使用模块模式，您可以避免使用变量和函数污染全局命名空间。这降低了命名冲突的风险，并使代码更健壮。\n\n#### 关注点分离\n\n模块模式通过允许您将相关功能组合在一起，从而促进了关注点的清晰分离。这使得代码更有条理，更容易理解。\n\n### 结论\n\n模块模式是 JavaScript 中用于创建自包含代码模块的强大工具。它通过允许您定义私有和公共成员来帮助封装，使代码更具模块化、可维护性和组织性。\n\n## 延伸阅读\n\n* [Addy Osmani 的 JavaScript 设计模式学习](https://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript)\n"
  },
  {
    "path": "questions/what-is-the-prototype-chain-and-how-does-it-work/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"6b9cdbbd\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"a9423b88\",\n        \"b442cc54\",\n        \"2dc18572\",\n        \"2a7816d0\",\n        \"e00af8fa\",\n        \"bb1744fe\",\n        \"18f611a7\",\n        \"1bcdde57\",\n        \"44d708b7\",\n        \"74e16eb8\",\n        \"9b5019f0\",\n        \"b442cc54\",\n        \"670df17e\",\n        \"71b00c34\",\n        \"18853ce5\",\n        \"c000bb96\",\n        \"5ac2cf91\",\n        \"670df17e\",\n        \"dc04009a\",\n        \"64d911eb\",\n        \"3d8820fd\",\n        \"fa1e3a8d\",\n        \"9b0804d\",\n        \"1f4770e5\",\n        \"84d01847\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"a9423b88\",\n        \"b442cc54\",\n        \"2dc18572\",\n        \"2a7816d0\",\n        \"e00af8fa\",\n        \"bb1744fe\",\n        \"18f611a7\",\n        \"1bcdde57\",\n        \"44d708b7\",\n        \"74e16eb8\",\n        \"9b5019f0\",\n        \"b442cc54\",\n        \"670df17e\",\n        \"71b00c34\",\n        \"18853ce5\",\n        \"c000bb96\",\n        \"5ac2cf91\",\n        \"670df17e\",\n        \"dc04009a\",\n        \"64d911eb\",\n        \"3d8820fd\",\n        \"fa1e3a8d\",\n        \"9b0804d\",\n        \"1f4770e5\",\n        \"84d01847\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-prototype-chain-and-how-does-it-work/en-US.mdx",
    "content": "---\ntitle: What is the prototype chain and how does it work?\n---\n\n## TL;DR\n\nThe prototype chain is a mechanism in JavaScript that allows objects to inherit properties and methods from other objects. When you try to access a property on an object, JavaScript will first look for the property on the object itself. If it doesn't find it, it will look at the object's prototype, and then the prototype's prototype, and so on, until it either finds the property or reaches the end of the chain, which is `null`.\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nPerson.prototype.greet = function () {\n  console.log(`Hello, my name is ${this.name}`);\n};\n\nconst alice = new Person('Alice');\nalice.greet(); // \"Hello, my name is Alice\"\n```\n\nIn this example, `alice` inherits the `greet` method from `Person.prototype`.\n\n---\n\n## What is the prototype chain and how does it work?\n\n### Understanding prototypes\n\nIn JavaScript, every object has a prototype. A prototype is also an object, and it can have its own prototype, forming a chain. This chain is known as the prototype chain.\n\n### How the prototype chain works\n\nWhen you try to access a property or method on an object, JavaScript will:\n\n1. Look for the property or method on the object itself.\n2. If it doesn't find it, it will look at the object's prototype.\n3. If it still doesn't find it, it will look at the prototype's prototype.\n4. This process continues until it either finds the property or method or reaches the end of the chain, which is `null`.\n\n### Example\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nPerson.prototype.greet = function () {\n  console.log(`Hello, my name is ${this.name}`);\n};\n\nconst alice = new Person('Alice');\nalice.greet(); // \"Hello, my name is Alice\"\n```\n\nIn this example:\n\n1. `alice` is an instance of `Person`.\n2. `alice` does not have a `greet` method directly on it.\n3. JavaScript looks at `alice`'s prototype, which is `Person.prototype`.\n4. `Person.prototype` has a `greet` method, so JavaScript calls it.\n\n### Prototype chain in built-in objects\n\nJavaScript's built-in objects also use the prototype chain. For example, arrays inherit from `Array.prototype`, which in turn inherits from `Object.prototype`.\n\n```js live\nconst arr = [1, 2, 3];\nconsole.log(arr.toString()); // \"1,2,3\"\n```\n\nIn this example:\n\n1. `arr` is an instance of `Array`.\n2. `arr` does not have a `toString` method directly on it.\n3. JavaScript looks at `arr`'s prototype, which is `Array.prototype`.\n4. `Array.prototype` has a `toString` method, so JavaScript calls it.\n\n### Modifying prototypes\n\nYou can add properties and methods to an object's prototype, and all instances of that object will have access to those properties and methods.\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst alice = new Person('Alice');\n\nPerson.prototype.sayGoodbye = function () {\n  console.log(`Goodbye from ${this.name}`);\n};\n\nalice.sayGoodbye(); // \"Goodbye from Alice\"\n```\n\nIn this example, we added a `sayGoodbye` method to `Person.prototype`, and now `alice` can use it.\n\n## Further reading\n\n- [MDN Web Docs: Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\n- [JavaScript.info: Prototypes](https://javascript.info/prototype-inheritance)\n- [Eloquent JavaScript: Prototypes](https://eloquentjavascript.net/06_object.html#h_jl8p9u9e2d)\n"
  },
  {
    "path": "questions/what-is-the-prototype-chain-and-how-does-it-work/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-prototype-chain-and-how-does-it-work\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"intermediate\",\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Prototypes & Inheritance\"\n}\n"
  },
  {
    "path": "questions/what-is-the-prototype-chain-and-how-does-it-work/zh-CN.mdx",
    "content": "---\ntitle: 什么是原型链以及它如何工作？\n---\n\n## TL;DR\n\n原型链是 JavaScript 中允许对象从其他对象继承属性和方法的一种机制。当您尝试访问对象上的属性时，JavaScript 将首先在对象本身上查找该属性。如果找不到，它将查看对象的原型，然后是原型的原型，依此类推，直到找到该属性或到达链的末尾，即 `null`。\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nPerson.prototype.greet = function () {\n  console.log(`Hello, my name is ${this.name}`);\n};\n\nconst alice = new Person('Alice');\nalice.greet(); // \"Hello, my name is Alice\"\n```\n\n在这个例子中，`alice` 从 `Person.prototype` 继承了 `greet` 方法。\n\n***\n\n## 什么是原型链以及它如何工作？\n\n### 理解原型\n\n在 JavaScript 中，每个对象都有一个原型。原型也是一个对象，它可以有自己的原型，从而形成一个链。这个链被称为原型链。\n\n### 原型链的工作原理\n\n当您尝试访问对象上的属性或方法时，JavaScript 将会：\n\n1. 在对象本身上查找属性或方法。\n2. 如果找不到，它将查看对象的原型。\n3. 如果仍然找不到，它将查看原型的原型。\n4. 此过程将一直持续到找到属性或方法，或者到达链的末尾，即 `null`。\n\n### 例子\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nPerson.prototype.greet = function () {\n  console.log(`Hello, my name is ${this.name}`);\n};\n\nconst alice = new Person('Alice');\nalice.greet(); // \"Hello, my name is Alice\"\n```\n\n在这个例子中：\n\n1. `alice` 是 `Person` 的一个实例。\n2. `alice` 并没有直接在其上拥有 `greet` 方法。\n3. JavaScript 查看 `alice` 的原型，即 `Person.prototype`。\n4. `Person.prototype` 有一个 `greet` 方法，所以 JavaScript 调用它。\n\n### 内置对象中的原型链\n\nJavaScript 的内置对象也使用原型链。例如，数组继承自 `Array.prototype`，而 `Array.prototype` 又继承自 `Object.prototype`。\n\n```js live\nconst arr = [1, 2, 3];\nconsole.log(arr.toString()); // \"1,2,3\"\n```\n\n在这个例子中：\n\n1. `arr` 是 `Array` 的一个实例。\n2. `arr` 并没有直接在其上拥有 `toString` 方法。\n3. JavaScript 查看 `arr` 的原型，即 `Array.prototype`。\n4. `Array.prototype` 有一个 `toString` 方法，所以 JavaScript 调用它。\n\n### 修改原型\n\n您可以向对象的原型添加属性和方法，该对象的所有实例都可以访问这些属性和方法。\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst alice = new Person('Alice');\n\nPerson.prototype.sayGoodbye = function () {\n  console.log(`Goodbye from ${this.name}`);\n};\n\nalice.sayGoodbye(); // \"Goodbye from Alice\"\n```\n\n在此示例中，我们向 `Person.prototype` 添加了一个 `sayGoodbye` 方法，现在 `alice` 可以使用它。\n\n## 延伸阅读\n\n* [MDN Web Docs: Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain)\n* [JavaScript.info: Prototypes](https://javascript.info/prototype-inheritance)\n* [Eloquent JavaScript: Prototypes](https://eloquentjavascript.net/06_object.html#h_jl8p9u9e2d)\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-break-and-continue-statements/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"17c9dbca\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"a7d6a386\",\n        \"6424556b\",\n        \"2a7816d0\",\n        \"fa30f38a\",\n        \"7fc72d5f\",\n        \"e3ccf0b\",\n        \"74ffc159\",\n        \"84b11f6a\",\n        \"43cab552\",\n        \"90ccbffa\",\n        \"b187595a\",\n        \"223870d9\",\n        \"74ffc159\",\n        \"f35971df\",\n        \"38193419\",\n        \"9a5615dd\",\n        \"1f4770e5\",\n        \"ec544a3e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"a7d6a386\",\n        \"6424556b\",\n        \"2a7816d0\",\n        \"fa30f38a\",\n        \"7fc72d5f\",\n        \"e3ccf0b\",\n        \"74ffc159\",\n        \"84b11f6a\",\n        \"43cab552\",\n        \"90ccbffa\",\n        \"b187595a\",\n        \"223870d9\",\n        \"74ffc159\",\n        \"f35971df\",\n        \"38193419\",\n        \"9a5615dd\",\n        \"1f4770e5\",\n        \"ec544a3e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-break-and-continue-statements/en-US.mdx",
    "content": "---\ntitle: What is the purpose of the `break` and `continue` statements?\n---\n\n## TL;DR\n\nThe `break` statement is used to exit a loop or switch statement prematurely, while the `continue` statement skips the current iteration of a loop and proceeds to the next iteration. For example, in a `for` loop, `break` will stop the loop entirely, and `continue` will skip to the next iteration.\n\n```js live\nfor (let i = 0; i < 10; i++) {\n  if (i === 5) break; // exits the loop when i is 5\n  console.log(i);\n}\n\nfor (let i = 0; i < 10; i++) {\n  if (i === 5) continue; // skips the iteration when i is 5\n  console.log(i);\n}\n```\n\n---\n\n## Purpose of the `break` and `continue` statements\n\n### `break` statement\n\nThe `break` statement is used to exit a loop or a switch statement before it has completed all its iterations or cases. This is useful when you want to stop the execution of the loop or switch based on a certain condition.\n\n#### Example in a loop\n\n```js live\nfor (let i = 0; i < 10; i++) {\n  if (i === 5) break; // exits the loop when i is 5\n  console.log(i);\n}\n// Output: 0 1 2 3 4\n```\n\n#### Example in a switch statement\n\n```js live\nfunction printDayOfWeek(day) {\n  switch (day) {\n    case 1:\n      console.log('Monday');\n      break;\n    case 2:\n      console.log('Tuesday');\n      break;\n    // other cases\n    default:\n      console.log('Invalid day');\n  }\n}\nprintDayOfWeek(2); // Tuesday\nprintDayOfWeek('myDay'); // Invalid day\n```\n\n### `continue` statement\n\nThe `continue` statement is used to skip the current iteration of a loop and proceed to the next iteration. This is useful when you want to skip certain iterations based on a condition without exiting the loop entirely.\n\n#### Example in a loop\n\n```js live\nfor (let i = 0; i < 10; i++) {\n  if (i === 5) continue; // skips the iteration when i is 5\n  console.log(i);\n}\n// Output: 0 1 2 3 4 6 7 8 9\n```\n\n### Differences between `break` and `continue`\n\n- The `break` statement exits the loop or switch statement entirely.\n- The `continue` statement skips the current iteration and moves to the next iteration of the loop.\n\n## Further reading\n\n- [MDN Web Docs: break](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break)\n- [MDN Web Docs: continue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue)\n- [JavaScript Loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-break-and-continue-statements/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-purpose-of-the-break-and-continue-statements\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Operators & Control Flow\"\n}\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-break-and-continue-statements/zh-CN.mdx",
    "content": "---\ntitle: break 和 continue 语句的用途是什么？\n---\n\n## TL;DR\n\n`break` 语句用于过早地退出循环或 switch 语句，而 `continue` 语句跳过循环的当前迭代并继续到下一个迭代。例如，在 `for` 循环中，`break` 将完全停止循环，而 `continue` 将跳到下一个迭代。\n\n```js live\nfor (let i = 0; i < 10; i++) {\n  if (i === 5) break; // 当 i 为 5 时退出循环\n  console.log(i);\n}\n\nfor (let i = 0; i < 10; i++) {\n  if (i === 5) continue; // 当 i 为 5 时跳过迭代\n  console.log(i);\n}\n```\n\n***\n\n## `break` 和 `continue` 语句的用途\n\n### `break` 语句\n\n`break` 语句用于在循环或 switch 语句完成所有迭代或 case 之前退出。当您希望根据特定条件停止循环或 switch 的执行时，这很有用。\n\n#### 循环中的示例\n\n```js live\nfor (let i = 0; i < 10; i++) {\n  if (i === 5) break; // 当 i 为 5 时退出循环\n  console.log(i);\n}\n// 输出：0 1 2 3 4\n```\n\n#### switch 语句中的示例\n\n```js live\nfunction printDayOfWeek(day) {\n  switch (day) {\n    case 1:\n      console.log('Monday');\n      break;\n    case 2:\n      console.log('Tuesday');\n      break;\n    // 其他情况\n    default:\n      console.log('Invalid day');\n  }\n}\nprintDayOfWeek(2); // 星期二\nprintDayOfWeek('myDay'); // 无效的日期\n```\n\n### `continue` 语句\n\n`continue` 语句用于跳过循环的当前迭代并继续到下一个迭代。当您希望根据某个条件跳过某些迭代而不完全退出循环时，这很有用。\n\n#### 循环中的示例\n\n```js live\nfor (let i = 0; i < 10; i++) {\n  if (i === 5) continue; // 当 i 为 5 时跳过迭代\n  console.log(i);\n}\n// 输出：0 1 2 3 4 6 7 8 9\n```\n\n### `break` 和 `continue` 的区别\n\n* `break` 语句完全退出循环或 switch 语句。\n* `continue` 语句跳过当前迭代并移至循环的下一个迭代。\n\n## 延伸阅读\n\n* [MDN Web 文档：break](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break)\n* [MDN Web 文档：continue](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue)\n* [JavaScript 循环](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-finally-block/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"c346fc05\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"6d2a5fef\",\n        \"41379cd8\",\n        \"2a7816d0\",\n        \"4437a7d1\",\n        \"8982136e\",\n        \"5a5af94f\",\n        \"3e3034bc\",\n        \"43c50729\",\n        \"628e78aa\",\n        \"e559e321\",\n        \"fb163764\",\n        \"ddc4f34d\",\n        \"8f9f4391\",\n        \"1f4770e5\",\n        \"ba040869\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"6d2a5fef\",\n        \"41379cd8\",\n        \"2a7816d0\",\n        \"4437a7d1\",\n        \"8982136e\",\n        \"5a5af94f\",\n        \"3e3034bc\",\n        \"43c50729\",\n        \"628e78aa\",\n        \"e559e321\",\n        \"fb163764\",\n        \"ddc4f34d\",\n        \"8f9f4391\",\n        \"1f4770e5\",\n        \"ba040869\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-finally-block/en-US.mdx",
    "content": "---\ntitle: What is the purpose of the `finally` block?\n---\n\n## TL;DR\n\nThe `finally` block in JavaScript is used to execute code after a `try` and `catch` block, regardless of whether an error was thrown or caught. It ensures that certain cleanup or finalization code runs no matter what. For example:\n\n```js\ntry {\n  // Code that may throw an error\n} catch (error) {\n  // Code to handle the error\n} finally {\n  // Code that will always run\n}\n```\n\n---\n\n## Purpose of the `finally` block\n\n### Ensuring cleanup\n\nThe `finally` block is often used to ensure that certain cleanup code runs regardless of whether an error occurred or not. This is useful for tasks like closing files, releasing resources, or resetting states.\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/posts/1',\n    );\n    if (!response.ok) {\n      throw new Error(`HTTP error! Status: ${response.status}`);\n    }\n    const data = await response.json();\n    console.log('Fetched data:', data);\n  } catch (error) {\n    console.error('An error occurred:', error);\n  } finally {\n    console.log('Cleanup code runs here');\n  }\n}\n\nfetchData();\n// Try creating a typo in the URL to see error handling.\n```\n\n### Guaranteeing execution\n\nThe `finally` block guarantees that the code within it will execute after the `try` and `catch` blocks have finished. This is true even if a `return` statement is encountered in the `try` or `catch` blocks.\n\n```js live\nfunction exampleFunction() {\n  try {\n    return 'Try block';\n  } catch (error) {\n    return 'Catch block';\n  } finally {\n    console.log('Finally block');\n  }\n}\n\nconsole.log(exampleFunction()); // Output: 'Finally block' followed by 'Try block'\n```\n\n### Handling asynchronous code\n\nWhen dealing with asynchronous code, the `finally` block can be used to ensure that certain actions are taken after a promise is settled, regardless of its outcome.\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.json())\n  .then((res) => console.log(res))\n  .catch((error) => console.error('Fetch error:', error))\n  .finally(() => console.log('Fetch attempt finished'));\n```\n\n## Further reading\n\n- [MDN Web Docs: try...catch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch)\n- [JavaScript.info: try...catch](https://javascript.info/try-catch)\n- [MDN Web Docs: Promise.prototype.finally()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally)\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-finally-block/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-purpose-of-the-finally-block\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Error Handling\"\n}\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-finally-block/zh-CN.mdx",
    "content": "---\ntitle: finally 块的目的是什么？\n---\n\n## TL;DR\n\nJavaScript 中的 `finally` 块用于在 `try` 和 `catch` 块之后执行代码，无论是否抛出或捕获了错误。它确保某些清理或最终确定代码无论如何都会运行。例如：\n\n```js\ntry {\n  // Code that may throw an error\n} catch (error) {\n  // Code to handle the error\n} finally {\n  // Code that will always run\n}\n```\n\n***\n\n## `finally` 块的目的\n\n### 确保清理\n\n`finally` 块通常用于确保某些清理代码运行，无论是否发生错误。这对于关闭文件、释放资源或重置状态等任务很有用。\n\n```js live\nasync function fetchData() {\n  try {\n    const response = await fetch(\n      'https://jsonplaceholder.typicode.com/posts/1',\n    );\n    if (!response.ok) {\n      throw new Error(`HTTP error! Status: ${response.status}`);\n    }\n    const data = await response.json();\n    console.log('Fetched data:', data);\n  } catch (error) {\n    console.error('An error occurred:', error);\n  } finally {\n    console.log('Cleanup code runs here');\n  }\n}\n\nfetchData();\n// Try creating a typo in the URL to see error handling.\n```\n\n### 保证执行\n\n`finally` 块保证其中的代码将在 `try` 和 `catch` 块完成后执行。即使在 `try` 或 `catch` 块中遇到 `return` 语句，也是如此。\n\n```js live\nfunction exampleFunction() {\n  try {\n    return 'Try block';\n  } catch (error) {\n    return 'Catch block';\n  } finally {\n    console.log('Finally block');\n  }\n}\n\nconsole.log(exampleFunction()); // Output: 'Finally block' followed by 'Try block'\n```\n\n### 处理异步代码\n\n处理异步代码时，`finally` 块可用于确保在 Promise 解决后采取某些操作，无论其结果如何。\n\n```js live\nfetch('https://jsonplaceholder.typicode.com/todos/1')\n  .then((response) => response.json())\n  .then((res) => console.log(res))\n  .catch((error) => console.error('Fetch error:', error))\n  .finally(() => console.log('Fetch attempt finished'));\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: try...catch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch)\n* [JavaScript.info: try...catch](https://javascript.info/try-catch)\n* [MDN Web Docs: Promise.prototype.finally()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally)\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-new-keyword/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"d7bc711b\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"b6748fea\",\n        \"b18cd56a\",\n        \"2a7816d0\",\n        \"ed348c69\",\n        \"503ac9c3\",\n        \"7204d89a\",\n        \"6813475a\",\n        \"6b31663c\",\n        \"dbf60fb4\",\n        \"6dcbf91\",\n        \"b3463dff\",\n        \"a855ac62\",\n        \"b9ba5b3b\",\n        \"75fe6fee\",\n        \"b8c2b9df\",\n        \"35a95f4e\",\n        \"1f4770e5\",\n        \"318c056e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"b6748fea\",\n        \"b18cd56a\",\n        \"2a7816d0\",\n        \"ed348c69\",\n        \"503ac9c3\",\n        \"7204d89a\",\n        \"6813475a\",\n        \"6b31663c\",\n        \"dbf60fb4\",\n        \"6dcbf91\",\n        \"b3463dff\",\n        \"a855ac62\",\n        \"b9ba5b3b\",\n        \"75fe6fee\",\n        \"b8c2b9df\",\n        \"35a95f4e\",\n        \"1f4770e5\",\n        \"318c056e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-new-keyword/en-US.mdx",
    "content": "---\ntitle: What is the purpose of the `new` keyword?\n---\n\n## TL;DR\n\nThe `new` keyword in JavaScript is used to create an instance of a user-defined object type or one of the built-in object types that has a constructor function. When you use `new`, it does four things: it creates a new object, sets the prototype, binds `this` to the new object, and returns the new object.\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person1 = new Person('Alice');\nconsole.log(person1.name); // Alice\n```\n\n---\n\n## The purpose of the `new` keyword\n\n### Creating a new object\n\nThe `new` keyword is used to create a new instance of an object. When you call a constructor function with `new`, it creates a new object.\n\n```js live\nfunction Car(model) {\n  this.model = model;\n}\n\nconst myCar = new Car('Toyota');\nconsole.log(myCar.model); // Toyota\n```\n\n### Setting the prototype\n\nThe new object’s internal `[[Prototype]]` property is set to the constructor function’s `prototype` property. This allows the new object to inherit properties and methods from the constructor’s prototype.\n\n```js live\nfunction Animal(type) {\n  this.type = type;\n}\n\nAnimal.prototype.speak = function () {\n  console.log(`${this.type} makes a sound`);\n};\n\nconst dog = new Animal('Dog');\ndog.speak(); // Dog makes a sound\n```\n\n### Binding `this` to the new object\n\nInside the constructor function, `this` refers to the new object that is being created. This allows you to add properties and methods to the new object.\n\n```js live\nfunction Book(title) {\n  this.title = title;\n}\n\nconst myBook = new Book('JavaScript Essentials');\nconsole.log(myBook.title); // JavaScript Essentials\n```\n\n### Returning the new object\n\nThe `new` keyword implicitly returns the new object created by the constructor function. If the constructor function explicitly returns an object, that object will be returned instead.\n\n```js live\nfunction Gadget(name) {\n  this.name = name;\n  return { type: 'Electronic' };\n}\n\nconst myGadget = new Gadget('Smartphone');\nconsole.log(myGadget.type); // Electronic\nconsole.log(myGadget.name); // undefined\n```\n\n## Further reading\n\n- [MDN Web Docs: new operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new)\n- [JavaScript.info: Constructor, operator \"new\"](https://javascript.info/constructor-new)\n- [Eloquent JavaScript: Constructors](https://eloquentjavascript.net/06_object.html#h_XTmO7z7MPq)\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-new-keyword/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-purpose-of-the-new-keyword\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Prototypes & Inheritance\"\n}\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-new-keyword/zh-CN.mdx",
    "content": "---\ntitle: new 关键字的用途是什么？\n---\n\n## TL;DR\n\nJavaScript 中的 `new` 关键字用于创建用户定义的对象类型或具有构造函数的内置对象类型的实例。 当你使用 `new` 时，它会做四件事：它创建一个新对象，设置原型，将 `this` 绑定到新对象，并返回新对象。\n\n```js live\nfunction Person(name) {\n  this.name = name;\n}\n\nconst person1 = new Person('Alice');\nconsole.log(person1.name); // Alice\n```\n\n***\n\n## `new` 关键字的用途\n\n### 创建一个新对象\n\n`new` 关键字用于创建对象的新实例。 当你使用 `new` 调用构造函数时，它会创建一个新对象。\n\n```js live\nfunction Car(model) {\n  this.model = model;\n}\n\nconst myCar = new Car('Toyota');\nconsole.log(myCar.model); // Toyota\n```\n\n### 设置原型\n\n新对象的内部 `[[Prototype]]` 属性被设置为构造函数的 `prototype` 属性。 这允许新对象从构造函数的原型继承属性和方法。\n\n```js live\nfunction Animal(type) {\n  this.type = type;\n}\n\nAnimal.prototype.speak = function () {\n  console.log(`${this.type} makes a sound`);\n};\n\nconst dog = new Animal('Dog');\ndog.speak(); // Dog makes a sound\n```\n\n### 将 `this` 绑定到新对象\n\n在构造函数内部，`this` 指的是正在创建的新对象。 这允许你将属性和方法添加到新对象。\n\n```js live\nfunction Book(title) {\n  this.title = title;\n}\n\nconst myBook = new Book('JavaScript Essentials');\nconsole.log(myBook.title); // JavaScript Essentials\n```\n\n### 返回新对象\n\n`new` 关键字隐式地返回由构造函数创建的新对象。 如果构造函数显式地返回一个对象，则将返回该对象。\n\n```js live\nfunction Gadget(name) {\n  this.name = name;\n  return { type: 'Electronic' };\n}\n\nconst myGadget = new Gadget('Smartphone');\nconsole.log(myGadget.type); // Electronic\nconsole.log(myGadget.name); // undefined\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: new operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new)\n* [JavaScript.info: Constructor, operator \"new\"](https://javascript.info/constructor-new)\n* [Eloquent JavaScript: Constructors](https://eloquentjavascript.net/06_object.html#h_XTmO7z7MPq)\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-switch-statement/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"7e3c718d\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"d673e085\",\n        \"ef339182\",\n        \"2a7816d0\",\n        \"e194cec3\",\n        \"b63af4db\",\n        \"caf6404e\",\n        \"1ce4c309\",\n        \"51b65241\",\n        \"5f593b6e\",\n        \"4e8ede6c\",\n        \"1105b4b1\",\n        \"9b5019f0\",\n        \"f2d69d2f\",\n        \"f404fd5f\",\n        \"e6ceecd7\",\n        \"b361b976\",\n        \"dbed4949\",\n        \"c11edc8\",\n        \"e1716c84\",\n        \"3524328a\",\n        \"31860e51\",\n        \"1f4770e5\",\n        \"84a60e2f\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d673e085\",\n        \"ef339182\",\n        \"2a7816d0\",\n        \"e194cec3\",\n        \"b63af4db\",\n        \"caf6404e\",\n        \"1ce4c309\",\n        \"51b65241\",\n        \"5f593b6e\",\n        \"4e8ede6c\",\n        \"1105b4b1\",\n        \"9b5019f0\",\n        \"f2d69d2f\",\n        \"f404fd5f\",\n        \"e6ceecd7\",\n        \"b361b976\",\n        \"dbed4949\",\n        \"c11edc8\",\n        \"e1716c84\",\n        \"3524328a\",\n        \"31860e51\",\n        \"1f4770e5\",\n        \"84a60e2f\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-switch-statement/en-US.mdx",
    "content": "---\ntitle: What is the purpose of the `switch` statement?\n---\n\n## TL;DR\n\nThe `switch` statement is used to execute one block of code among many based on the value of an expression. It is an alternative to using multiple `if...else if` statements. The `switch` statement evaluates an expression, matches the expression's value to a `case` label, and executes the associated block of code. If no `case` matches, the `default` block is executed.\n\n```js\nswitch (expression) {\n  case value1:\n    // code to be executed if expression === value1\n    break;\n  case value2:\n    // code to be executed if expression === value2\n    break;\n  default:\n  // code to be executed if no case matches\n}\n```\n\n---\n\n## Purpose of the `switch` statement\n\n### Simplifies multiple conditional checks\n\nThe `switch` statement provides a cleaner and more readable way to handle multiple conditional checks compared to using multiple `if...else if` statements. It is particularly useful when you need to compare the same expression against different values.\n\n### Syntax and structure\n\nThe basic syntax of a `switch` statement is as follows:\n\n```js\nswitch (expression) {\n  case value1:\n    // code to be executed if expression === value1\n    break;\n  case value2:\n    // code to be executed if expression === value2\n    break;\n  // more cases...\n  default:\n  // code to be executed if no case matches\n}\n```\n\n### How it works\n\n1. **Expression evaluation**: The `switch` statement evaluates the expression once.\n2. **Case matching**: It compares the result of the expression to the values of each `case` label.\n3. **Code execution**: If a match is found, the code associated with that `case` is executed.\n4. **Break statement**: The `break` statement is used to exit the `switch` block. If omitted, the next `case` will be executed (fall-through behavior).\n5. **Default case**: The `default` case is optional and executes if no matching `case` is found.\n\n### Example\n\nHere is an example of a `switch` statement in action:\n\n```js live\nlet fruit = 'apple';\n\nswitch (fruit) {\n  case 'banana':\n    console.log('Banana is yellow.');\n    break;\n  case 'apple':\n    console.log('Apple is red.');\n    break;\n  case 'grape':\n    console.log('Grape is purple.');\n    break;\n  default:\n    console.log('Unknown fruit.');\n}\n```\n\nIn this example, the output will be `Apple is red.` because the value of `fruit` matches the `case 'apple'`.\n\n### Fall-through behavior\n\nIf the `break` statement is omitted, the `switch` statement will continue to execute the subsequent `case` blocks until it encounters a `break` or the end of the `switch` block. This is known as fall-through behavior.\n\n```js live\nlet day = 2;\n\nswitch (day) {\n  case 1:\n    console.log('Monday');\n  case 2:\n    console.log('Tuesday');\n  case 3:\n    console.log('Wednesday');\n  default:\n    console.log('Unknown day');\n}\n```\n\nIn this example, the output will be:\n\n```\nTuesday\nWednesday\nUnknown day\n```\n\nThis happens because there are no `break` statements to stop the execution after the `case 2` block.\n\n## Further reading\n\n- [MDN Web Docs: switch statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch)\n- [JavaScript.info: switch statement](https://javascript.info/switch)\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-switch-statement/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-purpose-of-the-switch-statement\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Operators & Control Flow\"\n}\n"
  },
  {
    "path": "questions/what-is-the-purpose-of-the-switch-statement/zh-CN.mdx",
    "content": "---\ntitle: switch 语句的用途是什么？\n---\n\n## TL;DR\n\nswitch 语句用于根据表达式的值执行多个代码块中的一个。它是使用多个 `if...else if` 语句的替代方案。switch 语句计算一个表达式，将表达式的值与 `case` 标签匹配，并执行相关的代码块。如果没有 `case` 匹配，则执行 `default` 块。\n\n```js\nswitch (expression) {\n  case value1:\n    // code to be executed if expression === value1\n    break;\n  case value2:\n    // code to be executed if expression === value2\n    break;\n  default:\n  // code to be executed if no case matches\n}\n```\n\n***\n\n## `switch` 语句的用途\n\n### 简化多个条件检查\n\n与使用多个 `if...else if` 语句相比，`switch` 语句提供了一种更清晰、更易读的方式来处理多个条件检查。当您需要将同一表达式与不同的值进行比较时，它特别有用。\n\n### 语法和结构\n\n以下是 `switch` 语句的基本语法：\n\n```js\nswitch (expression) {\n  case value1:\n    // code to be executed if expression === value1\n    break;\n  case value2:\n    // code to be executed if expression === value2\n    break;\n  // more cases...\n  default:\n  // code to be executed if no case matches\n}\n```\n\n### 工作原理\n\n1. **表达式求值**：`switch` 语句计算一次表达式。\n2. **案例匹配**：它将表达式的结果与每个 `case` 标签的值进行比较。\n3. **代码执行**：如果找到匹配项，则执行与该 `case` 关联的代码。\n4. **Break 语句**：`break` 语句用于退出 `switch` 块。如果省略，将执行下一个 `case`（fall-through 行为）。\n5. **Default 案例**：`default` 案例是可选的，如果未找到匹配的 `case`，则执行。\n\n### 示例\n\n这是一个 `switch` 语句的示例：\n\n```js live\nlet fruit = 'apple';\n\nswitch (fruit) {\n  case 'banana':\n    console.log('香蕉是黄色的。');\n    break;\n  case 'apple':\n    console.log('苹果是红色的。');\n    break;\n  case 'grape':\n    console.log('葡萄是紫色的。');\n    break;\n  default:\n    console.log('未知水果。');\n}\n```\n\n在此示例中，输出将是 `Apple is red.`，因为 `fruit` 的值与 `case 'apple'` 匹配。\n\n### Fall-through 行为\n\n如果省略 `break` 语句，`switch` 语句将继续执行后续的 `case` 块，直到遇到 `break` 或 `switch` 块的末尾。这被称为 fall-through 行为。\n\n```js live\nlet day = 2;\n\nswitch (day) {\n  case 1:\n    console.log('星期一');\n  case 2:\n    console.log('星期二');\n  case 3:\n    console.log('星期三');\n  default:\n    console.log('未知日期');\n}\n```\n\n在这个例子中，输出将是：\n\n```\nTuesday\nWednesday\nUnknown day\n```\n\n发生这种情况是因为在 `case 2` 块之后没有 `break` 语句来停止执行。\n\n## 延伸阅读\n\n* [MDN Web Docs: switch statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch)\n* [JavaScript.info: switch statement](https://javascript.info/switch)\n"
  },
  {
    "path": "questions/what-is-the-spread-operator-and-how-is-it-used/en-US.langnostic.json",
    "content": "{\n  \"content\": {\n    \"source\": {\n      \"hashes\": [\n        \"77da26a5\",\n        \"4830c945\",\n        \"6ca0e90b\",\n        \"2a7816d0\",\n        \"94a7b9ce\",\n        \"8e41ac23\",\n        \"7de1b33\",\n        \"5c877420\",\n        \"ee6c7c6d\",\n        \"6eac6b38\",\n        \"b118e365\",\n        \"4dded10a\",\n        \"288c27ee\",\n        \"6a0c41cb\",\n        \"679ab33b\",\n        \"9bbb63c1\",\n        \"8ea29ca0\",\n        \"c0fb02fb\",\n        \"a2682ef8\",\n        \"973e67c0\",\n        \"ed290858\",\n        \"6726d5c6\",\n        \"477961a2\",\n        \"1f4770e5\",\n        \"af185466\"\n      ],\n      \"locale\": \"en-US\"\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4830c945\",\n        \"6ca0e90b\",\n        \"2a7816d0\",\n        \"94a7b9ce\",\n        \"8e41ac23\",\n        \"7de1b33\",\n        \"5c877420\",\n        \"ee6c7c6d\",\n        \"6eac6b38\",\n        \"b118e365\",\n        \"4dded10a\",\n        \"288c27ee\",\n        \"6a0c41cb\",\n        \"679ab33b\",\n        \"9bbb63c1\",\n        \"8ea29ca0\",\n        \"c0fb02fb\",\n        \"a2682ef8\",\n        \"973e67c0\",\n        \"ed290858\",\n        \"6726d5c6\",\n        \"477961a2\",\n        \"1f4770e5\",\n        \"af185466\"\n      ]\n    }\n  },\n  \"frontmatter\": {\n    \"title\": \"f32e43\"\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-spread-operator-and-how-is-it-used/en-US.mdx",
    "content": "---\ntitle: What is the spread operator and how is it used?\n---\n\n## TL;DR\n\nThe spread operator, represented by three dots (`...`), is used in JavaScript to expand iterable objects like arrays or strings into individual elements. It can also be used to spread object properties. For example, you can use it to combine arrays, copy arrays, or pass array elements as arguments to a function.\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\nconst combined = [...arr1, ...arr2];\nconsole.log(combined); // [1, 2, 3, 4, 5, 6]\n\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { c: 3, d: 4 };\nconst combinedObj = { ...obj1, ...obj2 };\nconsole.log(combinedObj); // { a: 1, b: 2, c: 3, d: 4 }\n```\n\n---\n\n## What is the spread operator and how is it used?\n\n### Expanding arrays\n\nThe spread operator can be used to expand elements of an array into individual elements. This is useful for combining arrays or copying arrays.\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\nconst combined = [...arr1, ...arr2];\nconsole.log(combined); // [1, 2, 3, 4, 5, 6]\n```\n\n### Copying arrays\n\nYou can create a shallow copy of an array using the spread operator.\n\n```js live\nconst original = [1, 2, 3];\nconst copy = [...original];\nconsole.log(copy); // [1, 2, 3]\n```\n\n### Passing array elements as function arguments\n\nThe spread operator can be used to pass elements of an array as arguments to a function.\n\n```js live\nfunction sum(a, b, c) {\n  return a + b + c;\n}\n\nconst numbers = [1, 2, 3];\nconsole.log(sum(...numbers)); // 6\n```\n\n### Expanding objects\n\nThe spread operator can also be used to expand properties of an object. This is useful for combining objects or copying objects.\n\n```js live\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { c: 3, d: 4 };\nconst combinedObj = { ...obj1, ...obj2 };\nconsole.log(combinedObj); // { a: 1, b: 2, c: 3, d: 4 }\n```\n\n### Copying objects\n\nYou can create a shallow copy of an object using the spread operator.\n\n```js live\nconst originalObj = { a: 1, b: 2 };\nconst copyObj = { ...originalObj };\nconsole.log(copyObj); // { a: 1, b: 2 }\n```\n\n### Using with strings\n\nThe spread operator can also be used to expand a string into individual characters.\n\n```js live\nconst str = 'hello';\nconst chars = [...str];\nconsole.log(chars); // ['h', 'e', 'l', 'l', 'o']\n```\n\n## Further reading\n\n- [MDN Web Docs: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n- [JavaScript.info: Spread operator](https://javascript.info/rest-parameters-spread-operator#spread-operator)\n- [FreeCodeCamp: JavaScript Spread and Rest Operators](https://www.freecodecamp.org/news/javascript-spread-and-rest-operators/)\n"
  },
  {
    "path": "questions/what-is-the-spread-operator-and-how-is-it-used/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-spread-operator-and-how-is-it-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Data Types & Variables\"\n}\n"
  },
  {
    "path": "questions/what-is-the-spread-operator-and-how-is-it-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是展开运算符以及如何使用它？\n---\n\n## TL;DR\n\n展开运算符，用三个点 (`...`) 表示，在 JavaScript 中用于将可迭代对象（如数组或字符串）展开为单个元素。它也可以用于展开对象属性。例如，您可以使用它来组合数组、复制数组或将数组元素作为参数传递给函数。\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\nconst combined = [...arr1, ...arr2];\nconsole.log(combined); // [1, 2, 3, 4, 5, 6]\n\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { c: 3, d: 4 };\nconst combinedObj = { ...obj1, ...obj2 };\nconsole.log(combinedObj); // { a: 1, b: 2, c: 3, d: 4 }\n```\n\n***\n\n## 什么是展开运算符以及如何使用它？\n\n### 展开数组\n\n展开运算符可用于将数组的元素展开为单个元素。这对于组合数组或复制数组很有用。\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\nconst combined = [...arr1, ...arr2];\nconsole.log(combined); // [1, 2, 3, 4, 5, 6]\n```\n\n### 复制数组\n\n您可以使用展开运算符创建数组的浅拷贝。\n\n```js live\nconst original = [1, 2, 3];\nconst copy = [...original];\nconsole.log(copy); // [1, 2, 3]\n```\n\n### 将数组元素作为函数参数传递\n\n展开运算符可用于将数组的元素作为参数传递给函数。\n\n```js live\nfunction sum(a, b, c) {\n  return a + b + c;\n}\n\nconst numbers = [1, 2, 3];\nconsole.log(sum(...numbers)); // 6\n```\n\n### 展开对象\n\n展开运算符也可用于展开对象的属性。这对于组合对象或复制对象很有用。\n\n```js live\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { c: 3, d: 4 };\nconst combinedObj = { ...obj1, ...obj2 };\nconsole.log(combinedObj); // { a: 1, b: 2, c: 3, d: 4 }\n```\n\n### 复制对象\n\n您可以使用展开运算符创建对象的浅拷贝。\n\n```js live\nconst originalObj = { a: 1, b: 2 };\nconst copyObj = { ...originalObj };\nconsole.log(copyObj); // { a: 1, b: 2 }\n```\n\n### 使用字符串\n\n扩展运算符也可以用来将字符串扩展成单个字符。\n\n```js live\nconst str = 'hello';\nconst chars = [...str];\nconsole.log(chars); // ['h', 'e', 'l', 'l', 'o']\n```\n\n## 延伸阅读\n\n* [MDN Web Docs: Spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)\n* [JavaScript.info: Spread operator](https://javascript.info/rest-parameters-spread-operator#spread-operator)\n* [FreeCodeCamp: JavaScript Spread and Rest Operators](https://www.freecodecamp.org/news/javascript-spread-and-rest-operators/)\n"
  },
  {
    "path": "questions/what-is-the-ternary-operator-and-how-is-it-used/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"f2569823\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"d22b4a74\",\n        \"2a7816d0\",\n        \"f9aba8af\",\n        \"83283a80\",\n        \"4af0e29\",\n        \"eea083fa\",\n        \"7fcc5ad4\",\n        \"4ab8f7e4\",\n        \"efd00327\",\n        \"19c254ba\",\n        \"49bd19b5\",\n        \"eb034731\",\n        \"9a6d1ea4\",\n        \"cc6fa7e8\",\n        \"5bb2a61b\",\n        \"31b305a7\",\n        \"2b9ea689\",\n        \"6dd3b324\",\n        \"d0b89c50\",\n        \"3b882e5b\",\n        \"f64f0206\",\n        \"1f4770e5\",\n        \"56dac479\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d22b4a74\",\n        \"2a7816d0\",\n        \"f9aba8af\",\n        \"83283a80\",\n        \"4af0e29\",\n        \"eea083fa\",\n        \"7fcc5ad4\",\n        \"4ab8f7e4\",\n        \"efd00327\",\n        \"19c254ba\",\n        \"49bd19b5\",\n        \"eb034731\",\n        \"9a6d1ea4\",\n        \"cc6fa7e8\",\n        \"5bb2a61b\",\n        \"31b305a7\",\n        \"2b9ea689\",\n        \"6dd3b324\",\n        \"d0b89c50\",\n        \"3b882e5b\",\n        \"f64f0206\",\n        \"1f4770e5\",\n        \"56dac479\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-ternary-operator-and-how-is-it-used/en-US.mdx",
    "content": "---\ntitle: What is the ternary operator and how is it used?\n---\n\n## TL;DR\n\nThe ternary operator is a shorthand for an `if-else` statement in JavaScript. It takes three operands: a condition, a result for true, and a result for false. The syntax is `condition ? expr1 : expr2`. For example, `let result = (a > b) ? 'a is greater' : 'b is greater';` assigns `'a is greater'` to `result` if `a` is greater than `b`, otherwise it assigns `'b is greater'`.\n\n---\n\n## What is the ternary operator and how is it used?\n\n### Introduction\n\nThe ternary operator, also known as the conditional operator, is a concise way to perform conditional evaluations in JavaScript. It is the only operator in JavaScript that takes three operands.\n\n### Syntax\n\nThe syntax for the ternary operator is:\n\n```js\ncondition ? expr1 : expr2;\n```\n\n- `condition`: An expression that evaluates to `true` or `false`\n- `expr1`: An expression that is executed if the condition is `true`\n- `expr2`: An expression that is executed if the condition is `false`\n\n### Example usage\n\nHere is a basic example of the ternary operator:\n\n```js live\nlet age = 18;\nlet canVote = age >= 18 ? 'Yes' : 'No';\nconsole.log(canVote); // Output: Yes\n```\n\nIn this example, the condition `age >= 18` is evaluated. If it is `true`, the string `'Yes'` is assigned to `canVote`. If it is `false`, the string `'No'` is assigned to `canVote`.\n\n### Nested ternary operators\n\nYou can also nest ternary operators, although it can make the code harder to read:\n\n```js live\nlet score = 85;\nlet grade =\n  score >= 90\n    ? 'A'\n    : score >= 80\n      ? 'B'\n      : score >= 70\n        ? 'C'\n        : score >= 60\n          ? 'D'\n          : 'F';\nconsole.log(grade); // Output: B\n```\n\nIn this example, the ternary operator is used to assign a grade based on the value of `score`.\n\n### Use cases\n\n- **Simple conditional assignments**: When you need to assign a value based on a condition.\n- **Inline conditional rendering**: Useful in JSX for conditional rendering in React.\n\n### Best practices\n\n- **Readability**: While the ternary operator can make code more concise, overusing it or nesting it too deeply can make the code hard to read. Use it judiciously.\n- **Complex conditions**: For complex conditions, consider using `if-else` statements for better readability.\n\n## Further reading\n\n- [MDN Web Docs: Conditional (ternary) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)\n- [JavaScript.info: Conditional operators](https://javascript.info/ifelse#conditional-operator)\n- [W3Schools: JavaScript ternary operator](https://www.w3schools.com/jsref/jsref_operators.asp)\n"
  },
  {
    "path": "questions/what-is-the-ternary-operator-and-how-is-it-used/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-ternary-operator-and-how-is-it-used\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Operators & Control Flow\"\n}\n"
  },
  {
    "path": "questions/what-is-the-ternary-operator-and-how-is-it-used/zh-CN.mdx",
    "content": "---\ntitle: 什么是三元运算符？它如何使用？\n---\n\n## 总结\n\n三元运算符是 JavaScript 中 `if-else` 语句的简写形式。它需要三个操作数：一个条件、一个真值结果和一个假值结果。语法是 `condition ? expr1 : expr2`。例如，`let result = (a > b) ? 'a is greater' : 'b is greater';` 如果 `a` 大于 `b`，则将 `'a is greater'` 赋值给 `result`，否则将 `'b is greater'` 赋值给 `result`。\n\n***\n\n## 什么是三元运算符？它如何使用？\n\n### 简介\n\n三元运算符，也称为条件运算符，是在 JavaScript 中执行条件评估的简便方法。它是 JavaScript 中唯一需要三个操作符的运算符。\n\n### 语法\n\n三元运算符的语法是：\n\n```js\ncondition ? expr1 : expr2;\n```\n\n* `condition`：一个计算结果为 `true` 或 `false` 的表达式\n* `expr1`：如果条件为 `true`，则执行的表达式\n* `expr2`：如果条件为 `false`，则执行的表达式\n\n### 使用示例\n\n这是一个三元运算符的基本示例：\n\n```js live\nlet age = 18;\nlet canVote = age >= 18 ? 'Yes' : 'No';\nconsole.log(canVote); // Output: Yes\n```\n\n在此示例中，将评估条件 `age >= 18`。如果为 `true`，则将字符串 `'Yes'` 赋值给 `canVote`。如果为 `false`，则将字符串 `'No'` 赋值给 `canVote`。\n\n### 嵌套三元运算符\n\n您也可以嵌套三元运算符，尽管这会使代码更难阅读：\n\n```js live\nlet score = 85;\nlet grade =\n  score >= 90\n    ? 'A'\n    : score >= 80\n      ? 'B'\n      : score >= 70\n        ? 'C'\n        : score >= 60\n          ? 'D'\n          : 'F';\nconsole.log(grade); // Output: B\n```\n\n在此示例中，三元运算符用于根据 `score` 的值分配等级。\n\n### 用例\n\n* **简单的条件赋值**：当您需要根据条件分配值时。\n* **内联条件渲染**：在 JSX 中用于在 React 中进行条件渲染时很有用。\n\n### 最佳实践\n\n* **可读性**：虽然三元运算符可以使代码更简洁，但过度使用或嵌套过深会使代码难以阅读。请谨慎使用。\n* **复杂条件**：对于复杂条件，请考虑使用 `if-else` 语句以获得更好的可读性。\n\n## 延伸阅读\n\n* [MDN Web Docs: Conditional (ternary) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)\n* [JavaScript.info: Conditional operators](https://javascript.info/ifelse#conditional-operator)\n* [W3Schools: JavaScript ternary operator](https://www.w3schools.com/jsref/jsref_operators.asp)\n"
  },
  {
    "path": "questions/what-is-the-use-of-promiseall/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"961514a0\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"4c82ca14\",\n        \"9eb9d290\",\n        \"2a7816d0\",\n        \"7699a9b5\",\n        \"7e5d8c12\",\n        \"53d0fd95\",\n        \"eea083fa\",\n        \"8e365f7f\",\n        \"876aebf3\",\n        \"4e8ede6c\",\n        \"ae5bce3d\",\n        \"4e891c05\",\n        \"9b5019f0\",\n        \"5165cd50\",\n        \"faec4b31\",\n        \"890b0975\",\n        \"c019b9d8\",\n        \"8c78e8e1\",\n        \"c2d6786c\",\n        \"f5f05a32\",\n        \"6dd3b324\",\n        \"ba53abf9\",\n        \"1f4770e5\",\n        \"da2048a0\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"4c82ca14\",\n        \"9eb9d290\",\n        \"2a7816d0\",\n        \"7699a9b5\",\n        \"7e5d8c12\",\n        \"53d0fd95\",\n        \"eea083fa\",\n        \"8e365f7f\",\n        \"876aebf3\",\n        \"4e8ede6c\",\n        \"ae5bce3d\",\n        \"4e891c05\",\n        \"9b5019f0\",\n        \"5165cd50\",\n        \"faec4b31\",\n        \"890b0975\",\n        \"c019b9d8\",\n        \"8c78e8e1\",\n        \"c2d6786c\",\n        \"f5f05a32\",\n        \"6dd3b324\",\n        \"ba53abf9\",\n        \"1f4770e5\",\n        \"da2048a0\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-the-use-of-promiseall/en-US.mdx",
    "content": "---\ntitle: What is the use of `Promise.all()`\n---\n\n## TL;DR\n\n`Promise.all()` is a method in JavaScript that takes an array of promises and returns a single promise. This returned promise resolves when all the input promises have resolved, or it rejects if any of the input promises reject. It is useful for running multiple asynchronous operations in parallel and waiting for all of them to complete.\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = 42;\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.all([promise1, promise2, promise3]).then((values) => {\n  console.log(values); // [3, 42, 'foo']\n});\n```\n\n---\n\n## What is the use of `Promise.all()`\n\n### Overview\n\n`Promise.all()` is a static method of the `Promise` object that is used to handle multiple promises concurrently. It takes an iterable (usually an array) of promises and returns a single promise that resolves when all the promises in the iterable have resolved or rejects if any of the promises reject.\n\n### Syntax\n\n```js\nPromise.all(iterable);\n```\n\n- `iterable`: An iterable object, such as an array, containing promises.\n\n### How it works\n\nWhen you pass an array of promises to `Promise.all()`, it returns a new promise. This new promise:\n\n- Resolves when all the promises in the array have resolved. The resolved value is an array of the resolved values of the input promises, in the same order as the input promises.\n- Rejects as soon as any of the input promises reject. The rejection reason is the reason of the first promise that rejects.\n\n### Example\n\nHere is an example to illustrate how `Promise.all()` works:\n\n```js live\nconst promise1 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'one');\n});\n\nconst promise2 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 200, 'two');\n});\n\nPromise.all([promise1, promise2])\n  .then((values) => {\n    console.log(values); // ['one', 'two']\n  })\n  .catch((error) => {\n    console.error(error);\n  });\n```\n\nIn this example, `Promise.all()` waits for both `promise1` and `promise2` to resolve. Once both promises have resolved, it logs the array of resolved values.\n\n### Error handling\n\nIf any of the promises passed to `Promise.all()` reject, the returned promise will immediately reject with the reason of the first promise that rejects.\n\n```js live\nconst promise1 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'one');\n});\n\nconst promise2 = new Promise((resolve, reject) => {\n  setTimeout(reject, 200, 'two');\n});\n\nPromise.all([promise1, promise2])\n  .then((values) => {\n    console.log(values);\n  })\n  .catch((error) => {\n    console.error(error); // 'two'\n  });\n```\n\nIn this example, `promise2` rejects after 200 milliseconds, causing the `Promise.all()` promise to reject immediately with the reason `'two'`.\n\n### Use cases\n\n- **Parallel API requests**: When you need to make multiple API requests and wait for all of them to complete before proceeding.\n- **Batch processing**: When you have multiple asynchronous tasks that can be executed in parallel and you need to wait for all of them to finish.\n- **Data aggregation**: When you need to gather data from multiple sources and combine the results.\n\n## Further reading\n\n- [MDN Web Docs on `Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)\n- [JavaScript Promises: An Introduction](https://developers.google.com/web/fundamentals/primers/promises)\n- [Understanding JavaScript Promises](https://www.digitalocean.com/community/tutorials/understanding-javascript-promises)\n"
  },
  {
    "path": "questions/what-is-the-use-of-promiseall/metadata.json",
    "content": "{\n  \"slug\": \"what-is-the-use-of-promiseall\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"featured\": false,\n  \"level\": \"basic\",\n  \"topics\": [\"async\", \"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\",\n  \"section\": \"Asynchronous JavaScript\"\n}\n"
  },
  {
    "path": "questions/what-is-the-use-of-promiseall/zh-CN.mdx",
    "content": "---\ntitle: Promise.all() 的用途是什么\n---\n\n## TL;DR\n\n`Promise.all()` 是 JavaScript 中的一种方法，它接受一个 promise 数组并返回一个单独的 promise。当所有输入 promise 都已解决时，此返回的 promise 将被解析，或者如果任何输入 promise 被拒绝，则会被拒绝。它用于并行运行多个异步操作并等待它们全部完成。\n\n```js live\nconst promise1 = Promise.resolve(3);\nconst promise2 = 42;\nconst promise3 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'foo');\n});\n\nPromise.all([promise1, promise2, promise3]).then((values) => {\n  console.log(values); // [3, 42, 'foo']\n});\n```\n\n***\n\n## Promise.all() 的用途是什么\n\n### 概述\n\n`Promise.all()` 是 `Promise` 对象的静态方法，用于同时处理多个 promise。它接受一个可迭代对象（通常是数组）的 promise，并返回一个单独的 promise，当可迭代对象中的所有 promise 都已解决时，该 promise 将被解析，或者如果任何 promise 被拒绝，则该 promise 将被拒绝。\n\n### 语法\n\n```js\nPromise.all(iterable);\n```\n\n* `iterable`：一个可迭代对象，例如包含 promise 的数组。\n\n### 工作原理\n\n当您将一个 promise 数组传递给 `Promise.all()` 时，它将返回一个新的 promise。这个新的 promise：\n\n* 当数组中的所有 promise 都已解决时，将解析。解析后的值是输入 promise 的解析值的数组，顺序与输入 promise 相同。\n* 一旦任何输入 promise 被拒绝，就会被拒绝。拒绝原因是被拒绝的第一个 promise 的原因。\n\n### 示例\n\n这是一个示例，用于说明 `Promise.all()` 的工作原理：\n\n```js live\nconst promise1 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'one');\n});\n\nconst promise2 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 200, 'two');\n});\n\nPromise.all([promise1, promise2])\n  .then((values) => {\n    console.log(values); // ['one', 'two']\n  })\n  .catch((error) => {\n    console.error(error);\n  });\n```\n\n在此示例中，`Promise.all()` 等待 `promise1` 和 `promise2` 都被解析。一旦两个 promise 都被解析，它将记录解析值的数组。\n\n### 错误处理\n\n如果传递给 `Promise.all()` 的任何 promise 被拒绝，则返回的 promise 将立即被拒绝，并带有第一个被拒绝的 promise 的原因。\n\n```js live\nconst promise1 = new Promise((resolve, reject) => {\n  setTimeout(resolve, 100, 'one');\n});\n\nconst promise2 = new Promise((resolve, reject) => {\n  setTimeout(reject, 200, 'two');\n});\n\nPromise.all([promise1, promise2])\n  .then((values) => {\n    console.log(values);\n  })\n  .catch((error) => {\n    console.error(error); // 'two'\n  });\n```\n\n在这个例子中，`promise2` 在 200 毫秒后被拒绝，导致 `Promise.all()` promise 立即以原因 `'two'` 拒绝。\n\n### 用例\n\n* **并行 API 请求**：当您需要发出多个 API 请求并等待所有请求完成才能继续时。\n* **批量处理**：当您有多个可以并行执行的异步任务，并且需要等待所有任务完成时。\n* **数据聚合**：当您需要从多个来源收集数据并合并结果时。\n\n## 延伸阅读\n\n* [MDN Web Docs 上的 `Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)\n* [JavaScript Promises：简介](https://developers.google.com/web/fundamentals/primers/promises)\n* [理解 JavaScript Promises](https://www.digitalocean.com/community/tutorials/understanding-javascript-promises)\n"
  },
  {
    "path": "questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"a48f539\",\n    \"subtitle\": \"fe0da86c\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"735518d\",\n        \"87deb665\",\n        \"a511962f\",\n        \"d37b5b85\",\n        \"e230eff7\",\n        \"9f0c4dc6\",\n        \"2a7816d0\",\n        \"31d334db\",\n        \"ee3a3042\",\n        \"8c6102dc\",\n        \"e42c6a99\",\n        \"b5e18e85\",\n        \"4771f3b4\",\n        \"735f0c5\",\n        \"70e92007\",\n        \"6cc87eda\",\n        \"483222a\",\n        \"c9bebce4\",\n        \"5b8e46fd\",\n        \"4f551e73\",\n        \"40808d83\",\n        \"444b3f4e\",\n        \"1f4770e5\",\n        \"57e46ad6\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"735518d\",\n        \"87deb665\",\n        \"a511962f\",\n        \"d37b5b85\",\n        \"e230eff7\",\n        \"9f0c4dc6\",\n        \"2a7816d0\",\n        \"31d334db\",\n        \"ee3a3042\",\n        \"8c6102dc\",\n        \"e42c6a99\",\n        \"b5e18e85\",\n        \"4771f3b4\",\n        \"735f0c5\",\n        \"70e92007\",\n        \"6cc87eda\",\n        \"483222a\",\n        \"c9bebce4\",\n        \"5b8e46fd\",\n        \"4f551e73\",\n        \"40808d83\",\n        \"444b3f4e\",\n        \"1f4770e5\",\n        \"57e46ad6\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/en-US.mdx",
    "content": "---\ntitle: What is `'use strict';` in JavaScript for?\nsubtitle: What are the advantages and disadvantages to using it?\n---\n\n## TL;DR\n\n`'use strict'` is a statement used to enable strict mode to entire scripts or individual functions. Strict mode is a way to opt into a restricted variant of JavaScript.\n\n**Advantages**\n\n- Makes it impossible to accidentally create global variables.\n- Makes assignments which would otherwise silently fail to throw an exception.\n- Makes attempts to delete undeletable properties throw an exception (where before the attempt would simply have no effect).\n- Requires that function parameter names be unique.\n- `this` is `undefined` in the global context.\n- It catches some common coding bloopers, throwing exceptions.\n- It disables features that are confusing or poorly thought out.\n\n**Disadvantages**\n\n- Many missing features that some developers might be used to.\n- No more access to `function.caller` and `function.arguments`.\n- Concatenation of scripts written in different strict modes might cause issues.\n\nOverall, the benefits outweigh the disadvantages and there is not really a need to rely on the features that strict mode prohibits. We should all be using strict mode by default.\n\n---\n\n## What is `\"use strict\"` in JavaScript?\n\nIn essence, `\"use strict\"` is a directive introduced in ECMAScript 5 (ES5) that signals to the JavaScript engine that the code it surrounds should be executed in \"strict mode\". Strict mode imposes stricter parsing and error handling rules, essentially making your code more secure and less error-prone.\n\nWhen you use \"use strict\", it helps you to write cleaner code, like preventing you from using undeclared variables. It can also make your code more secure because it disallows some potentially insecure actions.\n\n## How to use strict mode\n\n1. **Global Scope**: To enable strict mode globally, add the directive at the beginning of the JavaScript file:\n\n   ```js live\n   'use strict';\n   // any code in this file will be run in strict mode\n   function add(a, b) {\n     return a + b;\n   }\n   ```\n\n2. **Local Scope**: To enable strict mode within a function, add the directive at the beginning of the function:\n\n   ```js live\n   function myFunction() {\n     'use strict';\n     // this will tell JavaScript engine to use strict mode only for the `myFunction`\n     // Anything that is outside of the scope of this function will be treated as non-strict mode unless specified to use strict mode\n   }\n   ```\n\n## Key features of strict mode\n\n1. **Error prevention** : Strict mode prevents common errors such as:\n   - Using undeclared variables.\n   - Assigning values to non-writable properties.\n   - Using non-existent properties or variables.\n   - Deleting undeletable properties.\n   - Using reserved keywords as identifiers.\n   - Duplicating parameter names in functions.\n2. **Improved security**: Strict mode helps in writing more secure code by:\n   - Preventing the use of deprecated features like arguments.caller and arguments.callee.\n   - Restricting the use of eval() to prevent variable declarations in the calling scope.\n3. **Compatibility** : Strict mode ensures compatibility with future versions of JavaScript by preventing the use of reserved keywords as identifiers.\n\n### Examples\n\n1. Preventing accidental creation of global variables:\n\n   ```js live\n   // Without strict mode\n\n   function defineNumber() {\n     count = 123;\n   }\n   defineNumber();\n   console.log(count); // logs: 123\n   ```\n\n   ```js live\n   'use strict'; // With strict mode\n\n   function strictFunc() {\n     'use strict';\n     strictVar = 123; // ReferenceError: strictVar is not defined\n   }\n   strictFunc();\n   console.log(strictVar); // ReferenceError: strictVar is not defined\n   ```\n\n2. Making assignments which would otherwise silently fail to throw an exception:\n\n   ```js live\n   // Without strict mode\n   NaN = 'foo'; // This fails silently\n   console.log(NaN); // logs: NaN\n   ```\n\n   ```js live\n   'use strict'; // With strict mode\n   NaN = 'foo'; // Uncaught TypeError: Cannot assign to read only property 'NaN' of object '#<Window>'\n   ```\n\n3. Making attempts to delete undeletable properties throw an error in strict mode:\n\n   ```js live\n   // Without strict mode\n   delete Object.prototype; // This fails silently\n   ```\n\n   ```js live\n   'use strict'; // With strict mode\n   delete Object.prototype; // TypeError: Cannot delete property 'prototype' of function Object() { [native code] }\n   ```\n\n## Is it \"strictly\" necessary?\n\nAdding `'use strict'` in JavaScript is still beneficial and recommended, but it is no longer strictly necessary in all cases:\n\n1. **Modules**: The entire contents of JavaScript modules are automatically in strict mode, without needing the `'use strict'` statement. This applies to ES6 modules as well as Node.js CommonJS modules.\n2. **Classes**: Code within class definitions is also automatically in strict mode, even without `'use strict'`.\n\nWhile `'use strict'` is no longer mandatory in all contexts due to the automatic strict mode enforcement in modules and classes, it is still widely recommended as a best practice, especially for core JavaScript files, libraries, and when working with older browser environments or legacy code.\n\n### Notes\n\n1. **Placement**: The `'use strict'` directive must be placed at the beginning of the file or function. Placing it anywhere else will not have any effect.\n1. **Compatibility**: Strict mode is supported by all modern browsers except Internet Explorer 9 and lower.\n1. **Irreversible**: There is no way to cancel `'use strict'` after it's being set.\n\n## Further reading\n\n- [Strict mode - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)\n- [The modern mode, \"use strict\"](https://javascript.info/strict-mode)\n"
  },
  {
    "path": "questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/metadata.json",
    "content": "{\n  \"slug\": \"what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it\",\n  \"languages\": [],\n  \"companies\": [\"amazon\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 240,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/pt-BR.mdx",
    "content": "---\ntitle: O que é `\"use strict\";`?\nsubtitle: Quais são as vantagens e desvantagens de usa-lo?\n---\n\n`'use strict'` é uma declaração usada para habilitar o modo estrito em scripts inteiros ou funções individuais. O modo estrito é uma maneira de optar por uma variante restrita do JavaScript.\n\n## Vantagens\n\n- Faz com que seja impossível criar variáveis globais acidentalmente.\n- Faz com que as atribuições que falhariam silenciosamente disparem uma exceção.\n- Faz tentativas de excluir propriedades não deletáveis lançam uma exceção (onde antes da tentativa simplesmente não teria efeito).\n- Exige que os nomes dos parâmetros de função sejam exclusivos.\n- `this` é `undefined` no contexto global.\n- Ele captura alguns erros comuns de programação, lançando exceções.\n- Ele desabilita recursos que são confusos ou mal concebidos.\n\n## Desvantagens\n\n- Muitos recursos faltantes que alguns desenvolvedores podem estar acostumados.\n- Não há mais acesso a `function.caller` e `function.arguments`.\n- Concatenação de scripts escritos em diferentes modos estritos pode causar problemas.\n\nNo geral, os benefícios superam as desvantagens e não há realmente a necessidade de depender dos recursos que o modo estrito proíbe. Todos nós deveríamos estar usando o modo estrito por padrão.\n"
  },
  {
    "path": "questions/what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中的 `'use strict';` 是什么？\nsubtitle: 使用它有什么优点和缺点？\n---\n\n## TL;DR\n\n`'use strict'` 是一条语句，用于对整个脚本或单个函数启用严格模式。严格模式是一种选择加入 JavaScript 限制变体的方式。\n\n**优点**\n\n* 无法意外创建全局变量。\n* 使原本会静默失败的赋值抛出异常。\n* 使尝试删除不可删除的属性抛出异常（而之前尝试只会无效）。\n* 要求函数参数名称是唯一的。\n* `this` 在全局上下文中为 `undefined`。\n* 它可以捕获一些常见的编码错误，抛出异常。\n* 它禁用了令人困惑或考虑不周的功能。\n\n**缺点**\n\n* 许多开发人员可能习惯的缺失功能。\n* 无法再访问 `function.caller` 和 `function.arguments`。\n* 用不同严格模式编写的脚本的串联可能会导致问题。\n\n总的来说，优点大于缺点，而且实际上没有必要依赖严格模式禁止的功能。我们都应该默认使用严格模式。\n\n***\n\n## JavaScript 中的 `\"use strict\"` 是什么？\n\n本质上，`\"use strict\"` 是 ECMAScript 5 (ES5) 中引入的一个指令，它向 JavaScript 引擎发出信号，表明它所包围的代码应该在“严格模式”下执行。严格模式施加了更严格的解析和错误处理规则，从本质上使您的代码更安全，更不容易出错。\n\n当您使用“use strict”时，它有助于您编写更简洁的代码，例如阻止您使用未声明的变量。它还可以使您的代码更安全，因为它禁止某些潜在的不安全操作。\n\n## 如何使用严格模式\n\n1. **全局范围**：要在全局启用严格模式，请在 JavaScript 文件的开头添加指令：\n\n   ```js live\n   'use strict';\n   // 此文件中的任何代码都将在严格模式下运行\n   function add(a, b) {\n     return a + b;\n   }\n   ```\n\n2. **局部范围**：要在函数内启用严格模式，请在函数的开头添加指令：\n\n   ```js live\n   function myFunction() {\n     'use strict';\n     // 这将告诉 JavaScript 引擎仅对 `myFunction` 使用严格模式\n     // 任何超出此函数范围的内容都将被视为非严格模式，除非指定使用严格模式\n   }\n   ```\n\n## 严格模式的主要特点\n\n1. **错误预防**：严格模式可防止常见错误，例如：\n   * 使用未声明的变量。\n   * 将值分配给不可写属性。\n   * 使用不存在的属性或变量。\n   * 删除不可删除的属性。\n   * 将保留关键字用作标识符。\n   * 在函数中复制参数名称。\n2. **提高安全性**：严格模式通过以下方式帮助编写更安全的代码：\n   * 阻止使用已弃用的功能，如 arguments.caller 和 arguments.callee。\n   * 限制使用 eval() 以防止在调用范围内声明变量。\n3. **兼容性**：严格模式通过阻止将保留关键字用作标识符来确保与未来版本的 JavaScript 的兼容性。\n\n### 示例\n\n1. 防止意外创建全局变量：\n\n   ```js live\n   // 没有严格模式\n\n   function defineNumber() {\n     count = 123;\n   }\n   defineNumber();\n   console.log(count); // 日志：123\n   ```\n\n   ```js live\n   'use strict'; // 使用严格模式\n\n   function strictFunc() {\n     'use strict';\n     strictVar = 123; // ReferenceError: strictVar is not defined\n   }\n   strictFunc();\n   console.log(strictVar); // ReferenceError: strictVar is not defined\n   ```\n\n2. 使原本会静默失败的赋值抛出异常：\n\n   ```js live\n   // 没有严格模式\n   NaN = 'foo'; // 这会静默失败\n   console.log(NaN); // 日志：NaN\n   ```\n\n   ```js live\n   'use strict'; // 使用严格模式\n   NaN = 'foo'; // Uncaught TypeError: Cannot assign to read only property 'NaN' of object '#<Window>'\n   ```\n\n3. 使尝试删除不可删除的属性在严格模式下抛出错误：\n\n   ```js live\n   // 没有严格模式\n   delete Object.prototype; // 这会静默失败\n   ```\n\n   ```js live\n   'use strict'; // 使用严格模式\n   delete Object.prototype; // TypeError: Cannot delete property 'prototype' of function Object() { [native code] }\n   ```\n\n## 真的有必要吗？\n\n在 JavaScript 中添加 `'use strict'` 仍然是有益的，并且是推荐的，但在所有情况下不再严格需要：\n\n1. **模块**：JavaScript 模块的全部内容会自动进入严格模式，无需 `'use strict'` 语句。这适用于 ES6 模块以及 Node.js CommonJS 模块。\n2. **类**：类定义中的代码也会自动进入严格模式，即使没有 `'use strict'`。\n\n虽然由于模块和类中的自动严格模式强制执行，`'use strict'` 不再在所有上下文中是强制性的，但它仍然被广泛推荐作为最佳实践，尤其是在核心 JavaScript 文件、库以及使用较旧的浏览器环境或旧代码时。\n\n### 注意事项\n\n1. **放置**：`'use strict'` 指令必须放置在文件或函数的开头。将其放置在其他任何地方都不会有任何效果。\n2. **兼容性**：除了 Internet Explorer 9 及更低版本外，所有现代浏览器都支持严格模式。\n3. **不可逆**：设置 `'use strict'` 后，无法取消它。\n\n## 延伸阅读\n\n* [严格模式 - MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Strict_mode)\n* [现代模式，\"use strict\"](https://javascript.info/strict-mode)\n"
  },
  {
    "path": "questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"6974cfc5\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"54a52842\",\n        \"46a782c8\",\n        \"1808bf91\",\n        \"61782055\",\n        \"eaa3a244\",\n        \"9635527a\",\n        \"5581e95a\",\n        \"15c31f38\",\n        \"9e8e09c6\",\n        \"8c44c71\",\n        \"591dd6a\",\n        \"f0aba9df\",\n        \"149c3df7\",\n        \"ca5833ce\",\n        \"4f775901\",\n        \"7a95c522\",\n        \"8023e346\",\n        \"2a7816d0\",\n        \"10cbc85f\",\n        \"e3924c2e\",\n        \"2aa37a6\",\n        \"7e71d639\",\n        \"273d5f60\",\n        \"98dc827f\",\n        \"424503ca\",\n        \"5d48d3e7\",\n        \"483d351d\",\n        \"9b3a39e8\",\n        \"b16b67a8\",\n        \"3d8d5e3c\",\n        \"dec59727\",\n        \"651727d0\",\n        \"a9f51aeb\",\n        \"ddb0f727\",\n        \"5f38e7de\",\n        \"f55a485\",\n        \"d554a30f\",\n        \"67f15da1\",\n        \"3f40b693\",\n        \"7f0da9d8\",\n        \"af58902a\",\n        \"f6fc9f53\",\n        \"64fc870\",\n        \"e9d547db\",\n        \"5fb6b66b\",\n        \"1bc04577\",\n        \"d3c7063b\",\n        \"2c6f377c\",\n        \"ccb6db0b\",\n        \"1f4770e5\",\n        \"705d5f5b\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"54a52842\",\n        \"46a782c8\",\n        \"1808bf91\",\n        \"61782055\",\n        \"eaa3a244\",\n        \"9635527a\",\n        \"5581e95a\",\n        \"15c31f38\",\n        \"9e8e09c6\",\n        \"8c44c71\",\n        \"591dd6a\",\n        \"f0aba9df\",\n        \"149c3df7\",\n        \"ca5833ce\",\n        \"4f775901\",\n        \"7a95c522\",\n        \"8023e346\",\n        \"2a7816d0\",\n        \"10cbc85f\",\n        \"e3924c2e\",\n        \"2aa37a6\",\n        \"7e71d639\",\n        \"273d5f60\",\n        \"98dc827f\",\n        \"424503ca\",\n        \"5d48d3e7\",\n        \"483d351d\",\n        \"9b3a39e8\",\n        \"b16b67a8\",\n        \"3d8d5e3c\",\n        \"dec59727\",\n        \"651727d0\",\n        \"a9f51aeb\",\n        \"ddb0f727\",\n        \"5f38e7de\",\n        \"f55a485\",\n        \"d554a30f\",\n        \"67f15da1\",\n        \"3f40b693\",\n        \"7f0da9d8\",\n        \"af58902a\",\n        \"f6fc9f53\",\n        \"64fc870\",\n        \"e9d547db\",\n        \"5fb6b66b\",\n        \"1bc04577\",\n        \"d3c7063b\",\n        \"2c6f377c\",\n        \"ccb6db0b\",\n        \"1f4770e5\",\n        \"705d5f5b\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/en-US.mdx",
    "content": "---\ntitle: What language constructs do you use for iterating over object properties and array items in JavaScript?\n---\n\n## TL;DR\n\nThere are multiple ways to iterate over object properties as well as arrays in JavaScript:\n\n**`for...in` loop**\n\nThe `for...in` loop iterates over all enumerable properties of an object, including inherited enumerable properties. So it is important to have a check if you only want to iterate over object's own properties\n\n```js live\nconst obj = {\n  a: 1,\n  b: 2,\n  c: 3,\n};\n\nfor (const key in obj) {\n  // To avoid iterating over inherited properties\n  if (Object.hasOwn(obj, key)) {\n    console.log(`${key}: ${obj[key]}`);\n  }\n}\n```\n\n**`Object.keys()`**\n\n`Object.keys()` returns an array of the object's own enumerable property names. You can then use a for...of loop or forEach to iterate over this array.\n\n```js live\nconst obj = {\n  a: 1,\n  b: 2,\n  c: 3,\n};\n\nObject.keys(obj).forEach((key) => {\n  console.log(`${key}: ${obj[key]}`);\n});\n```\n\nMost common ways to iterate over array are using `for` loop and `Array.prototype.forEach` method.\n\n**Using `for` loop**\n\n```js live\nlet array = [1, 2, 3, 4, 5, 6];\nfor (let index = 0; index < array.length; index++) {\n  console.log(array[index]);\n}\n```\n\n**Using `Array.prototype.forEach` method**\n\n```js live\nlet array = [1, 2, 3, 4, 5, 6];\narray.forEach((number, index) => {\n  console.log(`${number} at index ${index}`);\n});\n```\n\n**Using `for...of`**\n\nThis method is the newest and most convenient way to iterate over arrays. It automatically iterates over each element without requiring you to manage the index.\n\n```js live\nconst numbers = [1, 2, 3, 4, 5];\n\nfor (const number of numbers) {\n  console.log(number);\n}\n```\n\nThere are also other inbuilt methods available which are suitable for specific scenarios for example:\n\n- `Array.prototype.filter`: You can use the `filter` method to create a new array containing only the elements that satisfy a certain condition.\n- `Array.prototype.map`: You can use the `map` method to create a new array based on the existing one, transforming each element with a provided function.\n- `Array.prototype.reduce`: You can use the `reduce` method to combine all elements into a single value by repeatedly calling a function that takes two arguments: the accumulated value and the current element.\n\n---\n\n## Iterating over objects\n\nIterating over object properties and array is very common in JavaScript and we have various ways to achieve this. Here are some of the ways to do it:\n\n### `for...in` statement\n\nThis loop iterates over all **enumerable** properties of an object, including those inherited from its prototype chain.\n\n```js live\nconst obj = {\n  status: 'working',\n  hoursWorked: 3,\n};\n\nfor (const property in obj) {\n  console.log(property);\n}\n```\n\nSince `for...in` statement iterates over all the object's **enumerable** properties (including inherited enumerable properties). Hence most of the time you should check whether the property exists on directly on the object via `Object.hasOwn(object, property)` before using it.\n\n```js live\nconst obj = {\n  status: 'working',\n  hoursWorked: 3,\n};\n\nfor (const property in obj) {\n  if (Object.hasOwn(obj, property)) {\n    console.log(property);\n  }\n}\n```\n\nNote that `obj.hasOwnProperty()` is not recommended because it doesn't work for objects created using `Object.create(null)`. It is recommended to use [`Object.hasOwn()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn) in newer browsers, or use the good old `Object.prototype.hasOwnProperty.call(object, key)`.\n\n### `Object.keys()`\n\n`Object.keys()` is a static method that will return an array of all the enumerable property names of the object that you pass it. Since `Object.keys()` returns an array, you can also use the array iteration approaches listed below to iterate through it.\n\n```js live\nconst obj = {\n  status: 'working',\n  hoursWorked: 3,\n};\n\nObject.keys(obj).forEach((property) => {\n  console.log(property);\n});\n```\n\n### `Object.entries()`:\n\nThis method returns an array of an object's enumerable properties in `[key, value]` pairs.\n\n```js live\nconst obj = { a: 1, b: 2, c: 3 };\nObject.entries(obj).forEach(([key, value]) => {\n  console.log(`${key}: ${value}`);\n});\n```\n\n### `Object.getOwnPropertyNames()`\n\n```js live\nconst obj = { a: 1, b: 2, c: 3 };\nObject.getOwnPropertyNames(obj).forEach((property) => {\n  console.log(property);\n});\n```\n\n`Object.getOwnPropertyNames()` is a static method that will lists all enumerable and non-enumerable properties of the object that you pass it. Since `Object.getOwnPropertyNames()` returns an array, you can also use the array iteration approaches listed below to iterate through it.\n\n## Arrays\n\n### `for` loop\n\n```js live\nconst arr = [1, 2, 3, 4, 5];\nfor (var i = 0; i < arr.length; i++) {\n  console.log(arr[i]);\n}\n```\n\nA common pitfall here is that `var` is in the function scope and not the block scope and most of the time you would want block scoped iterator variable. ES2015 introduces `let` which has block scope and it is recommended to use `let` over `var`.\n\n```js live\nconst arr = [1, 2, 3, 4, 5];\nfor (let i = 0; i < arr.length; i++) {\n  console.log(arr[i]);\n}\n```\n\n### `Array.prototype.forEach()`\n\n```js live\nconst arr = [1, 2, 3, 4, 5];\narr.forEach((element, index) => {\n  console.log(`${element} at index ${index}`);\n});\n```\n\nThe `Array.prototype.forEach()` method can be more convenient at times if you do not need to use the `index` and all you need is the individual array elements. However, the downside is that you cannot stop the iteration halfway and the provided function will be executed on the elements once. A `for` loop or `for...of` statement is more relevant if you need finer control over the iteration.\n\n### `for...of` statement\n\n```js live\nconst arr = [1, 2, 3, 4, 5];\nfor (let element of arr) {\n  console.log(element);\n}\n```\n\nES2015 introduces a new way to iterate, the `for-of` loop, that allows you to loop over objects that conform to the [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) such as `String`, `Array`, `Map`, `Set`, etc. It combines the advantages of the `for` loop and the `forEach()` method. The advantage of the `for` loop is that you can break from it, and the advantage of `forEach()` is that it is more concise than the `for` loop because you don't need a counter variable. With the `for...of` statement, you get both the ability to break from a loop and a more concise syntax.\n\nMost of the time, prefer the `.forEach` method, but it really depends on what you are trying to do. Before ES2015, we used `for` loops when we needed to prematurely terminate the loop using `break`. But now with ES2015, we can do that with `for...of` statement. Use `for` loops when you need more flexibility, such as incrementing the iterator more than once per loop.\n\nAlso, when using the `for...of` statement, if you need to access both the index and value of each array element, you can do so with ES2015 `Array.prototype.entries()` method:\n\n```js live\nconst arr = ['a', 'b', 'c'];\n\nfor (let [index, elem] of arr.entries()) {\n  console.log(index, elem);\n}\n```\n\n## Further reading\n\n- [Object.getOwnPropertyNames() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames)\n- [Object.keys() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)\n- [for...of - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n- [Array.prototype.forEach() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)\n"
  },
  {
    "path": "questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/metadata.json",
    "content": "{\n  \"slug\": \"what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 360,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/pt-BR.mdx",
    "content": "---\ntitle: Que construções de idioma você usa para iterar sobre propriedades de objeto e itens de matriz?\n---\n\n## Objetos\n\n### declaração `for...in`\n\n```js\nfor (const property in obj) {\n  console.log(property);\n}\n```\n\nA declaração `for...in` itera sobre todas as propriedades **enumeráveis** do objeto (incluindo as propriedades enumeráveis herdadas). Portanto, na maioria das vezes, você deve verificar se a propriedade existe diretamente no objeto por meio de `Object.hasOwn(object, property)` antes de usá-la.\n\n```js\nfor (const property in obj) {\n  if (Object.hasOwn(obj, property)) {\n    console.log(property);\n  }\n}\n```\n\nObserve que `obj.hasOwnProperty()` não é recomendado porque não funciona para objetos criados usando `Object.create(null)`. É recomendado usar [`Object.hasOwn()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn) nos navegadores mais recentes, ou use o bom `Object.prototype.hasOwnProperty.call(object, key)`.\n\n### `Object.keys()`\n\n```js\nObject.keys(obj).forEach((property) => {\n  console.log(property);\n});\n```\n\n`Object.keys()` é um método estático que retornará um array com todos os nomes de propriedade enumerados do objeto que você passa. Uma vez que `Object.keys()` retorna um array, você também pode usar as abordagens de iteração de matriz listadas abaixo para iterar através dele.\n\n_Referência: [Object.keys() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)_\n\n### `Object.getOwnPropertyNames()`\n\n```js\nObject.getOwnPropertyNames(obj).forEach((property) => {\n  console.log(property);\n});\n```\n\n`Object.getOwnPropertyNames()` é um método estático que listará todas as propriedades enumeradas e não-enumeráveis do objeto que você passou. Uma vez que `Object.getOwnPropertyNames()` retorna uma matriz, você também pode usar as abordagens de iteração de matriz listadas abaixo para percorrer a matriz.\n\n_Referência: [Object.keys() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames)_\n\n## Arrays\n\n### `for` loop\n\n```js\nfor (let i = 0; i < arr.length; i++) {\n  console.log(arr[i]);\n}\n```\n\nUma armadilha comum aqui é que `var` está no escopo da função e não no escopo de bloco, e na maioria das vezes você desejará uma variável de iterador com escopo de bloco. ES2015 introduz o `let` que tem escopo de bloco e é recomendado usar `let` em vez de `var`.\n\n```js\nfor (let i = 0; i < arr.length; i++) {\n  console.log(arr[i]);\n}\n```\n\n### `Array.prototype.forEach()`\n\n```js\narr.forEach((element, index) => {\n  console.log(element, index);\n});\n```\n\nO método `Array.prototype.forEach()` pode ser mais conveniente em algumas situações se você não precisar usar o índice e só precisar dos elementos individuais do array. No entanto, o lado negativo é que não se pode parar a iteração a meio do caminho e a função fornecida será executada uma vez nos elementos. Um laço `for` ou uma declaração `for...of` são mais relevantes quando é necessário um controle mais preciso sobre a iteração.\n\n_Referência: [Object.keys() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)_\n\n### declaração `for...of`\n\n```js\nfor (let element of arr) {\n  console.log(element);\n}\n```\n\nES2015 introduz uma nova forma de iterar, o laço `para`, que permite repetir o loop sobre objetos que estejam em conformidade com o [protocolo iterável](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) como `String`, `Array`, `Set`, etc. Ele combina as vantagens do loop `for` e do método `forEach()`. A vantagem do laço `para` é que você pode parar dele, e a vantagem de `forEach()` é que ele é mais conciso que o laço `for` porque você não precisa de uma variável contadora. Com a declaração `for...of`, você obtém a capacidade de quebrar de um laço e uma sintaxe mais concisa.\n\nA maioria das vezes, prefira o método `.forEach`, mas realmente depende do que você está tentando fazer. Antes do ES2015, usamos laços `for` quando precisávamos encerrar prematuramente o laço usando `break`. Mas agora com ES2015, podemos fazer isso com a declaração `for...of`. Use laços `for` quando você precisar de mais flexibilidade, como incrementar o iterador mais de uma vez por laço.\n\nAlém disso, ao usar o `for...of` declaração, se você precisar acessar o índice e o valor de cada elemento de matriz, você pode fazer isso com ES2015 `Array.prototype.entries()`:\n\n```js\nconst arr = ['a', 'b', 'c'];\n\nfor (let [index, elem] of arr.entries()) {\n  console.log(index, ': ', elem);\n}\n```\n\n_Referência: [for...of - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)_\n"
  },
  {
    "path": "questions/what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中使用什么语言结构来迭代对象属性和数组项？\n---\n\n## TL;DR\n\n在 JavaScript 中，有多种方法可以迭代对象属性和数组：\n\n**`for...in` 循环**\n\n`for...in` 循环遍历对象的所有可枚举属性，包括继承的可枚举属性。因此，如果您只想遍历对象的自有属性，进行检查非常重要\n\n```js live\nconst obj = {\n  a: 1,\n  b: 2,\n  c: 3,\n};\n\nfor (const key in obj) {\n  // To avoid iterating over inherited properties\n  if (Object.hasOwn(obj, key)) {\n    console.log(`${key}: ${obj[key]}`);\n  }\n}\n```\n\n**`Object.keys()`**\n\n`Object.keys()` 返回一个由对象自身的可枚举属性名称组成的数组。然后，您可以使用 for...of 循环或 forEach 遍历此数组。\n\n```js live\nconst obj = {\n  a: 1,\n  b: 2,\n  c: 3,\n};\n\nObject.keys(obj).forEach((key) => {\n  console.log(`${key}: ${obj[key]}`);\n});\n```\n\n迭代数组最常见的方法是使用 `for` 循环和 `Array.prototype.forEach` 方法。\n\n**使用 `for` 循环**\n\n```js live\nlet array = [1, 2, 3, 4, 5, 6];\nfor (let index = 0; index < array.length; index++) {\n  console.log(array[index]);\n}\n```\n\n**使用 `Array.prototype.forEach` 方法**\n\n```js live\nlet array = [1, 2, 3, 4, 5, 6];\narray.forEach((number, index) => {\n  console.log(`${number} at index ${index}`);\n});\n```\n\n**使用 `for...of`**\n\n此方法是迭代数组的最新和最方便的方法。它会自动迭代每个元素，而无需您管理索引。\n\n```js live\nconst numbers = [1, 2, 3, 4, 5];\n\nfor (const number of numbers) {\n  console.log(number);\n}\n```\n\n还有其他可用的内置方法，适用于特定场景，例如：\n\n* `Array.prototype.filter`：您可以使用 `filter` 方法创建一个新数组，其中仅包含满足特定条件的元素。\n* `Array.prototype.map`：您可以使用 `map` 方法基于现有数组创建一个新数组，并使用提供的函数转换每个元素。\n* `Array.prototype.reduce`：您可以使用 `reduce` 方法通过重复调用一个接受两个参数的函数（累积值和当前元素）将所有元素组合成一个值。\n\n***\n\n## 遍历对象\n\n在 JavaScript 中，遍历对象属性和数组非常常见，我们有多种方法可以实现这一点。以下是实现此目的的一些方法：\n\n### `for...in` 语句\n\n此循环遍历对象的所有**可枚举**属性，包括从其原型链继承的属性。\n\n```js live\nconst obj = {\n  status: 'working',\n  hoursWorked: 3,\n};\n\nfor (const property in obj) {\n  console.log(property);\n}\n```\n\n由于 `for...in` 语句遍历对象的所有**可枚举**属性（包括继承的可枚举属性）。因此，大多数情况下，在使用属性之前，您应该通过 `Object.hasOwn(object, property)` 检查该属性是否存在于对象上。\n\n```js live\nconst obj = {\n  status: 'working',\n  hoursWorked: 3,\n};\n\nfor (const property in obj) {\n  if (Object.hasOwn(obj, property)) {\n    console.log(property);\n  }\n}\n```\n\n请注意，不推荐使用 `obj.hasOwnProperty()`，因为它不适用于使用 `Object.create(null)` 创建的对象。建议在较新的浏览器中使用 [`Object.hasOwn()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn)，或者使用旧的 `Object.prototype.hasOwnProperty.call(object, key)`。\n\n### `Object.keys()`\n\n`Object.keys()` 是一种静态方法，它将返回您传递给它的对象的所有可枚举属性名称的数组。由于 `Object.keys()` 返回一个数组，您也可以使用下面列出的数组迭代方法来遍历它。\n\n```js live\nconst obj = {\n  status: 'working',\n  hoursWorked: 3,\n};\n\nObject.keys(obj).forEach((property) => {\n  console.log(property);\n});\n```\n\n### `Object.entries()`:\n\n此方法返回一个对象的可枚举属性的数组，以 `[key, value]` 对的形式。\n\n```js live\nconst obj = { a: 1, b: 2, c: 3 };\nObject.entries(obj).forEach(([key, value]) => {\n  console.log(`${key}: ${value}`);\n});\n```\n\n### `Object.getOwnPropertyNames()`\n\n```js live\nconst obj = { a: 1, b: 2, c: 3 };\nObject.getOwnPropertyNames(obj).forEach((property) => {\n  console.log(property);\n});\n```\n\n`Object.getOwnPropertyNames()` 是一种静态方法，它将列出您传递给它的对象的所有可枚举和不可枚举属性。由于 `Object.getOwnPropertyNames()` 返回一个数组，您也可以使用下面列出的数组迭代方法来遍历它。\n\n## 数组\n\n### `for` 循环\n\n```js live\nconst arr = [1, 2, 3, 4, 5];\nfor (var i = 0; i < arr.length; i++) {\n  console.log(arr[i]);\n}\n```\n\n这里一个常见的陷阱是 `var` 在函数作用域中，而不是块作用域中，并且大多数情况下您希望使用块作用域迭代器变量。 ES2015 引入了具有块作用域的 `let`，建议使用 `let` 而不是 `var`。\n\n```js live\nconst arr = [1, 2, 3, 4, 5];\nfor (let i = 0; i < arr.length; i++) {\n  console.log(arr[i]);\n}\n```\n\n### `Array.prototype.forEach()`\n\n```js live\nconst arr = [1, 2, 3, 4, 5];\narr.forEach((element, index) => {\n  console.log(`${element} at index ${index}`);\n});\n```\n\n`Array.prototype.forEach()` 方法有时会更方便，如果您不需要使用 `index`，而您只需要单个数组元素。 但是，缺点是您无法中途停止迭代，并且提供的函数将在元素上执行一次。 如果您需要更好地控制迭代，`for` 循环或 `for...of` 语句会更相关。\n\n### `for...of` 语句\n\n```js live\nconst arr = [1, 2, 3, 4, 5];\nfor (let element of arr) {\n  console.log(element);\n}\n```\n\nES2015 引入了一种新的迭代方式，即 `for-of` 循环，它允许您循环访问符合 [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) 的对象，例如 `String`、`Array`、`Map`、`Set` 等。 它结合了 `for` 循环和 `forEach()` 方法的优点。 `for` 循环的优点是您可以从中跳出，而 `forEach()` 的优点是它比 `for` 循环更简洁，因为您不需要计数器变量。 使用 `for...of` 语句，您可以同时获得跳出循环的能力和更简洁的语法。\n\n大多数情况下，更喜欢 `.forEach` 方法，但这确实取决于您要执行的操作。 在 ES2015 之前，当我们需要使用 `break` 提前终止循环时，我们使用 `for` 循环。 但现在有了 ES2015，我们可以使用 `for...of` 语句来做到这一点。 当您需要更大的灵活性时，例如每次循环递增迭代器一次以上时，请使用 `for` 循环。\n\n此外，在使用 `for...of` 语句时，如果您需要访问每个数组元素的索引和值，您可以使用 ES2015 `Array.prototype.entries()` 方法来实现：\n\n```js live\nconst arr = ['a', 'b', 'c'];\n\nfor (let [index, elem] of arr.entries()) {\n  console.log(index, elem);\n}\n```\n\n## 延伸阅读\n\n* [Object.getOwnPropertyNames() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames)\n* [Object.keys() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)\n* [for...of - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n* [Array.prototype.forEach() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)\n"
  },
  {
    "path": "questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"d9917568\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"d12ec8da\",\n        \"a498436f\",\n        \"2a7816d0\",\n        \"56d71ab6\",\n        \"eec4d8ed\",\n        \"6b616982\",\n        \"b6c09aeb\",\n        \"1c71c8cb\",\n        \"df8bf3dd\",\n        \"3dec99f0\",\n        \"7d3c403a\",\n        \"f647b995\",\n        \"fc53cfa0\",\n        \"72d375b6\",\n        \"95972e9\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"d12ec8da\",\n        \"a498436f\",\n        \"2a7816d0\",\n        \"56d71ab6\",\n        \"eec4d8ed\",\n        \"6b616982\",\n        \"b6c09aeb\",\n        \"1c71c8cb\",\n        \"df8bf3dd\",\n        \"3dec99f0\",\n        \"7d3c403a\",\n        \"f647b995\",\n        \"fc53cfa0\",\n        \"72d375b6\",\n        \"95972e9\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/en-US.mdx",
    "content": "---\ntitle: What tools and techniques do you use for debugging JavaScript code?\n---\n\n## TL;DR\n\nSome of the most commonly used tools and techniques for debugging JavaScript:\n\n- JavaScript language\n  - `console` methods (e.g. `console.log()`, `console.error()`, `console.warn()`, `console.table()`)\n  - `debugger` statement\n- Breakpoints (browser or IDE)\n- JavaScript frameworks\n  - [React Devtools](https://github.com/facebook/react-devtools)\n  - [Redux Devtools](https://github.com/gaearon/redux-devtools)\n  - [Vue Devtools](https://github.com/vuejs/vue-devtools)\n- Browser developer tools\n  - **Chrome DevTools**: The most widely used tool for debugging JavaScript. It provides a rich set of features including the ability to set breakpoints, inspect variables, view the call stack, and more.\n  - **Firefox Developer Tools**: Similar to Chrome DevTools with its own set of features for debugging.\n  - **Safari Web Inspector**: Provides tools for debugging on Safari.\n  - **Edge Developer Tools**: Similar to Chrome DevTools, as Edge is now Chromium-based.\n- Network requests\n  - **Postman**: Useful for debugging API calls.\n  - **Fiddler**: Helps capture and inspect HTTP/HTTPS traffic.\n  - **Charles Proxy**: Another tool for intercepting and debugging network calls.\n\n---\n\n## Debugging JavaScript\n\nHere are common tools and techniques developers frequently use for debugging JavaScript code.\n\n### `console` methods\n\n- `console.log()`: The most basic way to inspect values, variables, and data structures at various points in your code.\n- `console.error()`: Outputs errors to the console, often with more detailed stack traces.\n- `console.warn()`: Displays warnings.\n- `console.table()`: Formats data (especially arrays of objects) in a readable table.\n- `console.time()` and `console.timeEnd()`: Measure the execution time of code blocks.\n\n### `debugger` statement\n\n- Pauses code execution at the line where `debugger;` is placed.\n- Allows you to step through code line by line, inspect variables, and understand the flow of execution.\n\n### Breakpoints\n\n- Set breakpoints directly in the Sources panel of your browser's developer tools or IDE (e.g. VS Code) to pause execution at specific lines of code without modifying your source code.\n\n### Network tab\n\n- Monitor network requests made by your JavaScript code (e.g., AJAX calls, fetching data).\n- Inspect request headers, responses, timing, and identify potential issues.\n\n### Performance tab\n\n- Profile your JavaScript code to identify performance bottlenecks.\n- Analyze CPU usage, memory allocation, and rendering times.\n"
  },
  {
    "path": "questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/metadata.json",
    "content": "{\n  \"slug\": \"what-tools-and-techniques-do-you-use-for-debugging-javascript-code\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"low\",\n  \"ranking\": 480,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/pt-BR.mdx",
    "content": "---\ntitle: Quais ferramentas e técnicas você usa para depurar o código JavaScript?\n---\n\n- JavaScript\n  - [Chrome Devtools](https://hackernoon.com/twelve-fancy-chrome-devtools-tips-dc1e39d10d9d)\n  - declaração `debugger`\n  - Depuração tradicional com `console.log()`\n- React e Redux\n  - [React Devtools](https://github.com/facebook/react-devtools)\n  - [Redux Devtools](https://github.com/gaearon/redux-devtools)\n- Vue\n  - [Vue Devtools](https://github.com/vuejs/vue-devtools)\n"
  },
  {
    "path": "questions/what-tools-and-techniques-do-you-use-for-debugging-javascript-code/zh-CN.mdx",
    "content": "---\ntitle: 你使用什么工具和技术来调试 JavaScript 代码？\n---\n\n## TL;DR\n\n一些最常用的调试 JavaScript 的工具和技术：\n\n* JavaScript 语言\n  * `console` 方法（例如 `console.log()`、`console.error()`、`console.warn()`、`console.table()`）\n  * `debugger` 语句\n* 断点（浏览器或 IDE）\n* JavaScript 框架\n  * [React Devtools](https://github.com/facebook/react-devtools)\n  * [Redux Devtools](https://github.com/gaearon/redux-devtools)\n  * [Vue Devtools](https://github.com/vuejs/vue-devtools)\n* 浏览器开发者工具\n  * **Chrome DevTools**：用于调试 JavaScript 的最广泛使用的工具。它提供了一套丰富的功能，包括设置断点、检查变量、查看调用堆栈等。\n  * **Firefox Developer Tools**：类似于 Chrome DevTools，具有自己的一套调试功能。\n  * **Safari Web Inspector**：提供用于在 Safari 上调试的工具。\n  * **Edge Developer Tools**：类似于 Chrome DevTools，因为 Edge 现在基于 Chromium。\n* 网络请求\n  * **Postman**：用于调试 API 调用的工具。\n  * **Fiddler**：帮助捕获和检查 HTTP/HTTPS 流量。\n  * **Charles Proxy**：另一个用于拦截和调试网络调用的工具。\n\n***\n\n## 调试 JavaScript\n\n以下是开发人员经常用于调试 JavaScript 代码的常用工具和技术。\n\n### `console` 方法\n\n* `console.log()`：在代码的各个点检查值、变量和数据结构的最基本方法。\n* `console.error()`：将错误输出到控制台，通常带有更详细的堆栈跟踪。\n* `console.warn()`：显示警告。\n* `console.table()`：以可读的表格格式显示数据（尤其是对象数组）。\n* `console.time()` 和 `console.timeEnd()`：测量代码块的执行时间。\n\n### `debugger` 语句\n\n* 在放置 `debugger;` 的行处暂停代码执行。\n* 允许您逐行单步执行代码、检查变量并了解执行流程。\n\n### 断点\n\n* 直接在浏览器开发者工具或 IDE（例如 VS Code）的“Sources”面板中设置断点，以在特定代码行处暂停执行，而无需修改源代码。\n\n### 网络选项卡\n\n* 监视 JavaScript 代码发出的网络请求（例如，AJAX 调用、获取数据）。\n* 检查请求标头、响应、计时并识别潜在问题。\n\n### 性能选项卡\n\n* 分析 JavaScript 代码以识别性能瓶颈。\n* 分析 CPU 使用率、内存分配和渲染时间。\n"
  },
  {
    "path": "questions/whats-a-typical-use-case-for-anonymous-functions/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"d748b60f\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"fcc123f4\",\n        \"f90dc81c\",\n        \"bf26a694\",\n        \"c1e1429e\",\n        \"2a7816d0\",\n        \"d6943a58\",\n        \"7e85fba5\",\n        \"dc42f778\",\n        \"6ac67ae2\",\n        \"379d9005\",\n        \"f63b97b0\",\n        \"7ff2671\",\n        \"6bc9b91e\",\n        \"4c7d0a8e\",\n        \"7ecc9a9d\",\n        \"823f400e\",\n        \"b3d2d2d8\",\n        \"51cfcd8f\",\n        \"f21e775b\",\n        \"7d2e4e7\",\n        \"ebd53803\",\n        \"f3f051bb\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"fcc123f4\",\n        \"f90dc81c\",\n        \"bf26a694\",\n        \"c1e1429e\",\n        \"2a7816d0\",\n        \"d6943a58\",\n        \"7e85fba5\",\n        \"dc42f778\",\n        \"6ac67ae2\",\n        \"379d9005\",\n        \"f63b97b0\",\n        \"7ff2671\",\n        \"6bc9b91e\",\n        \"4c7d0a8e\",\n        \"7ecc9a9d\",\n        \"823f400e\",\n        \"b3d2d2d8\",\n        \"51cfcd8f\",\n        \"f21e775b\",\n        \"7d2e4e7\",\n        \"ebd53803\",\n        \"f3f051bb\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/whats-a-typical-use-case-for-anonymous-functions/en-US.mdx",
    "content": "---\ntitle: What's a typical use case for anonymous functions in JavaScript?\n---\n\n## TL;DR\n\nAnonymous function in Javascript is a function that does not have any name associated with it. They are typically used as arguments to other functions or assigned to variables.\n\n```js live\nconst arr = [-1, 0, 5, 6];\n\n// The filter method is passed an anonymous function.\narr.filter((x) => x > 1); // [5, 6]\n```\n\nThey are often used as arguments to other functions, known as higher-order functions, which can take functions as input and return a function as output. Anonymous functions can access variables from the outer scope, a concept known as closures, allowing them to \"close over\" and remember the environment in which they were created.\n\n```js live\n// Encapsulating Code\n(function () {\n  // Some code here.\n})();\n\n// Callbacks\nsetTimeout(function () {\n  console.log('Hello world!');\n}, 1000);\n\n// Functional programming constructs\nconst arr = [1, 2, 3];\nconst double = arr.map(function (el) {\n  return el * 2;\n});\nconsole.log(double); // [2, 4, 6]\n```\n\n---\n\n## Anonymous functions\n\nAnonymous functions provide a more concise way to define functions, especially for simple operations or callbacks. Besides that, they can also be used in the following scenarios\n\n### Immediate execution\n\nAnonymous functions are commonly used in Immediately Invoked Function Expressions (IIFEs) to encapsulate code within a local scope. This prevents variables declared within the function from leaking to the global scope and polluting the global namespace.\n\n```js live\n// This is an IIFE\n(function () {\n  var x = 10;\n  console.log(x); // 10\n})();\n\n// x is not accessible here\nconsole.log(typeof x); // undefined\n```\n\nIn the above example, the IIFE creates a local scope for the variable `x`. As a result, `x` is not accessible outside the IIFE, thus preventing it from leaking into the global scope.\n\n### Callbacks\n\nAnonymous functions can be used as callbacks that are used once and do not need to be used anywhere else. The code will seem more self-contained and readable when handlers are defined right inside the code calling them, rather than having to search elsewhere to find the function body.\n\n```js live\nsetTimeout(() => {\n  console.log('Hello world!');\n}, 1000);\n```\n\n### Higher-order functions\n\nIt is used as arguments to functional programming constructs like Higher-order functions or Lodash (similar to callbacks). Higher-order functions take other functions as arguments or return them as results. Anonymous functions are often used with higher-order functions like `map()`, `filter()`, and `reduce()`.\n\n```js live\nconst arr = [1, 2, 3];\nconst double = arr.map((el) => {\n  return el * 2;\n});\nconsole.log(double); // [2, 4, 6]\n```\n\n### Event Handling\n\nIn React, anonymous functions are widely used for defining callback functions inline for handling events and passing callbacks as props.\n\n```jsx\nfunction App() {\n  return <button onClick={() => console.log('Clicked!')}>Click Me</button>;\n}\n```\n\n## Follow-Up Questions\n\n- How do anonymous functions differ from named functions?\n- Can you explain the difference between arrow functions and anonymous functions?\n"
  },
  {
    "path": "questions/whats-a-typical-use-case-for-anonymous-functions/metadata.json",
    "content": "{\n  \"slug\": \"whats-a-typical-use-case-for-anonymous-functions\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 160,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/whats-a-typical-use-case-for-anonymous-functions/pt-BR.mdx",
    "content": "---\ntitle: Qual é um caso típico de uso para funções anônimas?\n---\n\nEles podem ser usados em IIFEs (funções autoexecutáveis) para encapsular algum código dentro de um escopo local, para que as variáveis declaradas nele não vazem para o escopo global.\n\n```js\n(function () {\n  // Algum código aqui.\n})();\n```\n\nComo uma função de callback que é usada apenas uma vez e não precisa ser usada em nenhum outro lugar. O código parecerá mais autônomo e legível quando os manipuladores forem definidos dentro do próprio código que os chama, em vez de ter que procurar em outro lugar para encontrar o corpo da função.\n\n```js\nsetTimeout(function () {\n  console.log('Olá mundo!');\n}, 1000);\n```\n\nArgumentos para construtos de programação funcional ou Lodash (semelhantes a funções de retorno de chamada).\n\n```js\nconst arr = [1, 2, 3];\nconst double = arr.ap(function (el) {\n  return el * 2;\n});\nconsole.log(double); // [2, 4, 6]\n```\n"
  },
  {
    "path": "questions/whats-a-typical-use-case-for-anonymous-functions/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中匿名函数的典型用例是什么？\n---\n\n## TL;DR\n\nJavascript 中的匿名函数是指没有关联名称的函数。它们通常用作其他函数的参数或分配给变量。\n\n```js live\nconst arr = [-1, 0, 5, 6];\n\n// The filter method is passed an anonymous function.\narr.filter((x) => x > 1); // [5, 6]\n```\n\n它们通常用作其他函数的参数，这些函数被称为高阶函数，可以接受函数作为输入并返回函数作为输出。匿名函数可以访问来自外部作用域的变量，这个概念被称为闭包，允许它们“封闭”并记住创建它们的环境。\n\n```js live\n// Encapsulating Code\n(function () {\n  // Some code here.\n})();\n\n// Callbacks\nsetTimeout(function () {\n  console.log('Hello world!');\n}, 1000);\n\n// Functional programming constructs\nconst arr = [1, 2, 3];\nconst double = arr.map(function (el) {\n  return el * 2;\n});\nconsole.log(double); // [2, 4, 6]\n```\n\n***\n\n## 匿名函数\n\n匿名函数提供了一种更简洁的定义函数的方式，尤其适用于简单操作或回调。除此之外，它们还可以用于以下场景\n\n### 立即执行\n\n匿名函数通常用于立即调用函数表达式 (IIFE)，以将代码封装在局部作用域内。这可以防止在函数内声明的变量泄漏到全局作用域并污染全局命名空间。\n\n```js live\n// This is an IIFE\n(function () {\n  var x = 10;\n  console.log(x); // 10\n})();\n\n// x is not accessible here\nconsole.log(typeof x); // undefined\n```\n\n在上面的例子中，IIFE 为变量 `x` 创建了一个局部作用域。因此，`x` 无法在 IIFE 之外访问，从而防止其泄漏到全局作用域。\n\n### 回调\n\n匿名函数可以用作仅使用一次且不需要在其他任何地方使用的回调。当处理程序在调用它们的代码内部定义时，代码看起来会更自包含且更具可读性，而不是必须在其他地方搜索以找到函数体。\n\n```js live\nsetTimeout(() => {\n  console.log('Hello world!');\n}, 1000);\n```\n\n### 高阶函数\n\n它用作函数式编程构造（如高阶函数或 Lodash（类似于回调））的参数。高阶函数将其他函数作为参数或将它们作为结果返回。匿名函数通常与高阶函数（如 `map()`、`filter()` 和 `reduce()`）一起使用。\n\n```js live\nconst arr = [1, 2, 3];\nconst double = arr.map((el) => {\n  return el * 2;\n});\nconsole.log(double); // [2, 4, 6]\n```\n\n### 事件处理\n\n在 React 中，匿名函数被广泛用于定义内联回调函数，用于处理事件和将回调作为 props 传递。\n\n```jsx\nfunction App() {\n  return <button onClick={() => console.log('Clicked!')}>Click Me</button>;\n}\n```\n\n## 后续问题\n\n* 你能解释一下箭头函数和匿名函数的区别吗？\n"
  },
  {
    "path": "questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"10679d6\",\n    \"subtitle\": \"192121c2\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"8c35b927\",\n        \"2a7816d0\",\n        \"c6cae930\",\n        \"f06bfc79\",\n        \"b5f04e40\",\n        \"39c5da5a\",\n        \"4bff8a9f\",\n        \"778e52ef\",\n        \"6ea7c6b9\",\n        \"c8cfa87c\",\n        \"21dc7444\",\n        \"524e9e1c\",\n        \"139d4408\",\n        \"add698fb\",\n        \"b8a4ccbb\",\n        \"45da4e57\",\n        \"7cb058d1\",\n        \"ee9c1eea\",\n        \"66c731e\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"8c35b927\",\n        \"2a7816d0\",\n        \"c6cae930\",\n        \"f06bfc79\",\n        \"b5f04e40\",\n        \"39c5da5a\",\n        \"4bff8a9f\",\n        \"778e52ef\",\n        \"6ea7c6b9\",\n        \"c8cfa87c\",\n        \"21dc7444\",\n        \"524e9e1c\",\n        \"139d4408\",\n        \"add698fb\",\n        \"b8a4ccbb\",\n        \"45da4e57\",\n        \"7cb058d1\",\n        \"ee9c1eea\",\n        \"66c731e\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/en-US.mdx",
    "content": "---\ntitle: \"What's the difference between a JavaScript variable that is: `null`, `undefined` or undeclared?\"\nsubtitle: How would you go about checking for any of these states?\n---\n\n## TL;DR\n\n| Trait | `null` | `undefined` | Undeclared |\n| --- | --- | --- | --- |\n| Meaning | Explicitly set by the developer to indicate that a variable has no value | Variable has been declared but not assigned a value | Variable has not been declared at all |\n| Type (via `typeof` operator) | `'object'` | `'undefined'` | `'undefined'` |\n| Equality Comparison | `null == undefined` is `true` | `undefined == null` is `true` | Throws a `ReferenceError` |\n\n---\n\n## Undeclared\n\n**Undeclared** variables are created when you assign a value to an identifier that is not previously created using `var`, `let` or `const`. Undeclared variables will be defined globally, outside of the current scope. In strict mode, a `ReferenceError` will be thrown when you try to assign to an undeclared variable. Undeclared variables are bad in the same way that global variables are bad. Avoid them at all cost! To check for them, wrap its usage in a `try`/`catch` block.\n\n```js live\nfunction foo() {\n  x = 1; // Throws a ReferenceError in strict mode\n}\n\nfoo();\nconsole.log(x); // 1 (if not in strict mode)\n```\n\nUsing the `typeof` operator on undeclared variables will give `'undefined'`.\n\n```js live\nconsole.log(typeof y === 'undefined'); // true\n```\n\n## `undefined`\n\nA variable that is `undefined` is a variable that has been declared, but not assigned a value. It is of type `undefined`. If a function does not return a value, and its result is assigned to a variable, that variable will also have the value `undefined`. To check for it, compare using the strict equality (`===`) operator or `typeof` which will give the `'undefined'` string. Note that you should not be using the loose equality operator (`==`) to check, as it will also return `true` if the value is `null`.\n\n```js live\nlet foo;\nconsole.log(foo); // undefined\nconsole.log(foo === undefined); // true\nconsole.log(typeof foo === 'undefined'); // true\n\nconsole.log(foo == null); // true. Wrong, don't use this to check if a value is undefined!\n\nfunction bar() {} // Returns undefined if there is nothing returned.\nlet baz = bar();\nconsole.log(baz); // undefined\n```\n\n## `null`\n\nA variable that is `null` will have been explicitly assigned to the `null` value. It represents no value and is different from `undefined` in the sense that it has been explicitly assigned. To check for `null,` simply compare using the strict equality operator. Note that like the above, you should not be using the loose equality operator (`==`) to check, as it will also return `true` if the value is `undefined`.\n\n```js live\nconst foo = null;\nconsole.log(foo === null); // true\nconsole.log(typeof foo === 'object'); // true\n\nconsole.log(foo == undefined); // true. Wrong, don't use this to check if a value is null!\n```\n\n## Notes\n\n- As a good habit, never leave your variables undeclared or unassigned. Explicitly assign `null` to them after declaring if you don't intend to use them yet.\n- Always explicitly declare variables before using them to prevent errors.\n- Using some static analysis tooling in your workflow (e.g. [ESLint](https://eslint.org/), TypeScript Compiler), will enable checks that you are not referencing undeclared variables.\n\n## Practice\n\nPractice implementing [type utilities that check for `null` and `undefined`](https://www.greatfrontend.com/questions/javascript/type-utilities?fpr=yangshun) on GreatFrontEnd.\n\n## Further Reading\n\n- [MDN Web Docs: null](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/null)\n- [MDN Web Docs: undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)\n- [MDN Web Docs: ReferenceError](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError)\n"
  },
  {
    "path": "questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/metadata.json",
    "content": "{\n  \"slug\": \"whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 90,\n  \"difficulty\": \"easy\"\n}\n"
  },
  {
    "path": "questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/pt-BR.mdx",
    "content": "---\ntitle: 'Qual é a diferença entre uma variável que é: `null`, `undefined` ou não declarada?'\nsubtitle: Como você checaria cada um destes estados?\"\n---\n\nVariáveis **não declaradas** são criadas quando você atribui um valor a um identificador que não foi criado anteriormente usando var, let ou const. Variáveis não declaradas serão definidas globalmente, fora do escopo atual. No modo estrito, um `ReferenceError` será lançado quando você tentar atribuir a uma variável não declarada. Variáveis não declaradas são ruins assim como as variáveis globais são ruins. Evite elas a todo custo! Para verificá-las, envolva o uso delas em um bloco `try/catch`.\n\n```js\nfunction foo() {\n  x = 1; // Lança um erro de referência em modo strict\n}\n\nfoo();\nconsole.log(x); // 1\n```\n\nUma variável que é `undefined` é uma variável que foi declarada, mas não atribuída um valor. É do tipo 'undefined'. Se uma função não retornar nenhum valor como resultado de sua execução, e se for atribuída a uma variável, a variável também terá o valor de `undefined`. Para verificar isso, compare usando o operador de igualdade estrita (`===`) ou `typeof`, que retornará a string `undefined`. Note que você não deve usar o operador de igualdade abstrata para verificar, pois também retornará `true` se o valor for `null`.\n\n```js\nvar foo;\nconsole.log(foo); // undefined\nconsole.log(foo === undefined); // true\nconsole.log(typeof foo === 'undefined'); // true\n\nconsole.log(foo == null); // verdadeiro. Errado, não use isso para verificar!\n\nfunction bar() {}\nvar baz = bar();\nconsole.log(baz); // undefined\n```\n\nUma variável que é `null` terá sido explicitamente atribuída ao valor `null`. Ele não representa nenhum valor e é diferente de `undefined` no sentido de que foi explicitamente atribuído. Para verificar se é `null,` simplesmente compare usando o operador de igualdade estrita. Observe que, assim como acima, você não deve usar o operador de igualdade abstrata (`==`) para verificar, pois também retornará `true` se o valor for `undefined`.\n\n```js\nvar foo = null;\nconsole.log(foo === null); // verdadeiro\nconsole.log(typeof foo === 'object'); // verdadeiro\n\nconsole.log(foo == undefined); // true. Errado, não use isto para verificar!\n```\n\nComo bom hábito, nunca deixe suas variáveis não declaradas ou não atribuídas. Atribua explicitamente `null` a elas depois de declará-las, se você não pretende usá-las ainda. Se você usa alguma ferramenta de análise estática em seu fluxo de trabalho (por exemplo, ESLint, TypeScript Compiler), geralmente ela também pode verificar se você está referenciando variáveis não declaradas.\n"
  },
  {
    "path": "questions/whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 变量 `null`、`undefined` 和未声明的区别是什么？\nsubtitle: 如何检查这些状态？\n---\n\n## TL;DR\n\n| 特性 | `null` | `undefined` | 未声明 |\n| --- | --- | --- | --- |\n| 含义 | 由开发人员显式设置，表示变量没有值 | 变量已声明但未赋值 | 变量根本未声明 |\n| 类型（通过 `typeof` 运算符） | `'object'` | `'undefined'` | `'undefined'` |\n| 等式比较 | `null == undefined` 为 `true` | `undefined == null` 为 `true` | 抛出 `ReferenceError` |\n\n***\n\n## 未声明\n\n**未声明** 变量是在您将值分配给先前未使用 `var`、`let` 或 `const` 创建的标识符时创建的。未声明的变量将在全局范围内定义，在当前范围之外。在严格模式下，当您尝试分配给未声明的变量时，将抛出 `ReferenceError`。未声明的变量和全局变量一样糟糕。不惜一切代价避免它们！要检查它们，请将其用法包装在 `try`/`catch` 块中。\n\n```js live\nfunction foo() {\n  x = 1; // 在严格模式下抛出 ReferenceError\n}\n\nfoo();\nconsole.log(x); // 1 (如果不在严格模式下)\n```\n\n对未声明的变量使用 `typeof` 运算符将给出 `'undefined'`。\n\n```js live\nconsole.log(typeof y === 'undefined'); // true\n```\n\n## `undefined`\n\n一个`undefined`的变量是已声明但未赋值的变量。它的类型是`undefined`。如果一个函数没有返回值，并且它的结果被分配给一个变量，那么该变量也将具有`undefined`值。要检查它，请使用严格相等运算符（`===`）或`typeof`进行比较，这将给出`'undefined'`字符串。请注意，您不应该使用宽松相等运算符（`==`）进行检查，因为它在值为`null`时也会返回`true`。\n\n```js live\nlet foo;\nconsole.log(foo); // undefined\nconsole.log(foo === undefined); // true\nconsole.log(typeof foo === 'undefined'); // true\n\nconsole.log(foo == null); // true. 错误，不要使用它来检查一个值是否为 undefined!\n\nfunction bar() {} // 如果没有任何返回，则返回 undefined。\nlet baz = bar();\nconsole.log(baz); // undefined\n```\n\n## `null`\n\n一个 `null` 的变量将被显式地赋值为 `null` 值。它表示没有值，并且与 `undefined` 的不同之处在于它已被显式赋值。要检查 `null`，只需使用严格相等运算符进行比较。请注意，与上述类似，您不应该使用松散相等运算符 (`==`) 进行检查，因为它在值为 `undefined` 时也会返回 `true`。\n\n```js live\nconst foo = null;\nconsole.log(foo === null); // true\nconsole.log(typeof foo === 'object'); // true\n\nconsole.log(foo == undefined); // true. 错误，不要使用它来检查一个值是否为 null!\n```\n\n## 注意事项\n\n* 养成一个好习惯，永远不要让你的变量未声明或未赋值。如果您不打算使用它们，在声明后显式地将 `null` 赋值给它们。\n* 始终在变量使用前显式声明它们以防止错误。\n* 在您的工作流程中使用一些静态分析工具（例如 [ESLint](https://eslint.org/)、TypeScript 编译器），将启用您未引用未声明变量的检查。\n\n## 实践\n\n在 GreatFrontEnd 上练习实现 [检查 `null` 和 `undefined` 的类型实用程序](https://www.greatfrontend.com/questions/javascript/type-utilities?fpr=yangshun)。\n\n## 延伸阅读\n\n* [MDN Web 文档：null](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/null)\n* [MDN Web 文档：undefined](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/undefined)\n* [MDN Web 文档：ReferenceError](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError)\n"
  },
  {
    "path": "questions/whats-the-difference-between-an-attribute-and-a-property/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"d07c950f\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"6eb4cf3b\",\n        \"2a7816d0\",\n        \"62039457\",\n        \"e290a7f5\",\n        \"406bf1ac\",\n        \"748ffe75\",\n        \"d537b631\",\n        \"e232568f\",\n        \"cdb066d8\",\n        \"c507b595\",\n        \"748ffe75\",\n        \"39e0d5ed\",\n        \"584d5660\",\n        \"67423e0a\",\n        \"a5795553\",\n        \"748ffe75\",\n        \"719fed3a\",\n        \"3dd8e583\",\n        \"ff3acc5\",\n        \"1f4770e5\",\n        \"3f468a42\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"6eb4cf3b\",\n        \"2a7816d0\",\n        \"62039457\",\n        \"e290a7f5\",\n        \"406bf1ac\",\n        \"748ffe75\",\n        \"d537b631\",\n        \"e232568f\",\n        \"cdb066d8\",\n        \"c507b595\",\n        \"748ffe75\",\n        \"39e0d5ed\",\n        \"584d5660\",\n        \"67423e0a\",\n        \"a5795553\",\n        \"748ffe75\",\n        \"719fed3a\",\n        \"3dd8e583\",\n        \"ff3acc5\",\n        \"1f4770e5\",\n        \"3f468a42\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/whats-the-difference-between-an-attribute-and-a-property/en-US.mdx",
    "content": "---\ntitle: What's the difference between an \"attribute\" and a \"property\" in the DOM?\n---\n\n## TL;DR\n\nAttributes are defined in the HTML and provide initial values for properties. Properties are part of the DOM and represent the current state of an element. For example, the `value` attribute of an `<input>` element sets its initial value, while the `value` property reflects the current value as the user interacts with it.\n\n---\n\n## Difference between an \"attribute\" and a \"property\" in the DOM\n\n### Attributes\n\nAttributes are defined in the HTML markup and provide initial values for elements. They are static and do not change once the page is loaded unless explicitly modified using JavaScript.\n\n#### Example\n\n```html\n<input type=\"text\" value=\"initial value\" />\n```\n\nIn this example, `value=\"initial value\"` is an attribute.\n\n### Properties\n\nProperties are part of the DOM and represent the current state of an element. They are dynamic and can change as the user interacts with the page or through JavaScript.\n\n#### Example\n\n```javascript\nconst inputElement = document.querySelector('input');\nconsole.log(inputElement.value); // Logs the current value of the input element\ninputElement.value = 'new value'; // Changes the current value of the input element\n```\n\nIn this example, `value` is a property of the `inputElement` object.\n\n### Key differences\n\n- **Initialization**: Attributes initialize DOM properties.\n- **State**: Attributes are static, while properties are dynamic.\n- **Access**: Attributes can be accessed using `getAttribute` and `setAttribute` methods, while properties can be accessed directly on the DOM object.\n\n#### Example\n\n```html\n<input id=\"myInput\" type=\"text\" value=\"initial value\" />\n```\n\n```javascript\nconst inputElement = document.getElementById('myInput');\n\n// Accessing attribute\nconsole.log(inputElement.getAttribute('value')); // \"initial value\"\n\n// Accessing property\nconsole.log(inputElement.value); // \"initial value\"\n\n// Changing property\ninputElement.value = 'new value';\nconsole.log(inputElement.value); // \"new value\"\nconsole.log(inputElement.getAttribute('value')); // \"initial value\"\n```\n\nIn this example, changing the `value` property does not affect the `value` attribute.\n\n## Further reading\n\n- [MDN Web Docs: Element.getAttribute()](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute)\n- [MDN Web Docs: Element.setAttribute()](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute)\n- [MDN Web Docs: HTML attributes vs. DOM properties](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#html_attributes_vs_dom_properties)\n"
  },
  {
    "path": "questions/whats-the-difference-between-an-attribute-and-a-property/metadata.json",
    "content": "{\n  \"slug\": \"whats-the-difference-between-an-attribute-and-a-property\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": false,\n  \"topics\": [\"web-api\", \"javascript\", \"html\"],\n  \"importance\": \"medium\",\n  \"ranking\": 999,\n  \"difficulty\": \"easy\"\n}\n"
  },
  {
    "path": "questions/whats-the-difference-between-an-attribute-and-a-property/pt-BR.mdx",
    "content": "---\ntitle: Qual é a diferença entre um \"atributo\" e uma \"propriedade\"?\n---\n\nAtributos são definidos na marcação HTML, mas as propriedades são definidas no DOM. Para ilustrar a diferença, imagine que temos esse campo de texto em nosso HTML: `<input type=\"text\" value=\"Hello\">`.\n\n```js\nconst input = document.querySelector('input');\nconsole.log(input.getAttribute('value')); // Olá\nconsole.log(input.value); // Olá\n```\n\nMas depois de alterar o valor do campo de texto adicionando \"Mundo!\" a ele, isso se torna:\n\n```js\nconsole.log(input.getAttribute('value')); // Olá\nconsole.log(input.value); // Olá Mundo!\n```\n"
  },
  {
    "path": "questions/whats-the-difference-between-an-attribute-and-a-property/zh-CN.mdx",
    "content": "---\ntitle: DOM 中“attribute”和“property”有什么区别？\n---\n\n## TL;DR\n\nAttributes 在 HTML 中定义，为属性提供初始值。属性是 DOM 的一部分，表示元素的当前状态。例如，`<input>` 元素的 `value` 属性设置其初始值，而 `value` 属性反映用户与之交互时的当前值。\n\n***\n\n## DOM 中“attribute”和“property”有什么区别\n\n### Attributes\n\nAttributes 在 HTML 标记中定义，为元素提供初始值。它们是静态的，一旦页面加载后就不会改变，除非使用 JavaScript 显式修改。\n\n#### 示例\n\n```html\n<input type=\"text\" value=\"initial value\" />\n```\n\n在此示例中，`value=\"initial value\"` 是一个 attribute。\n\n### Properties\n\nProperties 是 DOM 的一部分，表示元素的当前状态。它们是动态的，可以随着用户与页面交互或通过 JavaScript 而改变。\n\n#### 示例\n\n```javascript\nconst inputElement = document.querySelector('input');\nconsole.log(inputElement.value); // 记录输入元素的当前值\ninputElement.value = 'new value'; // 更改输入元素的当前值\n```\n\n在此示例中，`value` 是 `inputElement` 对象的属性。\n\n### 关键区别\n\n* **初始化**：Attributes 初始化 DOM 属性。\n* **状态**：Attributes 是静态的，而属性是动态的。\n* **访问**：可以使用 `getAttribute` 和 `setAttribute` 方法访问 Attributes，而可以直接在 DOM 对象上访问属性。\n\n#### 示例\n\n```html\n<input id=\"myInput\" type=\"text\" value=\"initial value\" />\n```\n\n```javascript\nconst inputElement = document.getElementById('myInput');\n\n// 访问 attribute\nconsole.log(inputElement.getAttribute('value')); // \"initial value\"\n\n// 访问 property\nconsole.log(inputElement.value); // \"initial value\"\n\n// 更改 property\ninputElement.value = 'new value';\nconsole.log(inputElement.value); // \"new value\"\nconsole.log(inputElement.getAttribute('value')); // \"initial value\"\n```\n\n在此示例中，更改 `value` 属性不会影响 `value` attribute。\n\n## 延伸阅读\n\n* [MDN Web 文档：Element.getAttribute()](https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getAttribute)\n* [MDN Web 文档：Element.setAttribute()](https://developer.mozilla.org/zh-CN/docs/Web/API/Element/setAttribute)\n* [MDN Web 文档：HTML 属性与 DOM 属性](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Attributes#html_attributes_vs_dom_properties)\n"
  },
  {
    "path": "questions/whats-the-difference-between-call-and-apply/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"bcea1662\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"dea192c\",\n        \"7dd15469\",\n        \"8f205c71\",\n        \"4e7671c3\",\n        \"2a7816d0\",\n        \"3c2f5705\",\n        \"a4d8526c\",\n        \"fbc30aaa\",\n        \"4e7671c3\",\n        \"60a757ae\",\n        \"4616869d\",\n        \"c81ac723\",\n        \"10c2d5c6\",\n        \"407e6940\",\n        \"5ca3e2c3\",\n        \"a668cef3\",\n        \"33ae0ea0\",\n        \"e82cfe4\",\n        \"37d72bcb\",\n        \"c46e5768\",\n        \"6e51c84c\",\n        \"97cae6df\",\n        \"4dd0a15b\",\n        \"883bd926\",\n        \"ebd53803\",\n        \"e8a456cd\",\n        \"45da4e57\",\n        \"df14f9a5\",\n        \"ee9c1eea\",\n        \"692eb18f\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"dea192c\",\n        \"7dd15469\",\n        \"8f205c71\",\n        \"4e7671c3\",\n        \"2a7816d0\",\n        \"3c2f5705\",\n        \"a4d8526c\",\n        \"fbc30aaa\",\n        \"4e7671c3\",\n        \"60a757ae\",\n        \"4616869d\",\n        \"c81ac723\",\n        \"10c2d5c6\",\n        \"407e6940\",\n        \"5ca3e2c3\",\n        \"a668cef3\",\n        \"33ae0ea0\",\n        \"e82cfe4\",\n        \"37d72bcb\",\n        \"c46e5768\",\n        \"6e51c84c\",\n        \"97cae6df\",\n        \"4dd0a15b\",\n        \"883bd926\",\n        \"ebd53803\",\n        \"e8a456cd\",\n        \"45da4e57\",\n        \"df14f9a5\",\n        \"ee9c1eea\",\n        \"692eb18f\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/whats-the-difference-between-call-and-apply/en-US.mdx",
    "content": "---\ntitle: What's the difference between `.call` and `.apply` in JavaScript?\n---\n\n## TL;DR\n\n`.call` and `.apply` are both used to invoke functions with a specific `this` context and arguments. The primary difference lies in how they accept arguments:\n\n- `.call(thisArg, arg1, arg2, ...)`: Takes arguments individually.\n- `.apply(thisArg, [argsArray])`: Takes arguments as an array.\n\nAssuming we have a function `add`, the function can be invoked using `.call` and `.apply` in the following manner:\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconsole.log(add.call(null, 1, 2)); // 3\nconsole.log(add.apply(null, [1, 2])); // 3\n```\n\n---\n\n## Call vs Apply\n\nBoth `.call` and `.apply` are used to invoke functions and the first parameter will be used as the value of `this` within the function. However, `.call` takes in comma-separated arguments as the next arguments while `.apply` takes in an array of arguments as the next argument.\n\nAn easy way to remember this is C for `call` and comma-separated and A for `apply` and an array of arguments.\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconsole.log(add.call(null, 1, 2)); // 3\nconsole.log(add.apply(null, [1, 2])); // 3\n```\n\nWith ES6 syntax, we can invoke `call` using an array along with the spread operator for the arguments.\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconsole.log(add.call(null, ...[1, 2])); // 3\n```\n\n## Use cases\n\n### Context management\n\n`.call` and `.apply` can set the `this` context explicitly when invoking methods on different objects.\n\n```js live\nconst person = {\n  name: 'John',\n  greet() {\n    console.log(`Hello, my name is ${this.name}`);\n  },\n};\n\nconst anotherPerson = { name: 'Alice' };\n\nperson.greet.call(anotherPerson); // Hello, my name is Alice\nperson.greet.apply(anotherPerson); // Hello, my name is Alice\n```\n\n### Function borrowing\n\nBoth `.call` and `.apply` allow borrowing methods from one object and using them in the context of another. This is useful when passing functions as arguments (callbacks) and the original `this` context is lost. `.call` and `.apply` allow the function to be invoked with the intended `this` value.\n\n```js live\nfunction greet() {\n  console.log(`Hello, my name is ${this.name}`);\n}\n\nconst person1 = { name: 'John' };\nconst person2 = { name: 'Alice' };\n\ngreet.call(person1); // Hello, my name is John\ngreet.apply(person2); // Hello, my name is Alice\n```\n\n### Alternative syntax to call methods on objects\n\n`.apply` can be used with object methods by passing the object as the first argument followed by the usual parameters.\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\n\nArray.prototype.push.apply(arr1, arr2); // Same as arr1.push(4, 5, 6)\n\nconsole.log(arr1); // [1, 2, 3, 4, 5, 6]\n```\n\nDeconstructing the above:\n\n1. The first object, `arr1` will be used as the `this` value.\n2. `.push()` is called on `arr1` using `arr2` as arguments as an array because it's using `.apply()`.\n3. `Array.prototype.push.apply(arr1, arr2)` is equivalent to `arr1.push(...arr2)`.\n\nIt may not be obvious, but `Array.prototype.push.apply(arr1, arr2)` causes modifications to `arr1`. It's clearer to call methods using the OOP-centric way instead where possible.\n\n## Follow-Up Questions\n\n- How do `.call` and `.apply` differ from `Function.prototype.bind`?\n\n## Practice\n\nPractice implementing your own [`Function.prototype.call` method](/questions/javascript/function-call) and [`Function.prototype.apply` method](/questions/javascript/function-apply) on GreatFrontEnd.\n\n## Further Reading\n\n- [Function.prototype.call | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call)\n- [Function.prototype.apply | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply)\n"
  },
  {
    "path": "questions/whats-the-difference-between-call-and-apply/metadata.json",
    "content": "{\n  \"slug\": \"whats-the-difference-between-call-and-apply\",\n  \"languages\": [],\n  \"companies\": [\"atlassian\"],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"basic\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"high\",\n  \"ranking\": 100,\n  \"difficulty\": \"easy\"\n}\n"
  },
  {
    "path": "questions/whats-the-difference-between-call-and-apply/pt-BR.mdx",
    "content": "---\ntitle: Qual é a diferença entre `.call` e `.apply`?\n---\n\n`.call` e `.apply` são usados para invocar funções e o primeiro parâmetro será usado como o valor de `this` dentro da função. No entanto, `.call` recebe argumentos separados por vírgulas como os próximos argumentos enquanto `.apply` recebe um array de argumentos como o próximo argumento. Uma maneira fácil de lembrar este é C para `chamada` e parâmetros separados por vírgulas e A para 'apply' e um array de argumentos.\n\n```js\nfunction add(a, b) {\n  return a + b;\n}\n\nconsole.log(add.call(null, 1, 2)); // 3\nconsole.log(add.apply(null, [1, 2])); // 3\n```\n"
  },
  {
    "path": "questions/whats-the-difference-between-call-and-apply/zh-CN.mdx",
    "content": "---\ntitle: JavaScript 中`.call` 和 `.apply` 有什么区别？\n---\n\n## TL;DR\n\n`.call` 和 `.apply` 都用于使用特定的 `this` 上下文和参数来调用函数。主要区别在于它们接受参数的方式：\n\n* `.call(thisArg, arg1, arg2, ...)`：单独获取参数。\n* `.apply(thisArg, [argsArray])`：将参数作为数组获取。\n\n假设我们有一个函数 `add`，可以使用以下方式使用 `.call` 和 `.apply` 调用该函数：\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconsole.log(add.call(null, 1, 2)); // 3\nconsole.log(add.apply(null, [1, 2])); // 3\n```\n\n***\n\n## Call vs Apply\n\n`.call` 和 `.apply` 都用于调用函数，第一个参数将用作函数中 `this` 的值。但是，`.call` 将逗号分隔的参数作为下一个参数，而 `.apply` 将参数数组作为下一个参数。\n\n记住这一点的一个简单方法是 C 代表 `call` 和逗号分隔，A 代表 `apply` 和参数数组。\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconsole.log(add.call(null, 1, 2)); // 3\nconsole.log(add.apply(null, [1, 2])); // 3\n```\n\n使用 ES6 语法，我们可以使用数组以及用于参数的扩展运算符来调用 `call`。\n\n```js live\nfunction add(a, b) {\n  return a + b;\n}\n\nconsole.log(add.call(null, ...[1, 2])); // 3\n```\n\n## 用例\n\n### 上下文管理\n\n`.call` 和 `.apply` 可以在调用不同对象上的方法时显式设置 `this` 上下文。\n\n```js live\nconst person = {\n  name: 'John',\n  greet() {\n    console.log(`Hello, my name is ${this.name}`);\n  },\n};\n\nconst anotherPerson = { name: 'Alice' };\n\nperson.greet.call(anotherPerson); // Hello, my name is Alice\nperson.greet.apply(anotherPerson); // Hello, my name is Alice\n```\n\n### 函数借用\n\n`.call` 和 `.apply` 都允许从一个对象借用方法并在另一个对象的上下文中使它们。当将函数作为参数（回调）传递并且原始 `this` 上下文丢失时，这很有用。`.call` 和 `.apply` 允许使用预期的 `this` 值调用该函数。\n\n```js live\nfunction greet() {\n  console.log(`Hello, my name is ${this.name}`);\n}\n\nconst person1 = { name: 'John' };\nconst person2 = { name: 'Alice' };\n\ngreet.call(person1); // Hello, my name is John\ngreet.apply(person2); // Hello, my name is Alice\n```\n\n### 调用对象方法的替代语法\n\n`.apply` 可以通过将对象作为第一个参数传递，然后传递通常的参数来与对象方法一起使用。\n\n```js live\nconst arr1 = [1, 2, 3];\nconst arr2 = [4, 5, 6];\n\nArray.prototype.push.apply(arr1, arr2); // Same as arr1.push(4, 5, 6)\n\nconsole.log(arr1); // [1, 2, 3, 4, 5, 6]\n```\n\n分解上述内容：\n\n1. 第一个对象 `arr1` 将用作 `this` 值。\n2. 在 `arr1` 上调用 `.push()`，使用 `arr2` 作为参数数组，因为它使用 `.apply()`。\n3. `Array.prototype.push.apply(arr1, arr2)` 等同于 `arr1.push(...arr2)`。\n\n可能并不明显，但 `Array.prototype.push.apply(arr1, arr2)` 会导致修改 `arr1`。如果可能，使用面向 OOP 的方式调用方法会更清晰。\n\n## 后续问题\n\n* `.call` 和 `.apply` 与 `Function.prototype.bind` 有什么不同？\n\n## 实践\n\n在 GreatFrontEnd 上实践实现你自己的 [`Function.prototype.call` 方法](/questions/javascript/function-call) 和 [`Function.prototype.apply` 方法](/questions/javascript/function-apply)。\n\n## 延伸阅读\n\n* [Function.prototype.call | MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call)\n* [Function.prototype.apply | MDN](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply)\n"
  },
  {
    "path": "questions/when-would-you-use-document-write/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"203bd99f\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"313058cf\",\n        \"2a7816d0\",\n        \"23571c3b\",\n        \"b4a97c71\",\n        \"9dade4a6\",\n        \"ad56e8e9\",\n        \"d994ea66\",\n        \"38bcc14d\",\n        \"f227c95f\",\n        \"2a7b55d3\",\n        \"75a13951\",\n        \"614d066a\",\n        \"26261459\",\n        \"879c06d9\",\n        \"105817f6\",\n        \"99fd8806\",\n        \"1f4770e5\",\n        \"fd2e97ad\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"313058cf\",\n        \"2a7816d0\",\n        \"23571c3b\",\n        \"b4a97c71\",\n        \"9dade4a6\",\n        \"ad56e8e9\",\n        \"d994ea66\",\n        \"38bcc14d\",\n        \"f227c95f\",\n        \"2a7b55d3\",\n        \"75a13951\",\n        \"614d066a\",\n        \"26261459\",\n        \"879c06d9\",\n        \"105817f6\",\n        \"99fd8806\",\n        \"1f4770e5\",\n        \"fd2e97ad\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/when-would-you-use-document-write/en-US.mdx",
    "content": "---\ntitle: When would you use `document.write()`?\n---\n\n## TL;DR\n\n`document.write()` is rarely used in modern web development because it can overwrite the entire document if called after the page has loaded. It is mainly used for simple tasks like writing content during the initial page load, such as for educational purposes or quick debugging. However, it is generally recommended to use other methods like `innerHTML`, `appendChild()`, or modern frameworks for manipulating the DOM.\n\n---\n\n## When would you use `document.write()`?\n\n### Initial page load\n\n`document.write()` can be used to write content directly to the document during the initial page load. This is one of the few scenarios where it might be appropriate, as it can be simpler and faster for very basic tasks.\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>Document Write Example</title>\n  </head>\n  <body>\n    <script>\n      document.write('<h1>Hello, World!</h1>');\n    </script>\n  </body>\n</html>\n```\n\n### Educational purposes\n\n`document.write()` is sometimes used in educational contexts to demonstrate basic JavaScript concepts. It provides a straightforward way to show how JavaScript can manipulate the DOM.\n\n### Quick debugging\n\nFor quick and dirty debugging, `document.write()` can be used to output variables or messages directly to the document. However, this is not recommended for production code.\n\n```javascript\nvar debugMessage = 'Debugging message';\ndocument.write(debugMessage);\n```\n\n### Legacy code\n\nIn some older codebases, you might encounter `document.write()`. While it's not recommended to use it in new projects, understanding it can be useful for maintaining or refactoring legacy code.\n\n### Why not use `document.write()`?\n\n- **Overwrites the document**: If called after the page has loaded, `document.write()` will overwrite the entire document, which can lead to loss of content and a poor user experience.\n- **Better alternatives**: Modern methods like `innerHTML`, `appendChild()`, and frameworks like React or Vue provide more control and are safer to use.\n\n```javascript\n// Using innerHTML\ndocument.getElementById('content').innerHTML = '<h1>Hello, World!</h1>';\n\n// Using appendChild\nvar newElement = document.createElement('h1');\nnewElement.textContent = 'Hello, World!';\ndocument.getElementById('content').appendChild(newElement);\n```\n\n## Further reading\n\n- [MDN Web Docs on document.write()](https://developer.mozilla.org/en-US/docs/Web/API/Document/write)\n- [Why is document.write() considered harmful?](https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice)\n- [Modern DOM manipulation methods](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction#modifying_the_document)\n"
  },
  {
    "path": "questions/when-would-you-use-document-write/metadata.json",
    "content": "{\n  \"slug\": \"when-would-you-use-document-write\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"advanced\",\n  \"featured\": false,\n  \"topics\": [\"web-api\", \"javascript\", \"html\"],\n  \"importance\": \"low\",\n  \"ranking\": 999,\n  \"difficulty\": \"hard\"\n}\n"
  },
  {
    "path": "questions/when-would-you-use-document-write/pt-BR.mdx",
    "content": "---\ntitle: Quando você usaria `document.write()`?\n---\n\n`document.write()` escreve uma string de texto em um fluxo de documento aberto por `document.open()`. Quando o `document.write()` é executado após o carregamento da página, ele chamará o `document.open`, o que limpará todo o documento (`<head>` e `<body>` removidos!) e substitui o conteúdo pelo valor do parâmetro dado. Portanto, geralmente é considerado perigoso e propenso a uso indevido.\n\nExistem algumas respostas online que explicam `documento.write()` está sendo usado no código analítico ou [quando deseja incluir estilos que só devem funcionar se o JavaScript estiver ativado](https://www.quirksmode.org/blog/archives/2005/06/three_javascrip_1.html). Ele está até sendo usado em boilerplate HTML5 para [carregar scripts em paralelo e preservar a ordem de execução](https://github.com/paulirish/html5-boilerplate/wiki/Script-Loading-Techniques#documentwrite-script-tag)! No entanto, esses motivos podem estar desatualizados e, atualmente, podem ser alcançados sem o uso do `document.write()`.\n"
  },
  {
    "path": "questions/when-would-you-use-document-write/zh-CN.mdx",
    "content": "---\ntitle: 你会在什么时候使用 `document.write()`？\n---\n\n## TL;DR\n\n`document.write()` 在现代 Web 开发中很少使用，因为它在页面加载后调用时会覆盖整个文档。它主要用于在初始页面加载期间编写内容等简单任务，例如用于教育目的或快速调试。但是，通常建议使用其他方法，如 `innerHTML`、`appendChild()` 或现代框架来操作 DOM。\n\n***\n\n## 你会在什么时候使用 `document.write()`？\n\n### 初始页面加载\n\n`document.write()` 可用于在初始页面加载期间将内容直接写入文档。这是它可能适用的少数情况之一，因为它对于非常基本的任务可能更简单、更快。\n\n```html\n<!doctype html>\n<html>\n  <head>\n    <title>Document Write Example</title>\n  </head>\n  <body>\n    <script>\n      document.write('<h1>Hello, World!</h1>');\n    </script>\n  </body>\n</html>\n```\n\n### 教育目的\n\n`document.write()` 有时用于教育环境中，以演示基本的 JavaScript 概念。它提供了一种直接的方式来展示 JavaScript 如何操作 DOM。\n\n### 快速调试\n\n对于快速而粗略的调试，`document.write()` 可用于将变量或消息直接输出到文档。但是，不建议在生产代码中使用此方法。\n\n```javascript\nvar debugMessage = 'Debugging message';\ndocument.write(debugMessage);\n```\n\n### 遗留代码\n\n在一些较旧的代码库中，你可能会遇到 `document.write()`。虽然不建议在新项目中使用它，但了解它对于维护或重构旧代码可能很有用。\n\n### 为什么不使用 `document.write()`？\n\n* **覆盖文档**：如果在页面加载后调用，`document.write()` 将覆盖整个文档，这可能导致内容丢失和糟糕的用户体验。\n* **更好的替代方案**：像 `innerHTML`、`appendChild()` 和 React 或 Vue 等框架的现代方法提供了更多控制，并且使用起来更安全。\n\n```javascript\n// 使用 innerHTML\ndocument.getElementById('content').innerHTML = '<h1>Hello, World!</h1>';\n\n// 使用 appendChild\nvar newElement = document.createElement('h1');\nnewElement.textContent = 'Hello, World!';\ndocument.getElementById('content').appendChild(newElement);\n```\n\n## 延伸阅读\n\n* [MDN Web Docs on document.write()](https://developer.mozilla.org/en-US/docs/Web/API/Document/write)\n* [Why is document.write() considered harmful?](https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice)\n* [Modern DOM manipulation methods](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction#modifying_the_document)\n"
  },
  {
    "path": "questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"a19f7675\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"6d141d1d\",\n        \"46a1b24c\",\n        \"2a7816d0\",\n        \"586cafbb\",\n        \"969c6da4\",\n        \"a63e85b\",\n        \"a11dd609\",\n        \"b1773384\",\n        \"e42d2d0\",\n        \"ad795303\",\n        \"b7cb65a1\",\n        \"5346abd9\",\n        \"286c84ee\",\n        \"a679f64a\",\n        \"9f4d3f30\",\n        \"a7812e83\",\n        \"bc867a5b\",\n        \"1f4770e5\",\n        \"44815e13\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"6d141d1d\",\n        \"46a1b24c\",\n        \"2a7816d0\",\n        \"586cafbb\",\n        \"969c6da4\",\n        \"a63e85b\",\n        \"a11dd609\",\n        \"b1773384\",\n        \"e42d2d0\",\n        \"ad795303\",\n        \"b7cb65a1\",\n        \"5346abd9\",\n        \"286c84ee\",\n        \"a679f64a\",\n        \"9f4d3f30\",\n        \"a7812e83\",\n        \"bc867a5b\",\n        \"1f4770e5\",\n        \"44815e13\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/en-US.mdx",
    "content": "---\ntitle: Why is extending built-in JavaScript objects not a good idea?\n---\n\n## TL;DR\n\nExtending a built-in/native JavaScript object means adding properties/functions to its `prototype`. While this may seem like a good idea at first, it is dangerous in practice. Imagine your code uses a few libraries that both extend the `Array.prototype` by adding the same `contains` method, the implementations will overwrite each other and your code will have unpredictable behavior if these two methods do not work the same way.\n\nThe only time you may want to extend a native object is when you want to create a polyfill, essentially providing your own implementation for a method that is part of the JavaScript specification but might not exist in the user's browser due to it being an older browser.\n\n---\n\n## Extending JavaScript\n\nIn JavaScript it's very easy to extend a built-in/native object. You can simply extend a built-in object by adding properties and functions to its `prototype`.\n\n```js live\nString.prototype.reverseString = function () {\n  return this.split('').reverse().join('');\n};\n\nconsole.log('hello world'.reverseString()); // Outputs 'dlrow olleh'\n\n// Instead of extending the built-in object, write a pure utility function to do it.\n\nfunction reverseString(str) {\n  return str.split('').reverse().join('');\n}\n\nconsole.log(reverseString('hello world')); // Outputs 'dlrow olleh'\n```\n\n## Disadvantages\n\nExtending built-in JavaScript objects is essentially modifying the global scope and it's not a good idea because:\n\n1. **Future-proofing**: If a browser decides to implement its own version of a method, your custom extension might get overridden silently, leading to unexpected behavior or conflicts.\n2. **Collisions**: Adding custom methods to built-in objects can lead to collisions with future browser implementations or other libraries, causing unexpected behavior or errors.\n3. **Maintenance and debugging**: When extending built-in objects, it can be difficult for other developers to understand the changes made, making maintenance and debugging more challenging.\n4. **Performance**: Extending built-in objects can potentially impact performance, especially if the extensions are not optimized for the specific use case.\n5. **Security**: In some cases, extending built-in objects can introduce security vulnerabilities if not done correctly, such as adding enumerable properties that can be exploited by malicious code.\n6. **Compatibility**: Custom extensions to built-in objects may not be compatible with all browsers or environments, leading to issues with cross-browser compatibility.\n7. **Namespace clashes**: Extending built-in objects can lead to namespace clashes if multiple libraries or scripts extend the same object in different ways, causing conflicts and unexpected behavior.\n\nWe dive deeper into [why it is a bad idea to modify the global scope](/questions/quiz/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it).\n\nIt is not recommended to extend built-in objects due to these potential issues and instead suggest using composition or creating custom classes and utility functions to achieve the desired functionality.\n\n## Alternatives to extending built-in objects\n\nInstead of extending built-in objects, do the following instead:\n\n1. **Create custom utility functions**: For simple tasks, creating small utility functions specific to your needs can be a cleaner and more maintainable solution.\n2. **Use libraries and frameworks**: Many libraries and frameworks provide their own helper methods and extensions, eliminating the need to modify built-in objects directly.\n\n## Polyfilling as a valid reason\n\nOne valid reason to extend built-in objects is to implement polyfills for the latest ECMAScript standard and proposals. [`core-js`](https://github.com/zloirock/core-js) is a popular library that is present on most popular websites. It not only polyfills missing features but also fixes incorrect or non-compliant implementations of JavaScript features in various browsers and runtimes.\n\n```js\nimport 'core-js/actual/array/flat-map'; // With this, Array.prototype.flatMap is available to be used.\n\n[1, 2].flatMap((it) => [it, it]); // => [1, 1, 2, 2]\n```\n\n## Further reading\n\n- [JS: don't extend JS objects](https://lucybain.com/blog/2014/js-extending-built-in-objects/)\n- [Extending built-in classes](https://javascript.info/extend-natives)\n"
  },
  {
    "path": "questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/metadata.json",
    "content": "{\n  \"slug\": \"why-is-extending-built-in-javascript-objects-not-a-good-idea\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"medium\",\n  \"ranking\": 320,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/pt-BR.mdx",
    "content": "---\ntitle: Por que estender objetos JavaScript nativos não é uma boa ideia?\n---\n\nEstender um objeto nativo/embutido do JavaScript significa adicionar propriedades/funções ao seu prototype. Embora isso possa parecer uma boa ideia a princípio, é perigoso na prática. Imagine que seu código use algumas bibliotecas que estendem o `Array.prototype` adicionando o mesmo método `contains`. As implementações se sobrescreverão e seu código quebrará se o comportamento desses dois métodos não for o mesmo.\n\nA única vez que você pode querer estender um objeto nativo é quando deseja criar um polyfill, essencialmente fornecendo sua própria implementação para um método que faz parte da especificação do JavaScript, mas pode não existir no navegador do usuário devido a ser um navegador mais antigo.\n"
  },
  {
    "path": "questions/why-is-extending-built-in-javascript-objects-not-a-good-idea/zh-CN.mdx",
    "content": "---\ntitle: 为什么扩展内置 JavaScript 对象不是一个好主意？\n---\n\n## TL;DR\n\n扩展内置/原生 JavaScript 对象意味着向其 `prototype` 添加属性/函数。虽然这乍一看可能是一个好主意，但实际上很危险。想象一下，您的代码使用了几个库，它们都通过添加相同的 `contains` 方法来扩展 `Array.prototype`，这些实现将相互覆盖，如果这两种方法的工作方式不同，您的代码将具有不可预测的行为。\n\n只有当您想创建一个 polyfill 时，才可能需要扩展原生对象，本质上是为您自己的方法提供实现，该方法是 JavaScript 规范的一部分，但由于它是一个较旧的浏览器，可能不存在于用户的浏览器中。\n\n***\n\n## 扩展 JavaScript\n\n在 JavaScript 中，扩展内置/原生对象非常容易。您只需通过向其 `prototype` 添加属性和函数来扩展内置对象。\n\n```js live\nString.prototype.reverseString = function () {\n  return this.split('').reverse().join('');\n};\n\nconsole.log('hello world'.reverseString()); // Outputs 'dlrow olleh'\n\n// Instead of extending the built-in object, write a pure utility function to do it.\n\nfunction reverseString(str) {\n  return str.split('').reverse().join('');\n}\n\nconsole.log(reverseString('hello world')); // Outputs 'dlrow olleh'\n```\n\n## 缺点\n\n扩展内置 JavaScript 对象本质上是在修改全局范围，这不是一个好主意，因为：\n\n1. **面向未来**：如果浏览器决定实现自己的方法版本，您的自定义扩展可能会被静默覆盖，从而导致意外行为或冲突。\n2. **冲突**：向内置对象添加自定义方法可能会导致与未来的浏览器实现或其他库发生冲突，从而导致意外行为或错误。\n3. **维护和调试**：扩展内置对象时，其他开发人员可能难以理解所做的更改，从而使维护和调试更具挑战性。\n4. **性能**：扩展内置对象可能会影响性能，特别是如果扩展未针对特定用例进行优化。\n5. **安全性**：在某些情况下，如果未正确执行，扩展内置对象可能会引入安全漏洞，例如添加可被恶意代码利用的可枚举属性。\n6. **兼容性**：对内置对象的自定义扩展可能与并非所有浏览器或环境兼容，从而导致跨浏览器兼容性问题。\n7. **命名空间冲突**：如果多个库或脚本以不同的方式扩展同一对象，扩展内置对象可能会导致命名空间冲突，从而导致冲突和意外行为。\n\n我们深入探讨了[为什么修改全局范围不是一个好主意](/questions/quiz/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it)。\n\n由于这些潜在问题，不建议扩展内置对象，而是建议使用组合或创建自定义类和实用程序函数来实现所需的功能。\n\n## 扩展内置对象的替代方案\n\n不要扩展内置对象，而是执行以下操作：\n\n1. **创建自定义实用程序函数**：对于简单的任务，创建特定于您需求的小型实用程序函数可以成为更清晰、更易于维护的解决方案。\n2. **使用库和框架**：许多库和框架都提供自己的辅助方法和扩展，从而无需直接修改内置对象。\n\n## 作为有效原因的 Polyfilling\n\n扩展内置对象的一个有效原因是为最新的 ECMAScript 标准和提案实现 polyfill。[`core-js`](https://github.com/zloirock/core-js) 是一个流行的库，存在于大多数流行的网站上。它不仅会 polyfill 缺失的功能，还会修复各种浏览器和运行时中 JavaScript 功能的不正确或不兼容的实现。\n\n```js\nimport 'core-js/actual/array/flat-map'; // With this, Array.prototype.flatMap is available to be used.\n\n[1, 2].flatMap((it) => [it, it]); // => [1, 1, 2, 2]\n```\n\n## 延伸阅读\n\n* [JS: don't extend JS objects](https://lucybain.com/blog/2014/js-extending-built-in-objects/)\n* [Extending built-in classes](https://javascript.info/extend-natives)\n"
  },
  {
    "path": "questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"6c212798\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"a205d777\",\n        \"cde7b226\",\n        \"4b652bee\",\n        \"28747c51\",\n        \"2a7816d0\",\n        \"2c31338e\",\n        \"2af285c6\",\n        \"a2cf7bc1\",\n        \"ce7c2459\",\n        \"988d0dfa\",\n        \"3b347d52\",\n        \"2bc8952c\",\n        \"1c2ab82d\",\n        \"3de51dde\",\n        \"b7d3be0\",\n        \"da0047e6\",\n        \"4592edd0\",\n        \"76018cb7\",\n        \"3328656\",\n        \"2ededf7a\",\n        \"c9a2ab27\",\n        \"2a7816d0\",\n        \"1f4770e5\",\n        \"d1dc74c3\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"a205d777\",\n        \"cde7b226\",\n        \"4b652bee\",\n        \"28747c51\",\n        \"2a7816d0\",\n        \"2c31338e\",\n        \"2af285c6\",\n        \"a2cf7bc1\",\n        \"ce7c2459\",\n        \"988d0dfa\",\n        \"3b347d52\",\n        \"2bc8952c\",\n        \"1c2ab82d\",\n        \"3de51dde\",\n        \"b7d3be0\",\n        \"da0047e6\",\n        \"4592edd0\",\n        \"76018cb7\",\n        \"3328656\",\n        \"2ededf7a\",\n        \"c9a2ab27\",\n        \"2a7816d0\",\n        \"1f4770e5\",\n        \"d1dc74c3\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/en-US.mdx",
    "content": "---\ntitle: Why is it, in general, a good idea to leave the global JavaScript scope of a website as-is and never touch it?\n---\n\n## TL;DR\n\nJavaScript that is executed in the browser has access to the global scope (the `window` object). In general it's a good software engineering practice to not pollute the global namespace unless you are working on a feature that truly needs to be global – it is needed by the entire page. Several reasons to avoid touching the global scope:\n\n- **Naming conflicts**: Sharing the global scope across scripts can cause conflicts and bugs when new global variables or changes are introduced.\n- **Cluttered global namespace**: Keeping the global namespace minimal avoids making the codebase hard to manage and maintain.\n- **Scope leaks**: Unintentional references to global variables in closures or event handlers can cause memory leaks and performance issues.\n- **Modularity and encapsulation**: Good design promotes keeping variables and functions within their specific scopes, enhancing organization, reusability, and maintainability.\n- **Security concerns**: Global variables are accessible by all scripts, including potentially malicious ones, posing security risks, especially if sensitive data is stored there.\n- **Compatibility and portability**: Heavy reliance on global variables reduces code portability and integration ease with other libraries or frameworks.\n\nFollow these best practices to avoid global scope pollution:\n\n- **Use local variables**: Declare variables within functions or blocks using `var`, `let`, or `const` to limit their scope.\n- **Pass variables as function parameters**: Maintain encapsulation by passing variables as parameters instead of accessing them globally.\n- **Use immediately invoked function expressions (IIFE)**: Create new scopes with IIFEs to prevent adding variables to the global scope.\n- **Use modules**: Encapsulate code with module systems to maintain separate scopes and manageability.\n\n---\n\n## What is the global scope?\n\nIn the browser, the global scope is the top-level context where variables, functions, and objects are accessible from anywhere in the code. The global scope is represented by the `window` object. Any variables or functions declared outside of any function or block (that is not within any module) are added to the `window` object and can be accessed globally.\n\nFor example:\n\n```js\n// Assuming this is run in the global scope and not within a module.\nvar globalVariable = 'I am global';\nfunction globalFunction() {\n  console.log('I am a global function');\n}\n\nconsole.log(window.globalVariable); // 'I am global'\nwindow.globalFunction(); // 'I am a global function'\n```\n\nIn this example, `globalVariable` and `globalFunction` are added to the `window` object and can be accessed from anywhere in the global context.\n\n## Pitfalls of global scope\n\nIn general, it's a good software engineering practice to not pollute the global namespace unless you are working on a feature that truly needs to be global – it is needed by the entire page. There are many reasons to avoid touching the global scope:\n\n- **Naming conflicts**: The global scope is shared across all scripts on a web page. If you introduce new global variables or modify existing ones, you risk causing naming conflicts with other scripts or libraries used on the same page. This can lead to unexpected behavior and difficult-to-debug issues.\n- **Cluttered global namespace**: The global namespace should be kept as clean and minimal as possible. Adding unnecessary global variables or functions can clutter the namespace and make it harder to manage and maintain the codebase over time.\n- **Scope leaks**: When working with closures or event handlers, it's easy to accidentally create unintended references to global variables, leading to memory leaks and performance issues. By avoiding global variables altogether, you can prevent these types of scope leaks.\n- **Modularity and encapsulation**: One of the principles of good software design is modularity and encapsulation. By keeping variables and functions within their respective scopes (e.g., module, function, or block scope), you promote better code organization, reusability, and maintainability.\n- **Security concerns**: Global variables can be accessed and modified by any script running on the page, including potentially malicious scripts. It is quite common for websites to load third-party scripts and in the event someone's network is compromised, it can pose security risks, especially if sensitive data is stored in global variables. However, in the first place you should not expose any sensitive data on the client.\n- **Compatibility and portability**: By relying heavily on global variables, your code becomes less portable and more dependent on the specific environment it was written for. This can make it harder to integrate with other libraries or frameworks, or to run the code in different environments (e.g., server-side vs browser).\n\nHere's an example of global scope being used.\n\n```js live\n// Assuming this is run in the global scope, not within a module.\nlet count = 0;\n\nfunction incrementCount() {\n  count++;\n  console.log(count);\n}\n\nfunction decrementCount() {\n  count--;\n  console.log(count);\n}\n\nincrementCount(); // Output: 1\ndecrementCount(); // Output: 0\n```\n\nIn this example, `count`, `incrementCount`, and `decrementCount` are defined on the global scope. Any script on the page can access and modify the `count`, as well as all variables on `window`.\n\n## Avoiding global scope pollution\n\nBy now we hope that you're convinced that it's not a good idea to define variables on the global scope. To avoid polluting the global scope, it is recommended to follow best practices such as:\n\n- **Use local variables**: Declare variables within functions or blocks to limit their scope and prevent them from being accessed globally. Use `var`, `let`, or `const` to declare variables within a specific scope, ensuring they are not accidentally made global.\n- **Pass variables as function parameters:**: Instead of accessing variables directly from the outer scope, pass them as parameters to functions to maintain encapsulation and avoid global scope pollution.\n- **Use modules**: Utilize module systems to encapsulate your code and prevent global scope pollution. Each module has its own scope, making it easier to manage and maintain your code.\n- **Use immediately invoked function expressions (IIFE)**: If modules are not available, wrap your code in an IIFE to create a new scope, preventing variables from being added to the global scope unless you explicitly expose them.\n\n```js live\n// Assuming this is run in the global scope, not within a module.\n(function () {\n  let count = 0;\n\n  window.incrementCount = function () {\n    count++;\n    console.log(count);\n  };\n\n  window.decrementCount = function () {\n    count--;\n    console.log(count);\n  };\n})();\n\nincrementCount(); // Output: 1\ndecrementCount(); // Output: 0\n```\n\nIn this example, `count` is not accessible in the global scope. It can only be accessed and modified by the `incrementCount` and `decrementCount` functions. These functions are exposed to the global scope by attaching them to the `window` object, but they still have access to the `count` variable in their parent scope. This provides a way to encapsulate the underlying data and only expose the necessary operations – no direct manipulation of the value is allowed.\n\n---\n\n## Further reading\n\n- [JavaScript modules - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n- [Modules, introduction](https://javascript.info/modules-intro)\n- [JS: don't touch the global scope](https://lucybain.com/blog/2014/js-dont-touch-global-scope/)\n- [Variables: Scopes, Environments, and Closures](https://exploringjs.com/es5/ch16.html)\n"
  },
  {
    "path": "questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/metadata.json",
    "content": "{\n  \"slug\": \"why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"javascript\"],\n  \"importance\": \"medium\",\n  \"ranking\": 330,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/pt-BR.mdx",
    "content": "---\ntitle: Por que, em geral, é uma boa ideia deixar o escopo global de um site como está e nunca modificá-lo?\n---\n\nJavaScript que é executado no navegador tem acesso ao escopo global, e se todos usarem o namespace global para definir suas variáveis, as colisões provavelmente ocorrerão. Use o padrão do módulo (IIFES) para encapsular suas variáveis dentro de um namespace local.\n"
  },
  {
    "path": "questions/why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it/zh-CN.mdx",
    "content": "---\ntitle: 为什么一般来说，最好保持网站的全局 JavaScript 作用域不变，并且永远不要触及它？\n---\n\n## 总结\n\n在浏览器中执行的 JavaScript 可以访问全局作用域（`window` 对象）。一般来说，不污染全局命名空间是一个很好的软件工程实践，除非你正在处理一个真正需要全局的特性——整个页面都需要它。避免触及全局作用域的几个原因：\n\n* **命名冲突**：在脚本之间共享全局作用域可能导致冲突和错误，当引入新的全局变量或进行更改时。\n* **全局命名空间混乱**：保持全局命名空间最小化可以避免使代码库难以管理和维护。\n* **作用域泄漏**：在闭包或事件处理程序中无意中引用全局变量可能导致内存泄漏和性能问题。\n* **模块化和封装**：良好的设计促进将变量和函数保持在其特定作用域内，从而增强组织性、可重用性和可维护性。\n* **安全问题**：全局变量可被所有脚本访问，包括潜在的恶意脚本，这会带来安全风险，特别是如果敏感数据存储在其中。\n* **兼容性和可移植性**：过度依赖全局变量会降低代码的可移植性，并降低与其他库或框架的集成难度。\n\n遵循这些最佳实践以避免全局作用域污染：\n\n* **使用局部变量**：使用 `var`、`let` 或 `const` 在函数或代码块内声明变量以限制其作用域。\n* **将变量作为函数参数传递**：通过将变量作为参数传递而不是全局访问它们来保持封装。\n* **使用立即调用函数表达式（IIFE）**：使用 IIFE 创建新作用域以防止将变量添加到全局作用域。\n* **使用模块**：使用模块系统封装代码以保持独立的作用域和可管理性。\n\n***\n\n## 什么是全局作用域？\n\n在浏览器中，全局作用域是顶级上下文，变量、函数和对象可以从代码中的任何位置访问。全局作用域由 `window` 对象表示。在任何函数或代码块（即不在任何模块内）之外声明的任何变量或函数都会添加到 `window` 对象中，并且可以在全局范围内访问。\n\n例如：\n\n```js\n// 假设这在全局作用域中运行，而不是在模块中。\nvar globalVariable = '我是全局变量';\nfunction globalFunction() {\n  console.log('我是一个全局函数');\n}\n\nconsole.log(window.globalVariable); // '我是全局变量'\nwindow.globalFunction(); // '我是一个全局函数'\n```\n\n在此示例中，`globalVariable` 和 `globalFunction` 被添加到 `window` 对象中，并且可以从全局上下文中的任何位置访问。\n\n## 全局作用域的陷阱\n\n一般来说，不污染全局命名空间是一个很好的软件工程实践，除非你正在处理一个真正需要全局的特性——整个页面都需要它。有很多原因可以避免触及全局作用域：\n\n* **命名冲突**：全局作用域在网页上的所有脚本之间共享。如果你引入新的全局变量或修改现有的全局变量，你可能会导致与在同一页面上使用的其他脚本或库发生命名冲突。这可能导致意外行为和难以调试的问题。\n* **全局命名空间混乱**：全局命名空间应保持尽可能干净和最小。添加不必要的全局变量或函数会使命名空间混乱，并使代码库随着时间的推移更难于管理和维护。\n* **作用域泄漏**：在使用闭包或事件处理程序时，很容易意外地创建对全局变量的无意引用，从而导致内存泄漏和性能问题。通过完全避免全局变量，你可以防止这些类型的作用域泄漏。\n* **模块化和封装**：良好软件设计原则之一是模块化和封装。通过将变量和函数保留在其各自的作用域内（例如，模块、函数或块作用域），你可以促进更好的代码组织、可重用性和可维护性。\n* **安全问题**：全局变量可以被页面上运行的任何脚本访问和修改，包括潜在的恶意脚本。网站加载第三方脚本是很常见的，如果有人网络被入侵，这可能会带来安全风险，特别是如果敏感数据存储在全局变量中。但是，首先你不应该在客户端上暴露任何敏感数据。\n* **兼容性和可移植性**：通过严重依赖全局变量，你的代码变得不太可移植，并且更依赖于编写它的特定环境。这可能会使它更难以与其他库或框架集成，或者在不同的环境中运行代码（例如，服务器端与浏览器）。\n\n这是一个使用全局作用域的例子。\n\n```js live\n// 假设这在全局作用域中运行，而不是在模块中。\nlet count = 0;\n\nfunction incrementCount() {\n  count++;\n  console.log(count);\n}\n\nfunction decrementCount() {\n  count--;\n  console.log(count);\n}\n\nincrementCount(); // 输出：1\ndecrementCount(); // 输出：0\n```\n\n在此示例中，`count`、`incrementCount` 和 `decrementCount` 在全局作用域中定义。页面上的任何脚本都可以访问和修改 `count`，以及 `window` 上的所有变量。\n\n## 避免全局作用域污染\n\n到目前为止，我们希望您相信在全局范围内定义变量不是一个好主意。为了避免污染全局范围，建议遵循最佳实践，例如：\n\n* **使用局部变量**：在函数或代码块内声明变量，以限制其作用域，防止它们被全局访问。使用 `var`、`let` 或 `const` 在特定作用域内声明变量，确保它们不会被意外地设置为全局变量。\n* **将变量作为函数参数传递**：不要直接从外部作用域访问变量，而是将它们作为参数传递给函数，以保持封装并避免全局作用域污染。\n* **使用模块**：利用模块系统来封装你的代码，防止全局作用域污染。每个模块都有自己的作用域，这使得管理和维护你的代码更容易。\n* **使用立即调用函数表达式（IIFE）**：如果模块不可用，将你的代码包装在 IIFE 中以创建一个新的作用域，防止变量被添加到全局作用域，除非你明确地暴露它们。\n\n```js live\n// Assuming this is run in the global scope, not within a module.\n(function () {\n  let count = 0;\n\n  window.incrementCount = function () {\n    count++;\n    console.log(count);\n  };\n\n  window.decrementCount = function () {\n    count--;\n    console.log(count);\n  };\n})();\n\nincrementCount(); // Output: 1\ndecrementCount(); // Output: 0\n```\n\n在这个例子中，`count`在全局范围内是不可访问的。它只能通过`incrementCount`和`decrementCount`函数访问和修改。这些函数通过将它们附加到`window`对象来暴露给全局范围，但它们仍然可以访问其父范围中的`count`变量。这提供了一种封装底层数据并仅公开必要操作的方法——不允许直接操作该值。\n\n***\n\n## 延伸阅读\n\n* [JavaScript modules - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)\n* [Modules, introduction](https://javascript.info/modules-intro)\n* [JS: don't touch the global scope](https://lucybain.com/blog/2014/js-dont-touch-global-scope/)\n* [Variables: Scopes, Environments, and Closures](https://exploringjs.com/es5/ch16.html)\n"
  },
  {
    "path": "questions/why-you-might-want-to-create-static-class-members/en-US.langnostic.json",
    "content": "{\n  \"frontmatter\": {\n    \"title\": \"c9900080\"\n  },\n  \"content\": {\n    \"source\": {\n      \"locale\": \"en-US\",\n      \"hashes\": [\n        \"77da26a5\",\n        \"df92fe62\",\n        \"e9156f8f\",\n        \"322b6d7f\",\n        \"c6fe14bf\",\n        \"2a7816d0\",\n        \"2a63ac6a\",\n        \"d58b7d1b\",\n        \"fef037e4\",\n        \"1633fb67\",\n        \"d86bfb50\",\n        \"db704af8\",\n        \"cb590ff2\",\n        \"83f9358a\",\n        \"275883aa\",\n        \"323dc4fc\",\n        \"a39e4253\",\n        \"72ddc219\",\n        \"f28e393f\",\n        \"8a48dd18\",\n        \"3b883daf\",\n        \"50b6197c\",\n        \"12555ca9\",\n        \"cd2b9098\",\n        \"9846f084\",\n        \"4f530b3e\",\n        \"ee9c1eea\",\n        \"8c069632\"\n      ]\n    },\n    \"targets\": {\n      \"zh-CN\": [\n        \"77da26a5\",\n        \"df92fe62\",\n        \"e9156f8f\",\n        \"322b6d7f\",\n        \"c6fe14bf\",\n        \"2a7816d0\",\n        \"2a63ac6a\",\n        \"d58b7d1b\",\n        \"fef037e4\",\n        \"1633fb67\",\n        \"d86bfb50\",\n        \"db704af8\",\n        \"cb590ff2\",\n        \"83f9358a\",\n        \"275883aa\",\n        \"323dc4fc\",\n        \"a39e4253\",\n        \"72ddc219\",\n        \"f28e393f\",\n        \"8a48dd18\",\n        \"3b883daf\",\n        \"50b6197c\",\n        \"12555ca9\",\n        \"cd2b9098\",\n        \"9846f084\",\n        \"4f530b3e\",\n        \"ee9c1eea\",\n        \"8c069632\"\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "questions/why-you-might-want-to-create-static-class-members/en-US.mdx",
    "content": "---\ntitle: Why might you want to create static class members in JavaScript?\n---\n\n## TL;DR\n\nStatic class members (properties/methods) has a `static` keyword prepended. Such members cannot be directly accessed on instances of the class. Instead, they're accessed on the class itself.\n\n```js live\nclass Car {\n  static noOfWheels = 4;\n  static compare() {\n    return 'Static method has been called.';\n  }\n}\n\nconsole.log(Car.noOfWheels); // 4\n```\n\nStatic members are useful under the following scenarios:\n\n- **Namespace organization**: Static properties can be used to define constants or configuration values that are specific to a class. This helps organize related data within the class namespace and prevents naming conflicts with other variables. Examples include `Math.PI`, `Math.SQRT2`.\n- **Helper functions**: Static methods can be used as helper functions that operate on the class itself or its instances. This can improve code readability and maintainability by separating utility logic from the core functionality of the class. Examples of frequently used static methods include `Object.assign()`, `Math.max()`.\n- **Singleton pattern**: In some rare cases, static properties and methods can be used to implement a singleton pattern, where only one instance of a class ever exists. However, this pattern can be tricky to manage and is generally discouraged in favor of more modern dependency injection techniques.\n\n---\n\n## Static class members\n\nStatic class members (properties/methods) are not tied to a specific instance of a class and have the same value regardless of which instance is referring to it. Static properties are typically configuration variables and static methods are usually pure utility functions which do not depend on the state of the instance. Such properties has a `static` keyword prepended.\n\n```js live\nclass Car {\n  static noOfWheels = 4;\n  static compare() {\n    return 'static method has been called.';\n  }\n}\n\nconsole.log(Car.noOfWheels); // Output: 4\nconsole.log(Car.compare()); // Output: static method has been called.\n```\n\nStatic members are not accessible by specific instance of class.\n\n```js live\nclass Car {\n  static noOfWheels = 4;\n  static compare() {\n    return 'static method has been called.';\n  }\n}\n\nconst car = new Car();\nconsole.log(car.noOfWheels); // Output: undefined\nconsole.log(car.compare()); // Error: TypeError: car.compare is not a function\n```\n\nThe `Math` class in JavaScript is a good example of a common library that uses static members. The `Math` class in JavaScript is a built-in object that provides a collection of mathematical constants and functions. It is a static class, meaning that all of its properties and methods are static. Here's an example of how the `Math` class uses static members:\n\n```js live\nconsole.log(Math.PI); // Output: 3.141592653589793\nconsole.log(Math.abs(-5)); // Output: 5\nconsole.log(Math.max(1, 2, 3)); // Output: 3\n```\n\nIn this example, `Math.PI`, `Math.abs()`, and `Math.max()` are all static members of the `Math` class. They can be accessed directly on the `Math` object without the need to create an instance of the class.\n\n## Reasons to use static class members\n\n### Utility functions\n\nStatic class members can be useful for defining utility functions that don't require any instance-specific (don't use `this`) data or behavior. For example, you might have a `Arithmetic` class with static methods for common mathematical operations.\n\n```js live\nclass Arithmetic {\n  static add(a, b) {\n    return a + b;\n  }\n  static subtract(a, b) {\n    return a - b;\n  }\n}\n\nconsole.log(Arithmetic.add(2, 3)); // Output: 5\nconsole.log(Arithmetic.subtract(5, 2)); // Output: 3\n```\n\n### Singletons\n\nStatic class members can be used to implement the Singleton pattern, where you want to ensure that only one instance of a class exists throughout your application.\n\n```js live\nclass Singleton {\n  static instance;\n\n  static getInstance() {\n    if (!this.instance) {\n      this.instance = new Singleton();\n    }\n    return this.instance;\n  }\n}\n\nconst singleton1 = Singleton.getInstance();\nconst singleton2 = Singleton.getInstance();\n\nconsole.log(singleton1 === singleton2); // Output: true\n```\n\n### Configurations\n\nStatic class members can be used to store configuration or settings that are shared across all instances of a class. This can be useful for things like API keys, feature flags, or other global settings.\n\n```js live\nclass Config {\n  static API_KEY = 'your-api-key';\n  static FEATURE_FLAG = true;\n}\n\nconsole.log(Config.API_KEY); // Output: 'your-api-key'\nconsole.log(Config.FEATURE_FLAG); // Output: true\n```\n\n### Performance\n\nIn some cases, using static class members can improve performance by reducing the amount of memory used by your application. This is because static class members are shared across all instances of a class, rather than being duplicated for each instance.\n\n## Further Reading\n\n- [Static methods and properties | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static)\n- [Static properties and methods | Javascript.info](https://javascript.info/static-properties-methods)\n"
  },
  {
    "path": "questions/why-you-might-want-to-create-static-class-members/metadata.json",
    "content": "{\n  \"slug\": \"why-you-might-want-to-create-static-class-members\",\n  \"languages\": [],\n  \"companies\": [],\n  \"access\": \"free\",\n  \"duration\": 5,\n  \"published\": true,\n  \"level\": \"intermediate\",\n  \"featured\": true,\n  \"topics\": [\"javascript\", \"oop\"],\n  \"importance\": \"medium\",\n  \"ranking\": 420,\n  \"difficulty\": \"medium\"\n}\n"
  },
  {
    "path": "questions/why-you-might-want-to-create-static-class-members/pt-BR.mdx",
    "content": "---\ntitle: Por que você pode querer criar membros de classe estáticos?\n---\n\nOs membros estáticos de classe (propriedades/métodos) não estão ligados a uma instância específica de uma classe e têm o mesmo valor independentemente da instância que está se referindo a ele. Propriedades estáticas geralmente são variáveis de configuração e métodos estáticos são normalmente funções utilitárias puras que não dependem do estado da instância.\n"
  },
  {
    "path": "questions/why-you-might-want-to-create-static-class-members/zh-CN.mdx",
    "content": "---\ntitle: 为什么你可能想要在 JavaScript 中创建静态类成员？\n---\n\n## TL;DR\n\n静态类成员（属性/方法）有一个前置的 `static` 关键字。此类成员不能直接在类的实例上访问。相反，它们在类本身上被访问。\n\n```js live\nclass Car {\n  static noOfWheels = 4;\n  static compare() {\n    return 'Static method has been called.';\n  }\n}\n\nconsole.log(Car.noOfWheels); // 4\n```\n\n静态成员在以下情况下很有用：\n\n* **命名空间组织**：静态属性可用于定义特定于类的常量或配置值。这有助于在类命名空间内组织相关数据，并防止与其他变量发生命名冲突。示例包括 `Math.PI`、`Math.SQRT2`。\n* **辅助函数**：静态方法可用作对类本身或其实例进行操作的辅助函数。这可以通过将实用程序逻辑与类的核心功能分开来提高代码的可读性和可维护性。常用静态方法的示例包括 `Object.assign()`、`Math.max()`。\n* **单例模式**：在极少数情况下，静态属性和方法可用于实现单例模式，其中只存在一个类的实例。但是，这种模式可能难以管理，通常不鼓励使用，而倾向于使用更现代的依赖注入技术。\n\n***\n\n## 静态类成员\n\n静态类成员（属性/方法）不与类的特定实例相关联，并且无论哪个实例引用它，都具有相同的值。静态属性通常是配置变量，静态方法通常是纯实用程序函数，不依赖于实例的状态。此类属性有一个前置的 `static` 关键字。\n\n```js live\nclass Car {\n  static noOfWheels = 4;\n  static compare() {\n    return 'static method has been called.';\n  }\n}\n\nconsole.log(Car.noOfWheels); // Output: 4\nconsole.log(Car.compare()); // Output: static method has been called.\n```\n\n静态成员不能被类的特定实例访问。\n\n```js live\nclass Car {\n  static noOfWheels = 4;\n  static compare() {\n    return 'static method has been called.';\n  }\n}\n\nconst car = new Car();\nconsole.log(car.noOfWheels); // Output: undefined\nconsole.log(car.compare()); // Error: TypeError: car.compare is not a function\n```\n\nJavaScript 中的 `Math` 类是使用静态成员的常见库的一个很好的例子。JavaScript 中的 `Math` 类是一个内置对象，它提供了一组数学常量和函数。它是一个静态类，这意味着它的所有属性和方法都是静态的。以下是 `Math` 类如何使用静态成员的示例：\n\n```js live\nconsole.log(Math.PI); // Output: 3.141592653589793\nconsole.log(Math.abs(-5)); // Output: 5\nconsole.log(Math.max(1, 2, 3)); // Output: 3\n```\n\n在此示例中，`Math.PI`、`Math.abs()` 和 `Math.max()` 都是 `Math` 类的静态成员。它们可以直接在 `Math` 对象上访问，而无需创建类的实例。\n\n## 使用静态类成员的原因\n\n### 实用函数\n\n静态类成员可用于定义不需要任何特定于实例（不使用 `this`）数据或行为的实用函数。例如，您可能有一个 `Arithmetic` 类，其中包含用于常见数学运算的静态方法。\n\n```js live\nclass Arithmetic {\n  static add(a, b) {\n    return a + b;\n  }\n  static subtract(a, b) {\n    return a - b;\n  }\n}\n\nconsole.log(Arithmetic.add(2, 3)); // Output: 5\nconsole.log(Arithmetic.subtract(5, 2)); // Output: 3\n```\n\n### 单例\n\n静态类成员可用于实现单例模式，在单例模式中，您希望确保应用程序中只存在一个类的实例。\n\n```js live\nclass Singleton {\n  static instance;\n\n  static getInstance() {\n    if (!this.instance) {\n      this.instance = new Singleton();\n    }\n    return this.instance;\n  }\n}\n\nconst singleton1 = Singleton.getInstance();\nconst singleton2 = Singleton.getInstance();\n\nconsole.log(singleton1 === singleton2); // Output: true\n```\n\n### 配置\n\n静态类成员可用于存储在类的所有实例之间共享的配置或设置。这对于 API 密钥、功能标志或其他全局设置非常有用。\n\n```js live\nclass Config {\n  static API_KEY = 'your-api-key';\n  static FEATURE_FLAG = true;\n}\n\nconsole.log(Config.API_KEY); // Output: 'your-api-key'\nconsole.log(Config.FEATURE_FLAG); // Output: true\n```\n\n### 性能\n\n在某些情况下，使用静态类成员可以通过减少应用程序使用的内存量来提高性能。这是因为静态类成员在类的所有实例之间共享，而不是为每个实例复制。\n\n## 延伸阅读\n\n* [静态方法和属性 | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static)\n* [静态属性和方法 | Javascript.info](https://javascript.info/static-properties-methods)\n"
  },
  {
    "path": "scripts/constants.ts",
    "content": "export const GITHUB_ORG = 'yangshun';\nexport const GITHUB_REPO = 'top-javascript-interview-questions';\n"
  },
  {
    "path": "scripts/gen.ts",
    "content": "import { slug } from 'github-slugger';\nimport { startCase } from 'lodash-es';\nimport fs from 'fs';\nimport path from 'path';\nimport grayMatter from 'gray-matter';\nimport util from 'util';\nimport { QuestionFrontmatter, QuestionItem, QuestionMetadata } from './types';\nimport { GITHUB_ORG, GITHUB_REPO } from './constants';\nimport questionsAll from '../data/questions.json';\nimport url from 'node:url';\n\nconst README_PATH_EN = 'README.md';\n\nconst readFileAsync = util.promisify(fs.readFile);\n\nasync function processQuestion(\n  dirName: string,\n  locale: string = 'en-US',\n): Promise<QuestionItem | null> {\n  const metadataPath = path.join('./questions', dirName, 'metadata.json');\n  const localeFile = path.join('./questions', dirName, locale + '.mdx');\n\n  const [metadataFile, markdownFile] = await Promise.all([\n    readFileAsync(metadataPath),\n    readFileAsync(localeFile),\n  ]);\n\n  const metadata: QuestionMetadata = JSON.parse(String(metadataFile));\n  const markdown = String(markdownFile);\n\n  const { data } = grayMatter(markdown);\n  const frontMatter = data as QuestionFrontmatter;\n\n  const title = frontMatter.title;\n  if (!title) {\n    console.warn(`${localeFile} does not have title`);\n    return null;\n  }\n\n  // Extract contents between the first `## TL;DR` and `---`.\n  const content = markdown.match(/## TL;DR\\n\\n([\\s\\S]*?)---\\n/);\n\n  const tlDrPart = content?.[1];\n  if (tlDrPart == null) {\n    return null;\n  }\n\n  // TODO: use a more robust check for headings.\n  if (tlDrPart.includes('###')) {\n    throw `${localeFile}'s TL;DR contains headings`;\n  }\n\n  return {\n    locale,\n    metadata,\n    href:\n      'https://www.greatfrontend.com' +\n      url.format({\n        pathname: `/questions/quiz/${metadata.slug}`,\n        query: {\n          language: 'js',\n          tab: 'quiz',\n        },\n      }),\n    title,\n    titleSlug: slug(title),\n    content: tlDrPart\n      // Replace relative links with absolute links.\n      .replace('](/', '](https://www.greatfrontend.com/')\n      .trim(),\n  };\n}\n\nasync function readQuestionsList() {\n  const qnSlugs = fs\n    .readdirSync('./questions', {\n      withFileTypes: true,\n    })\n    .filter((dirent) => dirent.isDirectory())\n    .map((dirent) => dirent.name);\n\n  return await Promise.all(\n    qnSlugs.map(async (qnSlug) => {\n      const metadataPath = path.join('./questions', qnSlug, 'metadata.json');\n\n      const metadataFile = await readFileAsync(metadataPath);\n      const metadata: QuestionMetadata = JSON.parse(String(metadataFile));\n      if (qnSlug !== metadata.slug) {\n        throw `Mismatch in directory and slug: \"${qnSlug}\" vs \"${metadata.slug}\"`;\n      }\n\n      return metadata;\n    }),\n  );\n}\n\nasync function processQuestionList(qns: string[]) {\n  const questionObjectsIncludingNull = await Promise.all(\n    qns.map((qnSlug) => processQuestion(qnSlug)),\n  );\n\n  return questionObjectsIncludingNull.flatMap((item) =>\n    item != null ? [item] : [],\n  );\n}\n\nfunction formatTableOfContents(qnList: QuestionItem[]) {\n  const tableOfContentsLines = [\n    '| No. | Questions | Level |',\n    '| --- | :-- | :-- |',\n  ];\n\n  qnList.forEach(({ metadata, title, titleSlug }, index) =>\n    tableOfContentsLines.push(\n      `| ${index + 1} | [${title}](#${titleSlug}) | ${startCase(\n        metadata.level,\n      )} |`,\n    ),\n  );\n\n  return tableOfContentsLines.join('\\n');\n}\n\nfunction formatQuestion(\n  qn: QuestionItem,\n  index: number,\n  tableOfContentsAnchor: string,\n  onGFE: boolean = true,\n) {\n  return `### ${qn.title}\n\n<!-- Update here: /questions/${qn.metadata.slug}/${qn.locale}.mdx -->\n\n${qn.content\n  .split('\\n')\n  // Add indentation.\n  // .map((line) => '    ' + line)\n  .join('\\n')}\n\n<!-- Update here: /questions/${qn.metadata.slug}/${qn.locale}.mdx -->\n\n<br>\n    ${\n      onGFE\n        ? `\n> Read the [detailed answer](${qn.href}) on [GreatFrontEnd](https://www.greatfrontend.com?gnrs=github) which allows progress tracking, contains more code samples, and useful resources.\n`\n        : ''\n    }\n[Back to top ↑](#${tableOfContentsAnchor}) &nbsp;&nbsp;/&nbsp;&nbsp; [✏️ Edit answer](https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/edit/main/questions/${\n    qn.metadata.slug\n  }/${qn.locale}.mdx)\n\n<br>\n`;\n}\n\ntype Options = Readonly<{\n  sortByRanking: boolean;\n  showLinkToGFE: boolean;\n  tableOfContentsAnchor: string;\n  tocStart: string;\n  tocEnd: string;\n  qnsStart: string;\n  qnsEnd: string;\n}>;\n\nasync function generateList(qns: string[], options: Options) {\n  const {\n    tableOfContentsAnchor,\n    tocStart,\n    tocEnd,\n    qnsStart,\n    qnsEnd,\n    showLinkToGFE,\n    sortByRanking,\n  } = options;\n  const qnItemListValue = await processQuestionList(qns);\n  const qnItemList = qnItemListValue.slice();\n\n  if (sortByRanking) {\n    qnItemList.sort((a, b) => a.metadata.ranking - b.metadata.ranking);\n  }\n  const qnTableOfContents = formatTableOfContents(qnItemList);\n  const qnAnswers = qnItemList\n    .map((qnItem, index) =>\n      formatQuestion(qnItem, index + 1, tableOfContentsAnchor, showLinkToGFE),\n    )\n    .join('\\n');\n\n  const readmeFile = String(fs.readFileSync(README_PATH_EN));\n\n  const tocRegex = new RegExp(\n    `(<!-- ${tocStart} -->)([\\\\s\\\\S]*?)(<!-- ${tocEnd} -->)`,\n  );\n  const qnsRegex = new RegExp(\n    `(<!-- ${qnsStart} -->)([\\\\s\\\\S]*?)(<!-- ${qnsEnd} -->)`,\n  );\n\n  const updatedText = readmeFile\n    .replace(tocRegex, `$1\\n\\n${qnTableOfContents}\\n\\n$3`)\n    .replace(qnsRegex, `$1\\n\\n${qnAnswers}\\n\\n$3`);\n\n  fs.writeFileSync(README_PATH_EN, updatedText);\n}\n\nasync function generateBulletList(\n  qns: string[],\n  options: Readonly<{\n    qnsStart: string;\n    qnsEnd: string;\n  }>,\n) {\n  const { qnsStart, qnsEnd } = options;\n  const qnItemList = await processQuestionList(qns);\n  const qnsItemListSorted = qnItemList.sort(\n    (a, b) => a.metadata.ranking - b.metadata.ranking,\n  );\n\n  const qnAnswers = qnsItemListSorted\n    .map(\n      (qnItem, index) =>\n        `${index + 1}. [${qnItem.title}](#${qnItem.titleSlug})`,\n    )\n    .join('\\n');\n\n  const readmeFile = String(fs.readFileSync(README_PATH_EN));\n\n  const qnsRegex = new RegExp(\n    `(<!-- ${qnsStart} -->)([\\\\s\\\\S]*?)(<!-- ${qnsEnd} -->)`,\n  );\n\n  const updatedText = readmeFile.replace(qnsRegex, `$1\\n\\n${qnAnswers}\\n\\n$3`);\n\n  fs.writeFileSync(README_PATH_EN, updatedText);\n}\n\nasync function generateAll() {\n  const qns = await readQuestionsList();\n\n  const featuredQns = qns.filter((qn) => qn.featured);\n  await generateList(\n    featuredQns.map((qn) => qn.slug),\n    {\n      tocStart: 'TABLE_OF_CONTENTS:TOP:START',\n      tocEnd: 'TABLE_OF_CONTENTS:TOP:END',\n      qnsStart: 'QUESTIONS:TOP:START',\n      qnsEnd: 'QUESTIONS:TOP:END',\n      tableOfContentsAnchor: 'table-of-contents-top-questions',\n      showLinkToGFE: true,\n      sortByRanking: true,\n    },\n  );\n\n  const nonFeaturedQns = Object.values(questionsAll).flat();\n  await generateList(nonFeaturedQns, {\n    tocStart: 'TABLE_OF_CONTENTS:ALL:START',\n    tocEnd: 'TABLE_OF_CONTENTS:ALL:END',\n    qnsStart: 'QUESTIONS:ALL:START',\n    qnsEnd: 'QUESTIONS:ALL:END',\n    tableOfContentsAnchor: 'table-of-contents-all-questions',\n    showLinkToGFE: false,\n    sortByRanking: false,\n  });\n\n  const basicQns = qns.filter((qn) => qn.level === 'basic');\n  await generateBulletList(\n    basicQns.map((qn) => qn.slug),\n    {\n      qnsStart: 'QUESTIONS:BASIC:START',\n      qnsEnd: 'QUESTIONS:BASIC:END',\n    },\n  );\n\n  const intermediateQns = qns.filter((qn) => qn.level === 'intermediate');\n  await generateBulletList(\n    intermediateQns.map((qn) => qn.slug),\n    {\n      qnsStart: 'QUESTIONS:INTERMEDIATE:START',\n      qnsEnd: 'QUESTIONS:INTERMEDIATE:END',\n    },\n  );\n\n  const advancedQns = qns.filter((qn) => qn.level === 'advanced');\n  await generateBulletList(\n    advancedQns.map((qn) => qn.slug),\n    {\n      qnsStart: 'QUESTIONS:ADVANCED:START',\n      qnsEnd: 'QUESTIONS:ADVANCED:END',\n    },\n  );\n}\n\ngenerateAll();\n"
  },
  {
    "path": "scripts/rank.ts",
    "content": "import fs from 'fs';\nimport path from 'path';\nimport util from 'util';\nimport { QuestionMetadata } from './types';\n\nconst readFileAsync = util.promisify(fs.readFile);\n\nconst ranks = {\n  'explain-hoisting': 1,\n  'what-are-the-differences-between-variables-created-using-let-var-or-const': 2,\n  'what-is-the-difference-between-double-equal-and-triple-equal': 3,\n  'what-is-event-loop-what-is-the-difference-between-call-stack-and-task-queue': 4,\n  'explain-event-delegation': 5,\n  'explain-how-this-works-in-javascript': 6,\n  'describe-the-difference-between-a-cookie-sessionstorage-and-localstorage': 7,\n  'describe-the-difference-between-script-async-and-script-defer': 8,\n  'whats-the-difference-between-a-variable-that-is-null-undefined-or-undeclared-how-would-you-go-about-checking-for-any-of-these-states': 9,\n  'whats-the-difference-between-call-and-apply': 10,\n  'explain-function-prototype-bind': 11,\n  'what-advantage-is-there-for-using-the-arrow-syntax-for-a-method-in-a-constructor': 12,\n  'explain-how-prototypal-inheritance-works': 13,\n  'difference-between-function-person-var-person-person-and-var-person-new-person': 14,\n  'explain-the-differences-on-the-usage-of-foo-between-function-foo-and-var-foo-function': 15,\n  'whats-a-typical-use-case-for-anonymous-functions': 16,\n  'what-are-the-various-ways-to-create-objects-in-javascript': 17,\n  'what-is-a-closure-and-how-why-would-you-use-one': 18,\n  'what-is-the-definition-of-a-higher-order-function': 19,\n  'what-are-the-differences-between-es6-class-and-es5-function-constructors': 20,\n  'describe-event-bubbling': 21,\n  'describe-event-capturing': 22,\n  'what-is-the-difference-between-mouseenter-and-mouseover-event': 23,\n  'what-is-use-strict-what-are-the-advantages-and-disadvantages-to-using-it': 24,\n  'explain-the-difference-between-synchronous-and-asynchronous-functions': 25,\n  'what-are-the-pros-and-cons-of-using-promises-instead-of-callbacks': 26,\n  'explain-ajax-in-as-much-detail-as-possible': 27,\n  'what-are-the-advantages-and-disadvantages-of-using-ajax': 28,\n  'what-are-the-differences-between-xmlhttprequest-and-fetch': 29,\n  'how-do-you-abort-a-web-request-using-abortcontrollers': 30,\n  'what-are-javascript-polyfills-for': 31,\n  'why-is-extending-built-in-javascript-objects-not-a-good-idea': 32,\n  'why-is-it-in-general-a-good-idea-to-leave-the-global-scope-of-a-website-as-is-and-never-touch-it': 33,\n  'explain-the-differences-between-commonjs-modules-and-es-modules': 34,\n  'what-are-the-various-data-types-in-javascript': 35,\n  'what-language-constructs-do-you-use-for-iterating-over-object-properties-and-array-items': 36,\n  'what-are-the-benefits-of-using-spread-syntax-and-how-is-it-different-from-rest-syntax': 37,\n  'what-are-iterators-and-generators-and-what-are-they-used-for': 38,\n  'explain-the-difference-between-mutable-and-immutable-objects': 39,\n  'what-is-the-difference-between-a-map-object-and-a-plain-object-in-javascript': 40,\n  'what-are-the-differences-between-map-set-and-weakmap-weakset': 41,\n  'why-you-might-want-to-create-static-class-members': 42,\n  'what-are-symbols-used-for': 43,\n  'what-are-server-sent-events': 44,\n  'what-are-javascript-object-property-flags-and-descriptors': 45,\n  'what-are-javascript-object-getters-and-setters-for': 46,\n  'what-are-proxies-in-javascript-used-for': 47,\n  'what-tools-and-techniques-do-you-use-for-debugging-javascript-code': 48,\n  'what-are-workers-in-javascript-used-for': 49,\n  'how-does-javascript-garbage-collection-work': 50,\n};\n\nasync function rankQuestion(dirName: string, locale: string = 'en-US') {\n  const metadataPath = path.join('./questions', dirName, 'metadata.json');\n\n  const [metadataFile] = await Promise.all([readFileAsync(metadataPath)]);\n\n  const metadata: QuestionMetadata = JSON.parse(String(metadataFile));\n\n  if (!ranks[metadata.slug]) {\n    console.warn(`${metadataPath} does not have a rank`);\n    return null;\n  }\n\n  const newMetadata = { ...metadata, ranking: ranks[metadata.slug] * 10 };\n\n  fs.writeFileSync(metadataPath, JSON.stringify(newMetadata, null, 2) + '\\n');\n}\n\nasync function readQuestionsList() {\n  const qnSlugs = fs\n    .readdirSync('./questions', {\n      withFileTypes: true,\n    })\n    .filter((dirent) => dirent.isDirectory())\n    .map((dirent) => dirent.name);\n  return qnSlugs;\n}\n\nasync function rankQuestionList(qns: string[]) {\n  await Promise.all(qns.map((qnSlug) => rankQuestion(qnSlug)));\n}\n\nasync function generate() {\n  const qns = await readQuestionsList();\n  await rankQuestionList(qns);\n}\n\ngenerate();\n"
  },
  {
    "path": "scripts/types.ts",
    "content": "export type QuestionMetadata = Readonly<{\n  slug: string;\n  published: boolean;\n  ranking: number;\n  level: 'basic' | 'intermediate' | 'advanced';\n  importance: string;\n  featured: boolean;\n}>;\n\nexport type QuestionFrontmatter = Readonly<{\n  title: string;\n}>;\n\nexport type QuestionItem = Readonly<{\n  metadata: QuestionMetadata;\n  href: string;\n  title: string;\n  titleSlug: string;\n  locale: string;\n  content: string;\n}>;\n"
  }
]