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

后端 未结 4 1839
夕颜
夕颜 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条回答
  •  情深已故
    2021-02-07 07:53

    Historically, JavaScript was an interpreted language. Which means an interpreter accepts the source code and executes it all in one step. The advantage here is simplicity and flexibility, but interpreters are very slow. Compilers convert the high level language into a lower level language that either the native processor or a VM (in this case, the Java VM) can execute directly. This is much faster.

    JavaScript in modern browsers is now compiled on the fly. So when the script is loaded, the first thing the JavaScript engine does is compile it into a bytecode and then execute it. The reason the entire compilation step is missing from the end user's perspective is because browser developers have (thankfully) maintained the requirement that JavaScript is not explicitly compiled.

    Java was from the getgo a language that always had an explicit compile step. But in many cases that's not true anymore. IDE's like IntelliJ or Eclipse can compile Java on the fly and in many cases remove the explicit compilation step.

提交回复
热议问题