① How does JavaScript work? What is the difference between interpreted and compiled languages?

  1. -> Generate bytecode (V8) -> generate machine code (compiler)

  2. Many sources say that JavaScript, Python, and Ruby are “interpreted languages” implemented through interpreters. This is misleading: languages tend to define their abstract semantics rather than enforce implementations.

For example, C is generally considered a “compiled language,” but an interpreter for C exists, such as Ch. Similarly, C++ has an interpreter version of the implementation, such as Cint.

In fact, many interpreters are implemented internally in a “compiler + virtual machine” way, where the compiler converts the source code into AST or bytecode, and the virtual machine does the actual execution.

Conclusion:

  • An interpreted language does not eliminate compilation, but simply does not require the user to explicitly use the compiler to get executable code.

  • In fact, many interpreters are implemented internally in a “compiler + virtual machine” fashion. The process is as follows: source -> compiler -> AST or bytecode -> virtual machine to do the actual execution.

What is the process of compiling Babel?

A: First, Babel’s role is to go from one source code to another, acting as a conversion compiler, which can be summarized as parsing (parsing JS code) -> transforming (parsing and modifying AST) -> rebuilding (converting modified AST into another JS code)

③ How are arrays and functions in JavaScript stored in memory?

A: ① array, JS array is mainly in the form of continuous memory storage FixedArray, HashTable storage form HashTable.

② Functions, which belong to the reference data type, are stored in the heap, and only an address is stored in the stack memory to represent the reference to the heap memory. When the interpreter looks for a reference value, it first retrieves its address in the stack and then retrieves the entity from the heap.

** tips: **

  • Storage of reference types in memory [address in stack memory -> entity in heap memory] reason: reference type entities are large, relatively occupy memory space.
  • Storage of value types within stack memory

What is the event loop mechanism in the browser?

Answer: ① Event loop in browser:

Macrotasks:

  • Script (whole code)
  • setTimeout
  • setInterval
  • setImmediate
  • I/O
  • UI rendering
  • event listner

Microtasks:

  • process.nextTick
  • Promise.then
  • Object.observe
  • MutationObserver

In the browser, whenever a monitored event occurs, the associated task bound to the event listener is added to the callback queue. The tasks generated by events are asynchronous tasks. Common event tasks include:

  • Event tasks generated by user interaction events, such as input actions;
  • Event tasks generated by timers, such as setTimeout;
  • Event tasks generated by asynchronous requests, such as HTTP requests.

When the main thread runs, there are heap and stack, where the heap is the memory and the stack is the function call stack. As you can see, the Event Loop is responsible for executing code, collecting and processing events, and executing subtasks in the queue, including the following.

  • JavaScript has a main thread and a call stack, and all tasks end up on the call stack waiting for the main thread to execute.
  • Synchronization tasks are placed on the call stack and wait for the main thread to execute in sequence.
  • There is a callback queue outside the main thread, and the asynchronous tasks in the callback queue end up running in the main thread as a call stack.
  • Synchronous tasks are executed on the main thread, and the code in the stack calls the browser API while executing, which generates some asynchronous tasks.
  • The asynchronous task will place the asynchronous task and its associated callback function into the callback queue when it has a result (such as when a listened event occurs).
  • After the execution of tasks in the call stack is completed, the main thread is idle and obtains tasks from the callback queue for processing.
  • This process is repeated over and over again, and this is how JavaScript works. It’s called an Event Loop.
conclusion
  1. Js has a main thread and call stack. All tasks are eventually put on the call stack to wait for the main thread to execute.
  2. Macro task -> micro task – Macro task -> micro task repeats

⑤ What are the advantages of ES6 Modules over CommonJS?

  • The CommonJS module prints a copy of the value, the ES6 module prints a reference to the value. That is, ES6 Module is read-only and cannot change its value
  • The CommonJS module is run time loaded, and the ES6 module is compile time output interface
  • The CommonJS module require() is loaded synchronously, ES6 module import command is loaded asynchronously
  • The interface for import is read-only and cannot modify its variable value. CommonJS can be reassigned, but assigning to ES6 Module will compile an error.

ES6 Modules Advantage: CommonJS loads an object (the module.exports property) that is only generated when the script is finished running. ES6 Modules are not objects, and their interface is just a static definition that is generated during code static parsing.

⑥ How is a high-level programming language compiled into a machine language?

A: High-level language code -> parse into AST (during adjoint lexical analysis, syntax analysis)-> Generate bytecode (V8)-> generate machine code (compiler)

🀍 What are the phases of a compiler? At what stage is data type checking generally performed?

There are five stages:

  1. Lexical analysis 【 data type check 】 lexical analysis
  2. Parse phase: The V8 engine converts JS code to AST
  3. Ignition phase: The interpreter converts the AST to bytecode, and parsing the bytecode execution also provides the information needed for the next phase of optimized compilation;
  4. TurboFan stage: The compiler uses the information gathered in the previous stage to optimize bytecode into executable machine code;
  5. Orinoco stage: Garbage collection stage, where memory space that is no longer used in the program is reclaimed.

