Why does Java code need to be compiled but JavaScript code does not

后端 未结 4 1842
夕颜
夕颜 2021-02-07 06:53

How come code written in Java needs to be compiled in byte-code that is interpreted by the JVM, but code written in a language like JavaScript does not need to be compiled and c

4条回答
  •  梦毁少年i
    2021-02-07 07:53

    Any language can be compiled and interpreted. In both cases, a piece of software has to read the source code, split it up, parse it, etc. to check certain requirements and then assign a meaning to every part of the program. The only difference is that the compiler then proceeds to generate code with (almost) the same meaning in another language (JVM bytecode, or JavaScript, or machine code, or something entirely else) while the interpreter carries out the meaning of the program immediately.

    Now, in practice it's both simpler and more complicated. It's simpler in many languages lend themselves better to one of the two - Java is statically-typed and there is relatively little dynamic about the meaning of a program, so you can compile it and thus do some work which would otherwise need to be done at runtime. JavaScript is dynamically-typed and you can't decide a lot of things (such as whether + is addition or concatenation) until runtime, so compilation does not afford you much performance. However, a mix of compiler and interpreter (compile to simplified intermediate representation, then interpret and/or compile that) is increasingly popular among dynamic language implementations. And then there's the fact that modern JavaScript implementations do compile, and in fact V8 never interprets anything.

提交回复
热议问题