How does JavaScript work?

Time:2019-11-6

Abstract:Understand JS execution principle.

  • Original: how does JavaScript work?
  • Author: hengg

Fundebug is reprinted by authorization, and the copyright belongs to the original author.

What is JavaScript?

Let’s confirm the definition of javascript: Javascript is an interpretive dynamic language.

Interpretative languages exist relative to compiled languages. The source code is not directly compiled into the target code, but converted into intermediate code, which is interpreted and run by the interpreter.

The major programming languages are compiled (such as C + +), interpreted (such as JavaScript), and semi interpreted semi compiled (such as Java).

How does the code run?

First let’s see how the code works.

We know that the code is executed by the CPU, but the current CPU can not directly execute such asif…elseIt can only execute binary instructions. But binary instructions are so unfriendly to human beings: it’s hard for us to judge a binary instruction quickly and accurately1000010010101001What does it stand for? So scientists invented assembly language.

assembly language

Assembly language is actually the mnemonic of binary instruction.

hypothesis10101010Represents a read memory operation. The memory address is10101111, register address is11111010, then complete operation101010101010111111111010It means to read the value of a memory address and load it into a register. The assembly language does not change this way of operation. It is just a mapping of binary instructions:

LD:10101010 
id:10101111
R:11111010

In this way, the above instructions can be expressed asLD id R, greatly enhancing the readability of the code.

But it’s not friendly enough. The CPU can only execute three address expressions, which is far away from people’s thinking mode and language mode. So great scientists invented advanced languages.

High-level language

“The code is written for people to see, not for machines, but by the way, computers can execute it.”

Advanced language is called “advanced” because it is more in line with our thinking and reading habits.if…elseThis kind of statement looks better than1010101010It’s much more comfortable. But the computer can not directly execute the high-level language, so it needs to convert the high-level language into assembly language / machine instructions to execute. This process is compilation.

Does JavaScript need to be compiled?

JavaScript is undoubtedly a high-level language, so it must be compiled before it can be executed. But why do we call it interpretive language? What’s the difference between compiled language and semi interpreted semi compiled language? Let’s start with compilation.

Compile

We have known the concept of compilation before. Now let’s talk about the platform: the same C + + code will be compiled into. Obj files on windows, while. O files will be generated on Linux. The two cannot be used in general. This is because an executable file needs not only the code but also the operating system API, memory, thread, process and other system resources, and different operating systems have different implementations. For example, we are familiar with the I / O multiplexing (the soul of event driven), which is implemented by IOCP on windows and epoll on Linux. Therefore, for different platforms, compiled languages need to be compiled separately, or even written separately, and the format of the generated executable files is not the same.

Cross platform

Java goes further on this, it realizes cross platform operation by introducing bytecode: no matter what operating system. Java file compiles. Class file (this is bytecode file, an intermediate form of object code). Java then provides different Java virtual machines for different systems to interpret and execute bytecode files. Interpretation execution does not generate the target code, but it is finally converted to assembly / binary instructions for computer execution.

If we write a simple operating system independently, can it run Java? Obviously not, because there is no JVM for this system. So the cross platform of Java and any other language has its limitations.

The advantage of Java using half explanation and half compilation is that it greatly improves the development efficiency, but correspondingly reduces the code execution efficiency. After all, virtual machine has performance loss.

Interpretation execution

JavaScript goes a step further. It’s full interpretation execution, or just in time compilation. It will not have intermediate code generation, nor will it have object code generation. This process is usually performed by the host environment (such as browser, node. JS).

Compiling process

Now we’ve confirmed that even interpreting the language of execution requires compilation. So how is the code compiled? Let’s have a brief look.

lexical analysis

Lexical analysis decomposes statements into lexical units, which are tokens.

function square(n){
    return n*n;
}

This function will be recognized by the lexical analyzer asfunctionsquare(n){return,,n ,*n}And they are labeled to indicate whether this is a variable or an operation.

Syntax analysis

This process will convert token into abstract syntax tree (AST):

{
    type:'function',
    id:{
        type:'id'
        name:'square'
    },
    params:[
        {
            type:'id',
            name:'n'
        }
    ]
    ...
}

Optimization and code generation

In this step, the compiler will do some optimization work, such as deleting redundant operations, deleting unused assignments, merging some variables and so on, and finally generate the target code.