Process:

Js -> word/syntax check -> AST (via V8 engine) -> bytecode (via interpreter) -> machine code (via compiler) -> Garbage collection phase (memory collection that will no longer be used)

ⅷ What is the difference between publish/subscribe and Observer?

A: In observer mode, the observed usually maintains a list of observers. The observer is notified when the observed state changes.

In the publish-subscribe model, a specific publisher dynamically maintains a list of subscribers: notifications of events published to corresponding subscribers can be started or stopped at run time as required by the program.

The difference is that the publisher doesn’t maintain the subscription list itself (it doesn’t actively maintain a list like an observer), it delegates work to the specific publisher (equivalent to a secretary, anyone who wants to know about me can just ask my secretary); After receiving the message from the publisher, the subscriber delegates the specific subscriber to handle the relevant processing.

When will decorator mode be used? [👉🏻 : Extending the functionality of existing objects]

A: The decorator pattern generally allows you to dynamically add new functionality to an existing object without changing its structure, which is equivalent to wrapping an existing object.

There are many application scenarios, such as writing jQ projects before, you can quickly and dynamically expand the methods above jQ, or vUE’s custom instructions, mainly hoping to extend the old functions through inheritance.

What programming paradigms do you know?

A: Declarative, imperative (object-oriented OOP), functional FP

11. What is a sandbox? What does the browser sandbox do?

A: The purpose of the sandbox is to keep untrusted code running in an environment that limits its access to resources outside the quarantine zone.

12. What are the advantages and disadvantages of Hash and History routes?

A: The hash routing mode is implemented based on the following features:

  • The hash value in the URL is only a state of the client, that is, when a request is made to the server, the hash part will not be sent.
  • Changes to the hash value add a record to the browser’s access history. So we can switch the hash through the browser’s back and forward buttons;
  • You can use the a tag and set the href attribute. When the user clicks on the tag, the HASH value of the URL will change. Or use JavaScript to assign loaction.hash to change the HASH value of the URL.
  • We can use the HashChange event to listen for changes in the hash value to jump (render) the page. When vue/ React detects hash changes, load different components.
  • When the hashchange event is triggered, the event object has two attributes: the URL before the hash (oldURL) and the URL after the hash (newURL) :

demo

www.baidu.com/#a=0 When you change the hash value after # :

window.addEventListener('hashchange'.function(e) { console.log(e.oldURL);  console.log(e.newURL) },false);
Copy the code

The history routing pattern is implemented based on the following features:

  • PushState and repalceState apis to implement URL changes;
  • We can use the PopState event to listen for URL changes to jump (render) the page;
  • History.pushstate () or history.replacEstate () will not trigger the popState event, so we need to trigger the page jump (rendering) manually.

13. Can const arrays in JavaScript be pushed? Why is that?

A: Yes, you can also splice().

Const declaration creates a read-only reference to a value. This does not mean that the values it holds are immutable, just that variable identifiers cannot be reassigned. For example, in the case where the reference content is an object, this means that the object’s content can be changed.

14. What are the advantages and disadvantages of asynchronous apis Callback, Promise, Generator and Async?

A: First of all, callback is not an asynchronous API. It was a means of implementing ASYNCHRONOUS PROGRAMMING in the early days of JS.

Promise was a community solution to the problem of callback hell in the ES6 release;

Generator is also an asynchronous programming solution. The most important feature of Generator is that it can yield the execution of functions. Generator functions can be seen as containers for asynchronous tasks and use yield syntax to indicate where they need to be paused.

Async/await is a new asynchronous solution proposed in ES7. Async is the syntactic sugar of Generator functions. The advantage of Async/await is that the code is clear (unlike using promises where you need to write a lot of then method chains). Async /await is not only a way of asynchronous programming with JS, but also has readability close to synchronous code, making it easier to understand.

Async /await comes with an executor, whereas generators have no executor. You need to call next() manually

15. What is the difference between Object.defineProperty and ES6 Proxy?

A: The advantages of Proxy are as follows

  • The Proxy can listen directly on the entire object rather than on properties.
  • The Proxy can listen for changes to the array directly.
  • Proxy has 13 interception methods, such as ownKeys, deleteProperty, has, etc. Object. DefineProperty does not have.
  • Proxy returns a new Object. We can only manipulate the new Object to achieve our purpose. Object.defineproperty can only be modified by iterating through Object attributes.
  • Proxy as the new standard will receive the browser manufacturers focus on continuous performance optimization, the new standard is rumored to be a performance bonus.

Object.defineproperty has the following advantages

  • It has good compatibility and supports IE9, but Proxy has browser compatibility problems and cannot be smoothed by Polyfill.

Object.defineproperty falls short of:

  • Object.defineproperty can only hijack attributes of objects, so we need to traverse each attribute of each Object.
  • Object.defineproperty cannot listen on arrays. Listen on the array by overriding the seven methods that change the data.
  • Object.defineproperty also cannot listen for new es6 maps and sets.
  • Object.defineproperty also cannot listen for additions and deletions, and is reactive via vue.set () and vue.delete.