Can Javascript be considered a interpreted language when using Google Chrome (V8)? - javascript

I was reading this excellent article on V8, Google's Javascript engine: https://developers.google.com/v8/design#mach_code.
At one point, they say that Javascript is compiled directly into machine language, without any bytecode or an interpreter.
To quote:
V8 compiles JavaScript source code directly into machine code when it
is first executed. There are no intermediate byte codes, no
interpreter.
So, why is Javascript still listed along with the "scripting" and "interpreted" languages, when it is clearly compiled (in V8, at least)?
Edit: can I somehow create an executable out of Javascript, if it is compiled? That would require somehow linking it to V8?
Considering that question, I found this quote:
V8 can run standalone, or can be embedded into any C++ application.
Here: http://code.google.com/p/v8/.

This is why "interpreted language" and "compiled language" are examples of sloppy terminology. Whether a language is compiled or interpreted is an attribute of an implementation, not of the language itself.
Many people confuse "dynamically typed languages" (like JavaScript) with "interpreted" and "statically typed language" with "compiled", but these are merely correlations rather than absolutes. It is possible to compile a dynamic language (although it's generally trickier than compiling a static one), and it's possible to interpret a static language (eg: Hugs is an interpreter for Haskell).

It is a scripting language because JS code is intended to be supplied and run as source code.
If the coder were to provide a compiled binary for you to execute, then it would not be a script.
Also, no matter what it does on Chrome, the same Javascript source code must also run in other platforms, which may be more or less of a traditional scripting environment. This also doesn't change the nature of the code itself of being a script.
Even if you go to the extreme of compiling it, JS is still a scripting language at heart. There are proper traditional compilers available for virtually every scripting language you can think of (Perl, PHP....); that doesn't stop them from being script languages, nor their source code from being a script.
Likewise, there are interpreters for many languages that are traditionally compiled.
Finally, the issue is further muddied by the concept of "compiling" one language into another. This has been around for a while, but the idea has really taken off with languages like Coffeescript that are intended to compile into Javascript. So what do you call the compiled Coffeescript code?
The terminology isn't really all that helpful, especially now, but the final answer to your question, in the context you're asking it, is that yes, Javascript is still a scripting language.

Here, let me demo the code:
exeFuncDefinedLater(100); // prove that js is a compiling language
function exeFuncDefinedLater(num) {
console.log("Your number is: " + num);
}
This piece of code could run both on Chrome Browser and Node js.
If anyone says that js is an interpreted language, then this piece of code would crash, as when u run later(), it should not know the later function body.
This could prove that js is a compiled language, as it compile later function (so machine could know it), then execute it.

Related

Javascript - Compiled language?

I am new to Web development, and I am studying JavaScript.
From a course at Stanford:
JavaScript is an interpreted language, not a compiled language. A program such as C++ or Java needs to be compiled before it is run. The source code is passed through a program called a compiler, which translates it into bytecode that the machine understands and can execute. In contrast, JavaScript has no compilation step. Instead, an interpreter in the browser reads over the JavaScript code, interprets each line, and runs it. More modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.
And from You Don't Know JS: Scope & Closures by Kyle Simpson:
... but despite the fact that JavaScript falls under the general category of “dynamic” or “interpreted” languages, it is in fact a compiled language.
Let’s just say, for simplicity sake, that any snippet of JavaScript has to be compiled before (usually right before!) it’s executed. So, the JS compiler will take the program var a = 2; and compile it first, and then be ready to execute it, usually right away.
And from some questions at Stack Overflow, there are some ideas like: It depend on an actual implementation of the language.
Do you have any ideas?
Chrome browser uses V8 engine for compiling Javascript just as other browsers may use Rhino Or SpiderMonkey.
V8 is a JavaScript engine built by Google written in C++. It is used for compiling JS, in both client-side (Google Chrome) and server-side (node.js) applications. In order to obtain speed, V8 translates JavaScript code into more efficient machine code instead of using an interpreter.
V8 compiles JavaScript code into machine code at script execution by implementing a JIT (Just-In-Time) compiler like a lot of modern JavaScript engines such as SpiderMonkey or Rhino (Mozilla) are doing. The main difference with V8 is that it doesn’t produce bytecode or any intermediate code. It just compiles JavaScript on the fly.
Hope this helps!
Well, you can probably get into semantics and terminology differences, but two important points:
Javascript (in a web page) is distributed in its source code form (or at least in minimized text form) and not as a binary compiled ahead-of-time
Javascript is not compiled into executable machine code even by the browser (although some parts of it may be these days as a performance optimization), but executed via a virtual machine
The term "compiled" used in this context refers to a language that is normally assumed to be translated directly into the language or format native to the machine it is going to be run on. Typical cases include both C and C++. But, understand that both of these languages can also be interpreted. An example of a C interpreter is Pico C, which handles a subset of C.
So, the real question is about environments. A language may be run in a compiled or interpreted environment. A clear distinction between the two cases can be made by the following test:
Does the language possess a "command level" mode
in which forward references are inherently impossible?
Think about this for a moment. A language that is interpreted is reading its specification in real time. A forward reference is to something that does not exist at the time the specification is made. Since machines have not (yet) been endowed with the facility of precognition or time travel (i.e. "time loop logic"), then such references are inherently unresolvable.
If such a level is defined as a mandatory part of the language, then the language may be said to be interpreted; otherwise, it may be said to be compiled. BASIC is interpreted, as some of its commands make direct reference to this layer (e.g. the "list" command). Similarly, the high-level AI language, Prolog, is - by this criterion - an interpreted language, since it also possesses commands that make direct reference to this layer. The "?-" command, itself, is an actual prompt, for instance; but its database commands also refer to and maintain the current state of the command-level layer.
However, this does not preclude parts of an interpreted language from being subject to compilation or to the methods used by compilers, or a compiled language from being run at a command mode level. In effect, that's what a debugger for a language like C or C++ already is, just to give an example.
Most languages that are defined to have a command level layer, normally have to compile to something. In particular, if the language satisfies the following condition, then it is almost mandatory that at least parts of it compile into something:
Does the language possess a facility for user-defined codelets,
for instance: subroutines, functions, lambdas, etc.?
The reason is simple: where are you going to put that code, after it's defined before it's used, and in what format? It is extremely inefficient to save and run it verbatim, so normally it will be translated into another form that is either: (a) a language-internal normal form (which which case, the rest of the language may be considered as "syntactic sugar" for the reduced subset language that the normal forms reside in), (b) into a language-external normal form (i.e. "byte-code"), or (c) a combination of both - it may do language-internal normalization first, before translating it into byte code.
So, most "interpreted" languages are compiled - into something. The only real question is: (1) what they are compiled into, and (2) when/how does the code that it is compiled into run - which is connected to the issue of the above-mentioned "command level" mode.
If the codelets are being compiled into a target-independent form - which is what is normally what is referred to when speaking of "byte code" - then it is not "compiled" in the sense the term is normally taken to refer to. The term compiled normally refers to translation into the language that is native to the machine that the language is being run on. In that case, there will be as many translators are there are types of machines that the language may run on - the translator is inherently machine-dependent.
The two cases are not mutually exclusive. So, a byte-code translator may appear as a stage for native-code compilation, whereby the codelets of an interpreted language are translated and stored directly in the native language of the machine that the language is being run on. That's called "Just In Time" compilation (or JIT).
The distinction is a bit blurry. Even compiled languages, like C or C++, may run on systems that have codelets that are either compiled or even pre-compiled that are loaded while the program is running.
I don't know enough about JS (yet) to say anything definitive about it - other than what can be inferred from observation.
First, since JS code is stored as codelets and is normally run in web clients on a need-to-use basis, it is likely that an implementation of will compile (or pre-compile) the codelets into an intermediate byte-code form.
Second, for reasons of security, it is unlikely that it will compile directly into the native code of the machine it is running on, since this may compromise the security of the machine by providing leaks through which malicious code can be sneaked into and through. That's the "sandbox" feature that browsers are supposed to adhere to.
Third, it is not normally used directly by a person on the other end as a language like Basic or even Prolog is used. However, in many (or even most) implementations it does have a "debug" mode. The browser, for instance, may allow even an ordinary user to both view and edit/debug JS code. Notwithstanding that, there really isn't a command-layer, per se, other than what appears in a web browser itself. Unresolved here is the question of whether the browser allows forward references in JS code. If it does, then it's not really a command level environment. But it may be browser-dependent. It might, for instance, load in an entire web page before ever starting up any JS code, rather than trying to run the JS in real time while a page is loading, in which case forward references would be possible.
Fourth, if the language wants to be efficient in terms of its execution speed, it will have some form of JIT - but this would require stringent validation of the JS compiler itself to ensure that nothing can slip out of the "sandbox" through the JIT into forbidden code on the host machine.
I'm pretty sure there are JS editors/interpreters out there, simply to have a way to develop JS. But I don't know if any references to a command-layer are a mandatory part of the specification for JS. If such specifications exist, then we can call it a bona fide interpreted language. Otherwise, it straddles the border line between the two language types as a language meant to be run in real time like an interpreted language, but which permits compilation directly to the native code of the machine it is running on.
The issue came to a head, for me, recently when I tried to directly translate an old stand-by text-based game (lunar lander) directly from the (interpreted) language FOCAL into C-BC (a C-like extension to POSIX BC whose source is located on GitHub here https://github.com/RockBrentwood/CBC). C-BC, like POSIX BC, is interpreted but allows user-defined codelets, so that implementations of BC normally define a "byte code" language to go with it (historically: this was "dc").
The FOCAL language has a run-time language - which theoretically could be compiled, but also a command-layer subset (e.g. the "library" or "erase" commands) which does not permit forward references that haven't yet been defined, though the run-time language permits forward references.
Unlike GNU-BC, C-BC has goto statements and labels, so it is possible to directly translate the game. However, at the command level (which in a BC file is the top level in the file's scope), this is not possible, since the the top-level of a file's code is - as far as a BC interpreter is concerned - making reference to things that might not yet exist, since the program could just as well have been being entered by a user in real-time. Instead, the entire source would have to be enclosed into { ... } brackets - which gets compiled, in its entirety, to byte-code first, before being executed. So, that's an example of a user-defined codelet, and a text-book example of why most interpreted languages have to have some facility for compiling into something.

How is dart2js code faster than javascript?

I'm trying to better understand dart's effect on performance. On the dart website, their benchmarks show that Dart code compiled to Javascript is faster than just Javascript. How is this possible?
I understand how the Dart VM is faster than v8, but what I don't get is how dart2js-generated javascript is faster than plain old javascript, when both are running in the same environment, v8.
dart2js is able to perform optimizations that would not normally be manually added in JavaScript code.
There is nothing particularly special about Dart being the source language in this case: any automated tool that generates JavaScript should be able to do this, for instance the GWT compiler (Java to JavaScript) does this as well. Of course, you can run automated tools on JavaScript source to generate better JavaScript as well, this is what the Closure compiler does.
Technically, you can manually achieve the same speed with handwritten JavaScript if you know all the tricks.
One example is function inlining. If you need a code fragment called repeatedly you would refactor it out in a function/method. Dart2js often does the opposite. Method calls often get replaced with the code fragment contained by the called function/method which is called inlining. If you would do this manually this would lead to unmaintainable code.
I think many of the optimizations go in that direction.
Writing the code that way would just be unreadable and thus unmaintainable.
This doesn't mean it's sloppy.
There is a great presentation by Vyacheslav Egorov from the dart team where he explains in detail some of the optimizations including in lining..
http://www.infoq.com/presentations/dart-compiler
Summary Vyacheslav Egorov details how some of Dart's language features affected the design of a new JIT Dart compiler and how the V8
JavaScript engine influenced the overall design.
There is an interesting video by Seth Ladd and Kasper Lund.
Kasper is involved in creating the Dart2js compiler and gives some code examples on how the compiler optimizes the Javascript code.

Writing optimised JS for asm.js

There is quite a bit of excitement on asm.js and how it will be able to run some very heavy applications. However, it is compiled from C++ code. Is it still possible to get the benefit of current improvements without knowing C++ or other low level languages?
Here is the thought that I had: Is it at all possible that we can write the code in Js, have it recompiled for asm.js for optimisation?
If you have small function that is very computation-heavy (crunching numbers rather than manipulating DOM) you could rewrite it in asm.js style yourself, manually. It's possible (I've done it), but tedious.
There are other asm.js compilers, e.g. LLJS that you may use instead of C++.
However, asm.js is not magic. You will only get performance benefit when you use language that is much better suited for ahead-of-time optimization than JS. You can't take fully-featured JS and make it faster by running JS VM on top of JS VM, just like you can't make ZIP files smaller by zipping them.
However, it is compiled from C++ code.
It is not. It's a language. Any program can emit text files which contain asm.js code. Emscripten compiles LLVM IR into asm.js, and there are compilers from C and C++ to LLVM IR, but this is only one possible way of getting asm.js code. Admittedly, it's currently the most mature, practical and popular way, but I would not be surprised at all if other asm.js compilers for other languages pop up some time in the future.
Is it still possible to get the benefit of current improvements without knowing C++ or other low level languages?
Well, in theory any language that can efficiently be compiled to machine code ahead-of-time can be implemented efficiently using asm.js, and that includes some rather high-level ones (e.g. Haskell).
But currently, nobody has a working implementation, and I don't expect this to ever become very popular. Right now, if you want asm.js performance, you'd probably write C or C++ code and compile it to asm.js, yes.
Note that the above excludes (among many others) Javascript.The fact that asm.js is a subset of Javascript is convenient in that asm.js code will run on unmodified browsers, but it's not of much use for anyone writing Javascript. asm.js is basically just a thin layer above machine code, with some amends for security and JS interoperability. Compiling JS to asm.js is as hard as compiling it to machine code: Easy if you don't give a damn about performance (just always used boxed dynamically-typed values like an interpreter, and emit calls to runtime library functions), very hard when you do.
In fact, after decades of research into the subject, there's still no example of a highly dynamic language like Javascript, Ruby or Python being compiled into machine code ahead of time and running much faster than a clever interpreter. Just-in-time compilation, on the other hand, is very much practical -- but the major JS engines already do that, in a less roundabout way than compiling to asm.js, then parsing it again and compiling it to machine code.
Asm.js isn't a separate language, but a subset of Javascript. It's just Javascript with a lot stripped out for performance. This means that you don't need to learn another language, though in this case knowing C/C++ might be useful to understand it.
Asm.js is a very strict subset of JavaScript, that can be generated relatively easily when compiling from C/C++ to JavaScript. Asm.js code is much closer to machine code than ordinary JavaScript code, which allowed browsers to heavily optimise for any code written in asm.js. In browsers that implemented those optimizations, your code will typically run about 50% of the speed of a C/C++ program that is compiled to machine code... which may seem slow, but is a hell of a lot faster than any ordinary JavaScript!
However, precisely because it's optimized for machines rather than humans, asm.js is practically impossible to handcode by any human developer... even though it's just JavaScript. While it is technically possible to convert - at least a subset of - ordinary JavaScript to an asm.js equivalent, such a conversion is not an easy task and I haven't encountered any project yet that made any attempt to achieve this.
Until someone achieves such a Herculean task, the best approach to producing asm.js code remains writing your code in C/C++ and converting it to JavaScript.
For more info on asm.js, see eg. John Resig's article from 2013 or the official specs.

Is there such a thing as a javascript compiler?

I'm wondering if its possible to write a javascript program and have it compiled and linked into an executable?
If so would it be possible to create a libjs that would be the equivalent of libc for the c/c++ world? wouldn't creating something like this make javascript a full fledged language that could then be compiled and run directly on the target hardware?
If you had a compiler for javascript, couldn't you write a new compiler in javascript?
Yes, you could write a js compiler. Not sure how popular it would be:
js engines are very fast these days, so you're not gaining much speed.
It would be platform specific, or you would have to support multiple platforms. Not pleasant.
What would it be useful for? The great thing about an interpreted language is the very fact that it doesn't need to be compiled. It shortens development cycles and build times (ever sat in front of a C program and had to change a file that the entire project relies on and had to run and rerun makes that take minutes to compile everything?).
Regarding your last point, you're correct. Had you one of these compilers, you could indeed write another one in javascript.
Read this ... and do not miss the comments.
Here are also some options.
Yes you have something called Google Closure Compiler but its not a compiler in the conventional sense,it doesnt convert javascript into machine code but converts javascript into javascript but highly optimized javascript. Its actually an optimizing compiler.Also the compiler runs some tests to detect errors like typos much like the tool JSLint.But Google advises to use this compiler on javascript written in Closure Library. see this for more on Closure Compiler.
But i dont think compiling client-side javascript to machine code is a good idea because machine code is machine dependent so then before you send javascript to the client you have to detects its OS and its processor architecture. So this would become like javascipt for firefox on linux,javascipt for firefox on windows,javascipt for firefox on x86,etc

Practicality of compiling another language to Javascript?

Recently several tools have been released such as pyjamas and Scheme2js that allow one to take code in a language such as Python or Scheme and compile it to Javascript.
But how practical is such a tool?
I could see debugging being quite painful as you would have to debug the compiled javascript code itself, and correlate any bugs in that code with the corresponding lines in the original python/scheme/etc source code. Even with an intelligent stack trace such as the pyjamas -d option provides, this still seems tedious.
Also, libraries such as jQuery make writing Javascript much more fun and productive. But for many developers Javascript is still a new language to learn.
Has anyone worked with compiled Javascript in a production environment? Any recommendations or comments on the practicality of compiling to Javascript instead of writing your code directly in Javascript?
I believe GWT, based on Java, may be the most popular product of this kind, though I wouldn't describing it as "compiling Java to JS" but rather as "generating JS code". While I personally share some of your doubts, and would rather code JS directly, I have to admit that it is indeed an extremely practical as well as popular tool, entirely production-ready: I observe that, internally, many web apps that are rich and complex enough to warrant a front-end / back-end split are more and more often ending up as a Python back-end and a Java front-end -- the latter specifically to allow GWT (of course there are also plenty of Python front-ends, and plenty of Python back-ends, but I think this is a trend).
Google Wave uses GWT and is probably the most talked-about web app using it so far; together with the huge number of GWT-using web apps listed here, I think it establishes beyond any doubt that the approach is practical (as well as popular;-). Whether it's optimal (vs. writing actual javascript with a good framework in support) is a harder question to answer.
One of the more heavily used JavaScript compilers is GWT. This compiles Java to JavaScript, and is definitely used in production. The web interface to Google Wave is written in this system.
Also, Skydeck wrote Ocamljs, in order to make it easy for them to write FireFox extensions. That also worked quite well.
In summary, if you can write a good compiler, there is no showstoppers keeping you from writing a good JavaScript compiler.
Google Web Toolkit does it (Java to Javascript compiling), and GWT is used widely by Google (duh) and many others, so it definitely is practical.
Since the code is autogenerated, you debug problems in Java - assumption that the problem is in your code, and not in the compiler code, is true in 99% of all cases.
List of languages that compile to JS
As an another example Haxe could be mentioned. Haxe is a independent language and compiles to Flash 6-10, JavaScript, NekoVM and also to c++ - source code. Why is this practical?
you could use features the language itself could not offer
recompile code on multiple platforms (e.g.: form check in JavaScript and on server side)
there is a remoting package for communication between the platforms, and its genius.
autocompletion through the compiler
compile time type checks
If you are interested, you could start reading here.

Categories