Title 1: How to improve JavaScript technology capabilities?

Author: Zen and the Art of Computer Programming

1. Introduction

With technological innovation and the booming development of the industry, more and more people are paying attention to and understanding the related technologies and knowledge in the field of front-end development. Front-end engineer positions are also constantly expanding, and many excellent companies have turned to front-end development. As a qualified front-end engineer, you must have the corresponding skills and knowledge to cope with increasingly complex business needs. This article will combine my actual experience and learning results to share some aspects, methodologies and technical routes that I think will help improve JavaScript technical capabilities. The article will cover the following aspects:

  1. Basic concepts and terminology
  2. Data Structures and Algorithms
  3. Browser-side JavaScript API
  4. Node.js programming practices
  5. HTTP request and response handling
  6. Modularization and componentization practices
  7. Functional Programming vs. Reactive Programming
  8. Command mode and chain of responsibility mode
  9. WebAssembly language implementation
  10. Asynchronous programming technology implementation
  11. Debugging techniques and tool usage
  12. Continuous integration/deployment tool configuration and use
  13. Web security protection measures
  14. testing technology

These knowledge points and technical abilities are essential for front-end engineers. However, due to limited personal abilities, there may inevitably be errors or omissions, and everyone is welcome to correct them!

2. Explanation of basic concept terms

2.1 HTML

HTML (HyperText Markup Language) is Hypertext Markup Language. It is the basic language for building web pages. All web page documents need to be written in accordance with HTML standards. Its main function is to define the structure, style, behavior, etc. of the page content through tags, so that the browser can correctly display the content of the web page, and also provide rich interactive functions for the web page.

2.2 CSS

CSS (Cascading Style Sheets) is a cascading style sheet, used to control the layout and appearance of web pages. Generally, various effects can be added to HTML elements through CSS, such as font color, font size, border, background color, gradient, shadow, animation, etc. The cascading nature of CSS allows multiple CSS rules to be applied to the same element to achieve different effects.

2.3 JavaScript

JavaScript is a lightweight scripting language used to dynamically update web page content, increase user interaction and control client programs. It is widely used in web page production, mobile application development, server-side application development and other fields. It is also a must-have programming language for front-end engineers.

2.3.1 ECMAScript

ECMAScript is the core specification of JavaScript, which specifies JavaScript’s syntax, types, statements, operators, etc. in detail. Currently, there are two versions of ECMAScript, ES5 and ES6.

2.3.2 DOM (Document Object Model)

DOM (Document Object Model) is a model and API recommended by the W3C organization for processing extensible markup languages. It defines how to get the structure of data from XML or HTML and allows access, modification and deletion of data. DOM provides JavaScript with powerful processing capabilities so that the structure and content of web pages can be dynamically manipulated.

2.3.3 BOM (Browser Object Model)

BOM (Browser Object Model) is the browser object model recommended by the W3C organization. It provides properties and methods related to browser windows and documents that allow JavaScript to interact with the browser. For example, you can obtain screen size, cookies, location information, network status and other information through the BOM.

2.3.4 AJAX (Asynchronous JavaScript And XML)

AJAX is a new web development technology that uses the XMLHttpRequest object to get data from the server and then uses JavaScript to dynamically update parts of the content on the page without reloading the entire page. This can not only save server resources, but also improve user efficiency.

2.3.5 Promise