Because the compilation of an instant compiled language usually takes place a few microseconds before it runs, the compiler can’t do much optimization work. This is also one of the reasons for the weakness of early JavaScript performance compared to compiled languages. However, for now, the performance gap between JavaScript and other languages is insufficient for the benefit of the V8 engine (node.js can translate JavaScript into C + + code with the js2c tool provided by V8 compared with the earlier JavaScript engines that converted to bytecode or interpreted execution).

Linking and loading

The target code can hardly run independently. Applications are usually composed of several parts (modules), for example, a simple output in C + + will be introduced into the standard libraryiostream

#include 
using namespace std;
int main(){    
    cout << "Happy Hacking!\n";    
    return 0;
}

The compiler needs to link multiple object codes (Libraries) to generate executable files. At this point, we have a simple understanding of the compilation process. But in fact, compilation is much more complicated than what we said, so we will not expand it here.

What is dynamic language, dynamic type?

We also know that JavaScript is a dynamic language. So what is dynamic language?

Generally speaking, this refers to the language in which the code can change its structure according to certain conditions at runtime. For example, when JavaScript is running, new functions, objects and even code can be introduced (EVAL); for example, Objective-C can also modify objects at run time, but it cannot dynamically create classes or Eval methods. Is Objective-C a dynamic language? So I think dynamic language is a problem of degree. We don’t have to be too entangled in this concept. We can pay more attention to its application. The hot update function commonly used in app is based on the dynamic language features.

JavaScript is a dynamically typed language. What is a dynamically typed language? The definition of dynamic types is clear: data types are not determined at compile time, but at run time.

So what kind of language is typescript? It has static type checking. Is it a static language? It’s actually just a dialect of JavaScript. Typescript still needs to be translated into JavaScript to execute (TSC), just as we use Babel to translate ES6 code into Es5. This process is not strictly compilation.

The biggest advantage of typescript is static type checking and type inference, which is a serious lack of JavaScript. But in fact, if we ignore the error message given by the IDE and forcibly run TS code, there is still a chance that we can run successfully.

error

Just now we mentioned the error report, so we can expand to say the error. Generally speaking, errors are divided into the following categories:

  • Compile time error
  • Error linking
  • Runtime error

Is it strictly corresponding to the compilation process?

Compile time error

Compile time errors are divided into:

  • Syntax error

    var str ='s ;

    This is a typical syntax error. This kind of code cannot generate ast, and will report an error in the lexical analysis stage. Usually when we write code like this, the IDE will report an error. This is the optimization of IDE, which is related to lexical analysis.

  • error in type

    The compiler will check the types of variables and functions we declare, which we are familiar with in JavaScriptType Error:undefined is not objectIt’s such a mistake.

Error linking

Exception that occurred during the link phase. In this case, JavaScript is rare and common in compiled languages.

Runtime error

This is the most difficult mistake to check, for example:

int divider(int a,int b){
    return a/b;
}

The above code has no problem in editing, compiling and linking stages, and can generate executable files normally. But once used in this waydivider(1,0)This is a typical runtime error. In general, runtime errors are caused by the program being not robust enough.

The ten most common errors in javascript:

The figure below shows the JavaScript TOP10 errors collected and counted by an error processing platform, including 7 typeerrors and 1 referenceerror

How does JavaScript work?

Obviously, we can use typescript to deal with these eight problems in a timely manner in the early stage of coding.

epilogue

Now we know how JavaScript works. But can knowing this help us write better code?

The answer is yes. Not to mention that typescript can help us improve type checking and type inference, the scope and this of JavaScript are also strongly related to the compilation process; at present, the mainstream small program framework can support a set of code and multiple platforms. I believe that after reading this article, you have roughly understood the principles behind these technologies. Happy Hacking!

By the way, I would like to recommend fundebug, a good bug monitoring tool~

About fundebug

Fundebug focuses on real-time BUG monitoring of JavaScript, WeChat applets, WeChat games, Alipay applets, React Native, Node.js and Java online applications. Since the official launch on the double 11 of 2016, fundebug has handled 2 billion + error events in total. Paying customers include sunshine insurance, walnut programming, litchi FM, 1-on-1 leader, micro pulse, qingtuan club and many other brand enterprises. Welcome to try it for free!