The seven data types of JS?

1. Undefined

Undefined means Undefined, and its type has only one value, Undefined. Any variable is of Undefined type before it is assigned, and the value is Undefined. In general, we can use the global variable undefined (the name of the variable undefined) to express this value, or void to make any expression undefined. In js, undefined is a variable, not a keyword, so to avoid tampering, it is recommended to use void 0 to obtain undefined.

2. Null

The Null type means defined but empty, so we do not define variables as undefined in our programming. This guarantees that all variables with undefined are never assigned. The Null type also has only one value, which is Null, and its semantics represent Null values. Null is the JS keyword, so you can safely use the null keyword to get the null value.

3. Boolean

The Boolean type has two values, true and false.

4. String

Coding format: blog.csdn.net/hongsong673…

String is used to represent text data. The meaning of String is not ‘String’, but the UTF16 encoding of the String. Our String operations charAt, length, and so on are for UTF16 encoding. The maximum length of a string is 2^53-1, but the length unit is a Unicode code point (a UTF16 unit), so the actual maximum length of a string is affected by the encoding length of the string. Be careful when handling characters outside the U+0000-U+FFFF range.

Once a string in JS is constructed, the contents of the string cannot be changed in any way, so strings have the characteristics of value types.

5. Number

The Number type in JS has 2^64-2^53+3 values. In addition to the double-precision floating-point number stipulation specified by IEEE754-2008, JS provides several exceptions in order to express several additional scenarios: NaN, Infinity, -infinity. The Number type cannot accurately represent integers outside the range -0x1FFFFFFFFF – 0x1FFFFFFFFFFF. The Number type cannot be compared using ===. (The Number type must be converted to binary first. Take the binary operation and convert it to decimal. Because the Number is a 64-bit double, the decimal part only has 52 digits, but 0.1 to binary is an infinite loop, so the accuracy loss occurs in rounding, so 0.1+0.2==0.3 is false).

6. Symbol

Symbol is a new type introduced by ES6. It is a collection of all non-string object keys. In the ES6 specification, the entire object system is remodeled with Symbol.

7. Object

In JavaScript, an object is defined as a “collection of properties.” Attributes are classified into data attributes and accessor attributes. Both are key-value structures. The key can be a string or a Symbol.

Type conversion: How does V8 achieve 1+ “2”?

In JavaScript, adding a number and a string returns a new string. This is because JavaScript thinks it makes sense to add a string and a number. V8 converts the number into a character and then performs the addition of the two strings, resulting in a new string.

In JavaScript, the type system is implemented according to the ECMAScript standard, so V8 executes strictly according to ECMAScript. In addition, V8 converts the object to a native string or number using the ToPrimitive function. During the conversion, ToPrimitive first calls the valueOf method on the object. If valueOf is not available, The toString method is called, and if neither vauleOf nor toString returns a value of the basic type, a TypeError error is raised.

Understand the object orientation of JS

In different programming languages, designers use different language features to abstract objects. The most successful genre is the ‘class’ way of describing objects. For example, C++ and Java are all class-based programming languages. There are also prototype-based programming languages that use archetypes to describe objects, as represented by JavaScript.

Class-based programming advocates the use of a development model that focuses on categories and relationships between classes. In this kind of language, there is always a class first, then an object is instantiated from the class, and there may be inheritance, combination and other relationships between classes. Classes, in turn, tend to integrate with the language’s type system, creating compile-time capabilities.

In contrast, prototype-based programming encourages the programmer to focus on the behavior of a set of object instances, and then to focus on how to divide those objects into the most recent prototype objects that are used in similar ways, rather than categorizing them into classes. The object oriented system based on prototype creates new objects by “copy”. The idea of “copy operation” in JS prototype system is: it does not really copy a prototype object, but makes the new object hold a reference to the prototype. Prototype systems are more compatible with highly dynamic languages and advocate prototype modification at runtime, which is also an important reason why JS authors choose prototype systems.

Every JS object must correspond to a stereotype object, and inherit properties and methods from the stereotype object. The value of an object’s __proto__ attribute is its corresponding prototype object. Read a property. If the object itself does not have one, access to the object’s stereotype continues until the stereotype is empty or found.

What is ES6? What’s the difference between ES5 and ES5?

  • Introduction of system library

Es5: You need to import the React package using require and make it into an object before you actually reference it.

Es6: You can use the import method to implement a system library reference directly without creating an extra library object

  • Export and reference a single class

Es5: To export a class to another module, module.exports is usually used. When referenced, it is still fetched by the require method;

Es6: You can use export Default to implement the same function and import using the import method

  • Components define methods internally

Es5: ###:function(); use a comma at the end of the method braces;

Es6: Omit the [:function] paragraph, and do not add a comma at the end to achieve separation.

  • Define the component’s property types and default properties