Promise is an object in JavaScript used to encapsulate the results of asynchronous operations. It has the following characteristics:

  • The status of an object can be Pending, Fulfilled, or Rejected.
  • Once the state changes, it never changes again.
  • Through the callback function, the result of the asynchronous operation is passed to the next step.

    2.3.6 Module (module)

    Module is a concept in JavaScript, which defines a set of related functions and can be shared through import and export .

    2.3.7 CommonJS

    CommonJS is the JavaScript module system standard, which defines the interfaces of each module through module definition specifications. In NodeJS, you can use require() and exports keywords to import and export modules.

    2.3.8 AMD (Asynchronous Module Definition)

    AMD is a module definition specification based on CommonJS. It allows asynchronous loading of modules in web pages, thereby improving performance. In the RequireJS framework, you can use define() and require() to load modules.

    2.3.9 jQuery

    jQuery is one of the most popular JavaScript libraries that provides a very useful API for easily manipulating the DOM. In jQuery, you can use selectors, events, animations, Ajax, and more.

    2.3.10 TypeScript

    TypeScript is an open source project launched by Microsoft. It is a superset of JavaScript and adds a type checking mechanism to help developers catch runtime errors. At the same time, it supports modularity and can better manage large projects.

    2.3.11 Vue.js

    Vue.js is a progressive framework developed in JavaScript. It consists of two parts: MVVM mode (Model-View-ViewModel) and Virtual DOM. It can greatly improve coding efficiency and development efficiency, and is suitable for complex single-page applications.

    2.3.12 React

    React is a JavaScript front-end framework launched by Facebook, which can be used to build high-performance user interfaces. It applies componentization ideas to the view layer and draws on some design concepts from other frameworks. Its JSX plug-in supports writing HTML code directly, making the development process smoother.

    3. Data Structure and Algorithm

    3.1 Array

    Array (Array) stores multiple values For collections, you can access elements in the array by index. Arrays in JavaScript support dynamic resizing, so there is no need to specify the size and can be expanded according to actual conditions. You can use a for…of loop to iterate over all elements in an array, or use the forEach method to iterate over all elements in an array.

    let arr = [1, 'a', true];
    

// Use for…of to loop through the array for(let item of arr){ console.log(item); // Output 1 a true }

// Use the forEach method to traverse the array arr.forEach((item, index, array) => { console.log(Item ${index + 1}: ${item}); });

## 3.2 Linked List
Linked List is a linear data structure. The linked list is composed of nodes. Each node stores the data value and the reference address pointing to the next node. Linked lists can make full use of memory space and overcome the shortcomings of arrays that can only be arranged sequentially.
### 3.2.1 One-way linked list
A one-way linked list (Singly LinkedList) is the simplest form of a linked list. Each node only saves the data value of the current node and does not save the pointer of the next node.


### 3.2.2 Doubly linked list
In addition to saving the data value of the current node, a doubly linked list (Doubly LinkedList) also saves the pointer of the previous node.


## 3.3 Stack Stack
Stack is a linear data structure. The top of the stack saves the last entered element. When the element is popped, the latest entered element becomes the new top of the stack. Stacks can be implemented using arrays or linked lists.
### 3.3.1 Stack application scenarios
The application scenarios of the stack are very wide, common ones include:

1. Base conversion
2. Bracket matching
3. Function call stack
4. Browser forward and backward history

## 3.4 Queue Queue
Queue is another linear data structure. The queue is a first-in-first-out (FIFO) linear table structure, that is, the latest entered element must be queued at the end of the queue. Queues can also be implemented using arrays or linked lists.
### 3.4.1 Queue application scenarios
The application scenarios of queues are also very wide, common ones include:

1. Production and consumption model
2. Task scheduling
3. CPU scheduling
4. Thread pool

## 3.5 Hash Table Hash Table
Hash Table is a data structure used to store key-value pairs. Its characteristic is to quickly find elements. In a hash table, when an element is stored, the calculated hash code is used as an index to store the element in the array. Through the index, you can quickly find the corresponding element.
### 3.5.1 Operation time complexity
- Search operation: O(1) average time complexity; O(n) worst time complexity, conflicts will occur with a very small probability
- Add operation: O(1) average time complexity; O(n) worst time complexity, conflicts will occur with a very small probability
- Deletion operation: O(1) average time complexity; O(n) worst time complexity, conflicts will occur with a very small probability
### 3.5.2 Hash conflict resolution
#### Open addressing method
Open Addressing is a simple and effective conflict resolution strategy. When a conflict occurs, a certain rule is used to detect whether the address is empty until a free position is found to insert the element. The main problem with the open addressing method is that aggregation may occur, resulting in a waste of space.


#### Zipper method
Chaining is a method of storing elements with the same hash value into a linked list. When a conflict occurs, the element is inserted into the head of the linked list.


