var

Before let, variables were declared using var, which was a common interview question such as variable promotion and the disadvantages of the for loop. Now that there are more reliable lets, the problem with var is documented here because of the older code.

Variable pollution problem

for(var i = 0; i<10; i++){}console.log(i); / / 10

if(true) {
  var b = 1;
}
console.log(b); / / 1
Copy the code

Like the code above, in for, if, or switch operations, we inadvertently create variables that pollute them, which is not desirable.

Use let to optimize:

for(let i = 0; i<10; i++){}console.log(i); // a is not defined

if(true) {
  let b = 1;
}
console.log(b); // b is not defined
Copy the code

Scoping problem

There’s a classic interview question I’ve been asked several times: How do I print 0-9 without changing the timer?

for(var i = 0; i < 10; i++){
  setTimeout(function(){
    console.log(i);
  }, 0)}// Print out 10 10s
Copy the code
  • Var creates a global variable. The “I” in the timer is already the “I” after the stacking of the “for” loop, so it gets 10. Let is the variable under the current scope, and the I in the timer is the I of each cycle, so it gets 0-9.

  • Create a closed scope range

for(var i = 0; i < 10; i++){
  (function(a){
    setTimeout(function(){
      console.log(a); // 得到0-9
    }, 0)
  })(i);
};
Copy the code

A let-like effect is achieved through a closed interval of self-executing functions, with I only in effect in the current scope.

= = and = = =

The == and === operators to verify equality exist in js.

  • = =Representing equal values
  • = = =Represents value and type are equal

Due to the existence of the double equal sign, there are some problems in the use, for example:

undefined= =null // true
false= ='0' // true
true= ='true' // false[] = =0 // true[] = =false // true
new Boolean('false') = =false // false
Copy the code

The reread front shows how to convert the double equal sign:

  • Undefined equal to null;
  • Strings and Booleans are converted to numbers and compared;
  • Convert the object to primitive and compare.

Sometimes when you do not know what type of data you will get, in order to strictly control the data type and possible bugs in the situation, it is still recommended to use third-grade judgment and compare the uncertain data you get after type conversion.

Semantic tag

HTML5 semantic tags are common, but rarely used. Commonly used examples:

h123456 p img a aside article nav header footer ... , etc.Copy the code

HTML is called hypertext Markup Language, which adds new presentation information to the original Notepad document to make the interface look richer and more layered.

Semantic tags are designed to specify which tags to use according to the book’s layout:

  • An ordered list
  • Unordered list
  • Main title
  • subtitle
  • Navigation – menu – Directory
  • Insert picture – Insert link
  • Bold – italic
  • And so on…

But most of my coding is div, SPAN, P, etc.

Here’s a quote from another reader:

Some of the points of semantic tags can make developers less likely to use them

1. Many semantic tags come with styles that we don’t need, so we need to cancel the default styles first, please.

2. Modern web pages are no longer structured according to the layout of books, and it is not easy to determine which semantic tags should be used for many page elements.

I agree with the second point, and I have not studied language typesetting in depth. Besides, nowadays, interface design is more diverse than books. In many places, I do not know what style should be used for typesetting, so I always use div and SPAN instead.

Summary of semantic tags: Use them appropriately (best) > Don’t use them (yeah) > Mess with them (forget it)

In fact, HTML is not an either-or language like serious programming languages. Some semantic uses can be controversial, so my advice is that you should try to use only the semantic tags you are familiar with, and only introduce semantic tags in certain situations. In this way, we can ensure that semantic tags are not abused and cause more problems.

Threads and processes

Windows processes can be viewed through the task manager.

  • A process is the smallest unit of CPU resource allocation
  • Thread is the smallest unit of CPU scheduling. A thread is the unit of a program run based on a process. There can be more than one thread in a process

A process is a factory, the factory has its independent resources – factories are independent of each other – threads are workers in the factory, multiple workers collaborate to complete a task – one or more workers within the factory – shared space between workers

Js is known as a single-threaded language, meaning it can only do one operation.

Browsers are multi-process, and each TAB page you open creates a separate process.

When you write the replacement tag

About replacing tags: after loading successfully, content will replace the original placeholder, such as IMG, video, audio, etc

About the IMG tag

For performance reasons, it is recommended to give the width and height of the image, because if the size of the replacement element changes after loading the file, it will trigger retypesetting. Img’s Alt attribute suggests a relatively friendly interaction when using a screen reader to access a page when an image fails to load.

Reactive images use the picture tag