Es5: Property types and default properties are implemented via the propTypes member and the getDefaultProps methods, respectively (these two methods should be fixed-named;

Es6: Static members are used uniformly.

  • Block level scope keyword let, const

ES6 adds the let const command to declare local variables.

If a variable is declared using var, its scope is within the function in which the statement resides, and the phenomenon of variable promotion exists. The scope of a variable declared by a let is within the code block where the statement is located. There is no variable promotion. The variable can be used only after the let statement is executed. Let does not allow multiple declarations of the same variable in the same scope.

Const is a constant that cannot be changed in subsequent code. What const actually guarantees is not that the value of the variable cannot be changed, but that the data stored in the memory address to which the variable points cannot be changed. For data of simple types (numbers, strings, Booleans), the value is stored at the memory address that the variable points to and is therefore equivalent to a constant. But for complex type data (mainly objects and arrays), variable pointing to save memory address is a pointer to the actual data, const can guarantee the pointer is fixed (i.e., always points to the other a fixed address), as far as it is pointing to the data structure of variable, is completely unable to control.

const a = []; a.push('Hello'); // Run a = ['Dave']; / / an errorCopy the code

In the above code, the constant a is an array. The array itself is writable, but if another array is assigned to a, an error is reported. If you really want to freeze an Object, you should use the object.freeze method.

  • ES6 supports deconstructed assignments
  • ES6 supports Arrow functions

  • ES6 supports string templates

var name = “Bob”, time = “today”; `Hello{name}, how are you {time}? `

  • ES6 adds classes, constructor, extends, super, but is essentially syntactic sugar (which has no effect on the functionality of the language, making it easier for programmers to use at the time)
  • ES6 adds Promises

Promises are objects that deal with asynchronous operations. Promises allow you to organize code in a way that makes it more intuitive (similar to jQuery’s Deferred) in a chain of calls.

Javascript inheritance mechanism design idea?

www.ruanyifeng.com/blog/2011/0…

__proto__ (prototype);

www.zhihu.com/question/34…

An object has a property _proto_ that points to the prototype object of the object’s constructor. Think of it this way: every JavaScript object (except null) is created with another object, which we call a stereotype, and every object “inherits” properties from that stereotype.

In addition to _proto_, the function also has the property prototype. The function’s prototype property refers to an object that is the prototype of the instance created by calling the constructor.

JS implements several methods of inheritance

Segmentfault.com/a/119000001…

Juejin. Im/post / 684490…

  • Stereotype chain inheritance: the stereotype of a child type is an instance object of its parent type.

  • Constructor inheritance: Call () is used in the subtype constructor to call the parent type constructor.

  • Prototype chain + constructor combination inheritance: inherits the properties of the parent class by calling the constructor of the parent class and retains the advantages of passing parameters, and then achieves function reuse by using the instance of the parent class as the prototype of the child class.

  • Prototype inheritance: using an empty object as a mediator, assign an object directly to the prototype of the empty object constructor.

  • Parasitic inheritance: Enhances the object on the basis of the original type inheritance, returning the constructor.

  • Parasitic combinative inheritance: ES5 has an object.create () method that can replace the above Object method. Let B = object.create (A), A deep copy of A to generate B Object, B inherits all properties and methods of A, and then uses constructor inheritance to achieve parameter passing. This is the best way to do it, and this is how libraries do it.

  • Class inheritance in ES6.

Is everything in JS an object?

Juejin. Im/post / 684490…

Not everything in JavaScript is an object, but everything can act as an object.

The three basic types, string, number, and Boolean, are sometimes treated as wrapper types, and it’s easy to convert between the primitive value and the wrapper type: Primitive to wrapper type: new String(” ABC “) Wrapper type to primitive type: new String(“abc”).valueOf()

A primitive value like the String “ABC” is fundamentally different from a wrapper instance like new String (” ABC “). For example (using typeof and instanceof) : typeof “pet”; //”string” typeof new String(“pet”); //”object” “pet” instanceof String; // false new String(“pet”) instanceof String; // true “pet” === new String(“pet”); // false When a property or method is called on some basic type, JavaScript first converts it to a temporary wrapper object and accesses the property/method on it without affecting the original property.

Why is the value of Typeof (null) in JavaScript “object”?

www.zhihu.com/question/21…

This is a bug where the JS TYPE value is stored in a 32-bit unit. The 32 bits have 1-3 bits representing the TYPE TAG and the other bits representing the real value. The object marker bits are all zeros, and the lower three bits are exactly zeros. Use the integer −2^30 for undefined.

The difference between undefined and null in JS?

www.ruanyifeng.com/blog/2014/0…

What’s the difference between apply() and call()?

www.cnblogs.com/lengyuehuah…

Deep copy and shallow copy difference and JS how to achieve deep copy

www.cnblogs.com/echolun/p/7…

How to distinguish between A deep copy and A shallow copy, to put it simply, is to assume that B copies A, and when you modify A, see if B changes. If B also changes, it’s A shallow copy, and if B doesn’t change, it’s A deep copy.

What does the global function eval() do?

Eval () takes only one argument, and returns it directly if the argument passed is not a string. If the argument is a string, it compiles the string as javascript code. Raises a syntaxError exception if compilation fails. If the compilation is successful, the code starts executing and returns the value of the last expression or statement in the string, or undefined if the last expression or statement has no value. If the string throws an exception, the exception passes the call to eval().

Execution environment and scope chain in JavaScript

Github.com/nightn/fron…

The execution environment defines the environment in which the JS code runs. This execution environment includes the variables, objects, functions, and this that the JS code has access to.

The execution environment contains something called a variable object, which holds all the variables and functions defined in the environment.

Execution environments can be divided into three categories:

Global execution environment: This is the default environment in which the first line of JS code is executed. All global code is executed in this environment. Function execution environment: Each function has its own function execution environment. Whenever the JS engine finds a function call (note that it is a call, not a declaration), it creates a new function execution environment. Eval: The execution environment in the Eval function.

As mentioned earlier, each execution environment has a variable object (VO), and the variable objects contained in the function execution environment are called active objects (AO).

JS engine is divided into two processes when analyzing JS code, one is the compilation phase, the other is the execution phase. The compile phase deals with variable and function declarations in the code, and the execution phase starts executing specific statements. When the JS code is loaded, the JS engine first conducts the compilation phase of the code, and it will create the execution environment in this compilation phase, which is completed by the JS engine through three steps

Execution environment creation:

Create live object or variable object: live object is a special object in JS, it contains all the variables, function parameters and internal function declaration of the current execution environment. Unlike normal objects, live objects do not have a proto stereotype property. Create scope chain: After the active object is created, the JS engine will initialize the scope chain. The scope chain is actually a list of many variable objects, including all variable objects from the global execution environment to the current function execution environment. It is through this scope chain that the JS engine performs variable lookup.

Determining the value of this: After initializing the scope chain, the JS engine begins determining the value of this.

The JS engine will enter the execution phase after the compilation phase. In the execution phase, the JS engine will scan the code again, update the variable object, and execute the code.

Block-level scoping and Temporary Dead Zones (TDZ) in ES6

Juejin. Im/post / 684490…

ES6 divides execution environments into lexical environments and variable environments. The binding of let, const variable declarations, and var variable declarations in ES6 can be distinguished by two different procedures (lexical environments, variable environments). Both the creation of the scope chain and the creation of the variable object (VO) that is performed during the creation of the variable environment can be done during the creation of the lexical environment.

The difference between lexical environment and variable environment is: Variables declared as “let” and “const” have no value during the creation phase of the execution context. Variables declared as “var” are already “undefined” during the creation phase of the execution context. If you access variables declared as “var” during this phase, you normally get undefined. ReferenceError is reported: variable is not defined, and this phase is a temporary dead zone.

Event loops in JavaScript

zhuanlan.zhihu.com/p/33058983

The Event Loop is not provided by the ES language (that is, the ES specification does not provide a description of the Event Loop), it is provided by the ES hosting environment. ES provides only one heap (heap memory) and one stack (function call stack). The ES hosting environment also provides a Callback Queue. In simple terms, this callback queue is where the callback functions are waiting to be executed. For example, the setTimeout callback function, the Button click event handler, and so on. These callbacks are immediately queued when certain events are triggered (such as when a timer ends, a button is clicked). Note that they are queued immediately, not executed immediately.

When will a Callback in the Callback Queue be executed?

It waits for all tasks in the current execution stack to complete. When the main thread is idle, the main thread will look for any tasks in the event queue. If so, the main thread will fetch the first event, put the event callback on the stack, and then execute the synchronization code… “And so on and so on, thus forming an infinite cycle.

Technically, a Callback Queue does not hold functions, but messages, so a Callback Queue can also be called a message Queue. Each message has a function associated with it to process the message, which is called with the corresponding message as an input parameter.

Why does the code in a Promise execute before setTimeout?

When given a piece of JS code, the browser or node environment passes it to the JS engine and asks it to execute it. Before ES3, JS itself did not have the ability to execute code asynchronously, which means that the host environment passed a piece of code to THE JS engine, the engine will execute the code in order to complete, the task initiated by the host is called macro task. After ES5, PROMISES were introduced into JS, so that the JS engine itself can initiate tasks without the need for a browser to arrange them. The tasks it initiates are called micro-tasks.

The macro task queue is equivalent to an event loop. In the macro task, JS promise will also generate asynchronous code, which must be guaranteed to complete in a macro task. Therefore, each macro task contains a micro task queue.

With macro task and micro task mechanisms, we can implement JS engine level and host level tasks. For example, Promise is always added to the end of the micro task queue, and host apis such as setTimeout are added to the macro task queue.

The this keyword in JS?

Github.com/nightn/fron…

This refers to the object that called the function.

  1. Normal function calls, the function is called by the person, this is who.
  2. Constructor, if called directly without the new operator, refers to this to window. When an object instance is generated with the new operator, this refers to the newly generated object.
  3. Anonymous functions or functions that are not in any object point to Windows.
  4. If it is call, apply, etc., specify who this is.

Closures in JS

www.ruanyifeng.com/blog/2009/0…

Closures are functions that can read variables inside other functions.

Because in Javascript, only subfunctions inside a function can read local variables, you can simply think of closures as “functions defined inside a function.” So, in essence, a closure is a bridge between the inside of a function and the outside.

Closures can be used in many ways. It is useful for reading variables inside a function and for keeping their values in memory.