## 3.6 Sorting Sorting
Sorting is a method used to sort a set of data. It is divided into internal sorting and external sorting.
### 3.6.1 Internal Sorting Internal Sorting
Internal Sorting means that the data is sorted completely in memory, so it takes up less memory space. Typical algorithms for internal sorting include quick sort, merge sort, radix sort, etc.

QuickSort is one of the most popular internal sorting algorithms at present. It is a recursive algorithm and is faster than other internal sorting algorithms.

Merge Sort is a divide-and-conquer method that splits an array into two half-arrays, sorts the two half-arrays separately, and then merges the two sorted arrays.

Radix Sort is a non-comparison sorting algorithm, which is based on bitwise sorting of integers.

### 3.6.2 External Sorting External Sorting
External Sorting means that the data is stored on the disk, so it takes up a large amount of memory space. Typical algorithms for external sorting include merge sorting, massive data processing, etc.

### 3.6.3 Stable Sorting Stable Sorting
Stable Sorting means that the relative positions of equal elements remain unchanged after sorting. For example, bubble sort, insertion sort, and merge sort are all stable sorting algorithms.

However, counting sort and bucket sort are not stable sorting algorithms.

# 4. Browser-side JavaScript API
## 4.1 Document Object Model (DOM)
DOM (Document Object Model) is a model and API recommended by the W3C organization for processing extensible markup languages. It defines how to get the structure of data from XML or HTML and allows access, modification and deletion of data. DOM provides JavaScript with powerful processing capabilities so that the structure and content of web pages can be dynamically manipulated.

document.getElementById(): Get the element node through the id attribute.
document.getElementsByTagName(): Get the element node list by tag name.
element.getAttribute(): Get the attribute value of the element node.
element.setAttribute(): Set the attribute value of the element node.
element.appendChild(): Appends a child node to the end of the child node list of an element node.
element.insertBefore(): Insert a child node at any position in the child node list of an element node.
element.removeChild(): Removes the child nodes of an element node.
element.cloneNode(): Copy an element node.
window.setTimeout(): Delay execution of the specified function.
window.setInterval(): Execute the specified function regularly.
event.stopPropagation(): prevents events from bubbling.
event.preventDefault(): Prevent default events.
## 4.2 Browser Object Model (BOM)
BOM (Browser Object Model) is the browser object model recommended by the W3C organization. It provides properties and methods related to browser windows and documents that allow JavaScript to interact with the browser. For example, you can obtain screen size, cookies, location information, network status and other information through the BOM.

window.alert(): pops up a warning box.
window.confirm(): pops up a confirmation box.
window.prompt(): pops up the input box.
window.location.href: Get the current page URL.
window.history.back(): Go back to the previous page.
window.history.forward(): Forward to the next page.
navigator.userAgent: Get the browser's userAgent.
navigator.language: Get the browser's language.
navigator.platform: Get the operating system platform.
navigator.appName: Get the browser name.
navigator.appVersion: Get the browser version.
screen.width / screen.height: Get the screen width and height.
window.innerWidth / window.innerHeight: Get the width and height of the current window.
## 4.3 Local Storage
localStorage is a localStorage object that can be used to store data persistently. Unless cleared manually, the data will still exist after the browser is closed.

localStorage.setItem('key', value): Set the key-value pair in localStorage.
localStorage.getItem('key'): Get the value corresponding to key in localStorage.
localStorage.removeItem('key'): Delete the value corresponding to key in localStorage.
localStorage.clear(): Clear localStorage.
## 4.4 Session Storage
sessionStorage is similar to localStorage, and is also used to store data persistently, but sessionStorage is only valid for the current session, and the data disappears automatically when the session ends.

sessionStorage.setItem('key', value): Set the key-value pair in sessionStorage.
sessionStorage.getItem('key'): Get the value corresponding to key in sessionStorage.
sessionStorage.removeItem('key'): Delete the value corresponding to key in sessionStorage.
sessionStorage.clear(): Clear sessionStorage.
## 4.5 IndexedDB
IndexedDB is an advanced database technology that provides indexing, transactions, queries, sorting and other functions. Through it, a large amount of data can be stored locally in the browser, and it has the characteristics of fast query speed, support for offline storage, and strong fault tolerance.