<picture>
  <source srcset="image-wide.png" media="(min-width: 600px)">
  <source srcset="image-wide2.png" media="(min-width: 1200px)">
</picture>
Copy the code

The picture tag is more semantic and structured than replacing images with CSS media queries, and should be used with care if you want to work with older browsers.

Use source in video/audio

The video tag also supports the SRC attribute, but only one address can be entered. Different browsers support different video formats. Using the source tag allows the browser to select the supported video format to load. Also, the source tag is more purposeful and readable than using JS code to determine the browser vendor and version. Browser support is relatively good: Internet Explorer 9+, Firefox, Opera, Chrome, and Safari are supported.

<video controls="controls" >
  <source src="movie.webm" type="video/webm" >
  <source src="movie.ogg" type="video/ogg" >
  <source src="movie.mp4" type="video/mp4">
  You browser does not support video.
</video>
Copy the code

Refresh the page using location.href

Using location.reload() will refresh the page, and all resources (CSS, JS, IMG, etc.) on the page will be re-requested to the server. It is recommended to use location.href= “current page URL” instead of location.reload(). Using location.href browsers will read local cached resources.

Statement-expression

JavaScript follows the “statement-expression” structure of common programming languages, most of which are designed this way.

Record here oneself before not quite familiar knowledge point.

The var statements

  • Variables are promoted during precompilation
console.log(a); // undefiend
var a = 1;
Copy the code
  • Features: Through for, switch, if, etc
if(true) {
  var a = 1;
}
console.log(a); / / 1
Copy the code

Let and const statements

  • Applies only to the current scope and cannot be redeclared.
  • Variables declared by const cannot be modified.
  • There is no variable lifting problem.
  • Does not penetrate for, switch, if, etc

Function declaration

  • Precompilation phase improved
console.log(foo); // function
function foo() {};
Copy the code
  • There is no promotion in if
console.log(foo); // undefined
if(true) {
  function foo() {};
}
Copy the code

IIFE- A function expression that executes immediately

  • Used to generate scopes, for example:
for (var i = 0; i < 10; i++) {
  setTimeout(() = > {
    console.log(i); // Get 10 10s})}// use IIFE to get 0-9
for(var i = 0; i < 10; i++){
  (function(a){
    setTimeout(function(){
      console.log(a); / / get a 0-9
    }, 0)
  })(i);
};
Copy the code
  • Produces a read-only function name feature
var a = 1;
(function a() {
  console.log(a); // function
  a = 2; // The function name in the current scope is read-only and cannot be changed
  console.log(a); // function}) ();console.log(a); / / 1.
Copy the code

Event loop – Order of execution

Single thread

Js is single-threaded, which means that it can only do one thing at a time, meaning that all the task code needs to queue up for execution, and one task can be completed before the next one can be started. The queue of tasks is called a message queue. The repeated execution of tasks in the message queue is called an event loop.

Our JS code executes from the top down, but there will inevitably be some asynchronous operations, such as making Ajax requests and using timer operations. So how does JS handle asynchronous operations?

Take a look at the following code:

    console.log("a")
    let r = new Promise(function (resolve, reject) {
      console.log("b");
      resolve()
    });
    r.then(() = > console.log("c"));
    setTimeout(() = > { console.log("d")},0)
    setTimeout(() = > { console.log("e")},1000)
    console.log("f")
Copy the code

If you can’t reach an accurate conclusion in a short time, then you need to understand the event execution mechanism in JS.

Macro and micro tasks

For tasks in message queues, there are two types:

  • Macrotask: setTimeout, setInterval
  • Microtasks: Promise

A macro task contains a micro task. When a macro task is completed, the next macro task begins.

0. Start executing, find some code, put it in a macro task

  1. To perform a
  2. b
  3. Find the asynchronous operation THEN, which is a microtask, and add it to the queue of microtasks in the current macro task
  4. Found timer D, setTimeout belongs to macro task, added to macro task queue
  5. Found timer E, setTimeout belongs to macro task, added to macro task queue
  6. To perform the f
  7. The code has been executed, the microtask queue is executed, and c is printed out
  8. The microtask queue completes and starts executing the next macro task queue
  9. Just print d, no other microtasks, and start the next macro task queue
  10. Print e. All macro tasks are completed

The data type

Every value in the JavaScript language belongs to a certain data type. The JavaScript language specifies seven language types. According to the latest language standards, the seven language types are:

  • Undefined;
  • Null;
  • Boolean;
  • The String;
  • Number;
  • Symbol;
  • The Object.

The program logic consists of data type + running algorithm.