I. What do you understand about Fetch and what are its strengths and weaknesses?
The Fetch API is a modern JavaScript interface for making web requests, designed as an alternative to the traditional XMLHttpRequest, providing a simpler, more flexible way to fetch resources and interact with servers. Below, I'll go over the pros and cons of Fetch.
Benefits of Fetch:
The syntax is simple and intuitive: Fetch uses a Promise-based mechanism , which makes the code more concise and easy to read . Compared to XMLHttpRequest, it avoids callback hell, which greatly improves code maintainability.
fetch('/data') .then(response => ()) .then(data => (data)) .catch(error => ('Error:', error));
Better readability and maintainability: Since Fetch is based on Promise, combining it with the async/await syntax can make asynchronous code look like synchronous code, further improving readability.
async function fetchData() { try { const response = await fetch('/data'); const data = await (); (data); } catch (error) { ('Error:', error); } }
Greater flexibility: Fetch provides a rich set of options (options), you can easily set the request method , headers , request body and so on.
fetch('/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: ({ key: 'value' }) });
Stream Processing: The Fetch API supports streaming processing of response bodies and can read response data incrementally, which is suitable for processing large files or real-time data.
fetch('/data') .then(response => { const reader = (); // Step-by-step data processing });
Fetch's shortcomings:
-
Progress monitoring is not supported: Unlike XMLHttpRequest, Fetch does not currently support native progress events (such as the
onprogress
), which makes it impossible to get progress updates when downloading or uploading large files. -
Compatibility with older browsers: Fetch is a modern API that is not supported by some older browsers (e.g. IE) and requires the use of polyfill to ensure compatibility.
-
Cookies are not sent by default: Fetch does not send cookies by default, you need to set them manually.
credentials
Options.
fetch('/data', { credentials: 'include' });
Error handling mechanism: Fetch's handling of network errors and HTTP errors (e.g., 404 or 500) requires special attention, as only network errors will trigger thecatch
and HTTP errors are still treated as successful requests.
fetch('/data') .then(response => { if (!) { throw new Error('Network response was not ok'); } return (); }) .catch(error => ('Error:', error));
Understanding let, const, and var in JavaScript
There are three main ways to declare variables in JavaScript:var
、let
cap (a poem)const
. Each of them has its unique characteristics and applicable scenarios. Below, I will describe the differences between them in detail.
1. var
var
is the earliest form of variable declaration introduced in JavaScript. It has the following characteristics:
-
function scope:
var
Declared variables are local inside the function and global outside the function. -
Variable promotion:
var
Declared variables are elevated to the top of the function or global scope, but variable initialization is not elevated. -
Repeatable statements: within the same scope.
var
Declared variables can be declared repeatedly.
function example() { (a); // undefined var a = 10; (a); // 10 } example();
2. let
let
was introduced in ES6 to declare block-scoped variables. It has several features:
-
block scope (computing):
let
Declared variables are valid within block-level scopes and do not pollute global scopes. -
Variable-free lifting:
let
Declared variables are not promoted and must be declared before they can be used. -
Non-repeatable declarations: within the same scope.
let
A declared variable cannot be declared repeatedly.
function example() { if (true) { let a = 10; (a); // 10 } (a); // ReferenceError: a is not defined } example();
3. const
const
was also introduced in ES6 for declaring constants. It has several features:
-
block scope (computing):
const
Declared variables are valid in block-level scope. -
variability:
const
Declared variables must be initialized at the time of declaration and may not be reassigned after initialization (except for objects and arrays, whose internal values are mutable). -
Non-repeatable declarations: within the same scope.
const
Declared variables cannot be declared repeatedly.
function example() { const a = 10; a = 20; // TypeError: Assignment to constant variable. const obj = { key: 'value' }; = 'new value'; // It's allowed. (); // 'new value' } example();