indexedDB.open(): Open or create IndexedDB.
dbInstance.transaction(): Start a transaction.
objectStore.add(): Add data to objectStore.
objectStore.delete(): Delete data.
objectStore.put(): Update data.
objectStore.get(): Get data.
objectStore.getAll(): Get all data.
## 4.6 Fetch API
The Fetch API is a JavaScript API for handling HTTP communications and can be used to send Ajax requests.

fetch('/api')
 .then(response => response.json())
 .then(data => console.log(data))
 .catch(error => console.error(error));
## 4.7 WebSockets
WebSocket is a communication protocol that implements full-duplex communication between the browser and the server. Through WebSocket, the client can receive data from the server in real time and can also send data to the server.

const ws = new WebSocket("ws://localhost:8080");

ws.onmessage = event => {
  const data = JSON.parse(event.data);
  console.log(data);
};

ws.onerror = error => {
  console.error(error);
};

ws.send(JSON.stringify({ message: "Hello World!" }));
## 4.8 Canvas API
Canvas is a new technology in HTML5, which provides an interface for drawing images and animations. It allows you to generate, modify, and save dynamic images on web pages, as well as interact with background data.

canvas.getContext("2d"): Get canvas context.
context.fillStyle = "red";: Set the fill color.
context.fillRect(x, y, width, height): Draw a rectangle.
context.strokeStyle = "blue";: Set the stroke color.
context.beginPath();: Start path.
context.arc(x, y, radius, startAngle, endAngle, anticlockwise): Draw an arc.
context.lineTo(x, y): Connect line segments.
context.fill(): fill area.
context.closePath(): Close the path.
context.rotate(angle): Rotate.
context.scale(x, y): scaling.
context.translate(x, y): Translation.
context.clip(): clipping.
## 4.9 SVG API
SVG (Scalable Vector Graphics) is a vector-based graphics format that can be used to present complex vector graphics and is scalable. With SVG, you can create graphics, animations, charts, primitives, interactions, and more.

svg.createElement(): Create an element.
elem.setAttribute(): Set the attribute of the element.
elem.appendChild(): Add elements.
elem.addEventListener(): Bind event listener.
document.body.appendChild(svg): Adds the svg element to the page.
## 4.10 File API
File API is a new set of file operation interfaces in HTML5, which can be used to read, write, copy, compress, and decompress files.

FileReader(): Create a FileReader object.
fileReader.readAsDataURL(): Read the file content and return base64 encoding.
Blob(): Creates a Blob object.
fileWriter.write(): Write file content.
compression.compress(): Compress files.
compression.decompress(): Decompress the file.
## 4.11 Geolocation API
Geolocation API is a positioning technology in HTML5 that can be used to obtain the user's latitude and longitude information.

navigator.geolocation.getCurrentPosition(position => {
  console.log(`Latitude is :${position.coords.latitude},Longitude is :${position.coords.longitude}`);
}, error => {
  console.log(error);
});
## 4.12 Drag and Drop API
Drag and Drop API is a new drag-and-drop technology in HTML5, which can be used to implement the function of drag-and-drop uploading files.

const dropZone = document.getElementById("drop-zone");

dropZone.ondragover = e => {
  e.preventDefault();
};

dropZone.ondrop = e => {
  e.preventDefault();

  const files = e.dataTransfer.files;

  uploadFiles(files);
};

function uploadFiles(files) {
  const formData = new FormData();

  for (let i = 0; i < files.length; i + + ) {
    const file = files[i];

    formData.append("files[]", file);
  }

  fetch("/upload", { method: "POST", body: formData })
   .then(res => res.text())
   .then(text => console.log(text))
   .catch(err => console.error(err));
}
# 5.Node.js programming practice
## 5.1 Install Node.js
Node.js is a JavaScript runtime environment based on the Chrome V8 engine, which allows JavaScript code to run on the server side. To install Node.js, you need to install the latest LTS version (long-term support version) first, and then configure the environment variables.

Download: https://nodejs.org/en/download/

Installation: After the installation is completed, you need to restart the computer to make the environment variables take effect.

Configure environment variables: right-click "My Computer", select "Properties", click the "Advanced System Settings" button, select the "Environment Variables" button, and add the node installation directory under the Path of the system variable. If the installation directory is in C:\Program Files\
odejs, you need to add the C:\Program Files\
odejs\
ode-vXX.X.X-win-x64 folder to the Path variable, where XX.X.X represents the version of Node.js.

Verify that the installation is successful: Enter node -v in the command prompt to check the Node.js version.

Upgrade the npm package manager: npm install -g npm@latest
## 5.2 Create the first Node.js program
Below is a Node.js program for Hello World!.

```javascript
console.log("Hello World!");

Save as hello.js. Then execute the following command in the command prompt:

node hello.js

You can see the output: “Hello World!”.

5.3 Express Framework

Express is a web application framework based on Node.js that provides a series of powerful features, such as:

  • MVC architectural pattern
  • Extensible routing
  • Powerful HTTP tools
  • Integrated view template engine
  • Support RESTful API
  • Flexible plug-in system
  • More……

The general process of developing web applications using Express is as follows:

  1. Install Express: npm install express –save
  2. Introduce Express: var express = require(‘express’);
  3. Create an Express app: var app = express();
  4. Configure middleware: app.use(/* middleware */);
  5. Set routing: app.route(/* path /)./ methods */;
  6. Start the Express application: app.listen(portNumber, function(){ /* callback */ });

Here is a simple Express application:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

The above example shows a basic Express application with only a GET request route ‘/’ and the response content is “Hello World!”.

For more information about the usage of Express, please refer to the official documentation: http://www.expressjs.com.cn/guide/routing.html

5.4 MongoDB database

MongoDB is a NoSQL database based on distributed file storage and supports distributed ACID transactions.

The general process of developing web applications using MongoDB is as follows:

  1. Install MongoDB: https://docs.mongodb.com/manual/administration/install-community/
  2. Configure the database: Configure the mongod.conf file (the windows installation package will automatically complete this step).
  3. Start the MongoDB service: bin\mongod.exe –config mongodb.conf
  4. Create a database: mongo –eval “db=db.getSiblingDB(‘test’)”
  5. Connect to the database: mongo test
  6. Create a collection: db.createCollection(“mycollection”)
  7. Insert data: db.mycollection.insert({“name”:”John”})
  8. Query data: db.mycollection.find().pretty()

MongoDB official documentation: https://docs.mongodb.com/manual/introduction/

5.5 Redis database

Redis is a high-performance, non-relational database that supports a variety of data structures, including strings, hash tables, sets, sorted sets, bitmaps, hyperloglogs, and geospatial index services.

The general process of developing web applications using Redis is as follows:

  1. Install Redis: https://redis.io/download
  2. Start the Redis service: redis-server.exe redis.windows.conf
  3. Connect to Redis server: redis-cli.exe
  4. Execute command: SET myKey someValue

For more information about the usage of Redis, please refer to the official documentation: https://redis.io/documentation

5.6 MySQL database

MySQL is a relational database launched by Oracle. It supports SQL language and multiple data structures, including:

  • Relational Database
  • embedded database
  • NoSQL database

The general process of developing web applications using MySQL is as follows:

  1. Install MySQL: https://dev.mysql.com/downloads/mysql/
  2. Start the MySQL service: mysqld.exe
  3. Create database: CREATE DATABASE dbName DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  4. Connect to the database: mysql -u root -p passwordOfRootUser
  5. Create a table: CREATE TABLE table_name (column_name column_type constraint,… );
  6. Insert data: INSERT INTO table_name (column1, column2,…) VALUES (‘value1’, ‘value2’,…);
  7. Query data: SELECT * FROM table_name WHERE condition;

For more information about the usage of MySQL, please refer to the official documentation: https://dev.mysql.com/doc/refman/8.0/en/