Is there a technical reason on why we couldn't have a language like Java/C# integrated into the browser, instead of JavaScript?

11Responses

Write your response…

This answer has received 3 appreciations.

You can write in most languages in the browser right now, and it's getting easier and more popular as time goes by. There are many serious downsides, as well as compelling advantages.

Some downsides to using a different language:

  • JavaScript has, arguably, the worlds largest community for any programming language. It's easy to hire developers or find contributors for your OSS project.
  • JavaScript has NPM, an awesome repository of modules that can do almost everything you'd ever need. This is especially an advantage when prototyping.
  • Other languages have a tendency to die out, but JavaScript will always be with us.
  • The latest version of JavaScript is pretty good, and it only gets better every year. Is it really worth jumping ship to some niche language when JavaScript is probably going to catch up soon anyway?

Of course, there are benefits from using other languages. Most of them only show up with large, long-lived applications:

  • JavaScript doesn't have static types. A large app can feel like a ticking time bomb waiting to get in some inconsistent state and have a runtime error. Static types can catch many of these errors ahead of time.
  • JavaScript's flexibility means that it works with most programming styles, but specializes in none of them. Other languages have different opinionated rules and tools which can make your code more expressive and catch bugs earlier.
  • Other languages frequently offer more expressive syntax and data constructs which lets you write the same code in less lines.

There are three main categories of alternate languages to be aware of:

  • Languages that have JavaScript compilers.
  • Languages designed as alternatives to JavaScript
  • Languages that use Emscriptem, ASM.js, and/or Webassembly

Languages that have JavaScript compilers

JavaScript is popular enough that most major languages have tools to "compile" them to JavaScript. If you already "speak" one of these languages then they can be a great option to bring your existing code and expertise to the web.

Languages designed for JavaScript

Each of these languages were designed by very smart people with a JavaScript background to solve real-world problems. They are definitely not a good idea if you're making small apps, since ES2016 is pretty good anyway and you'll lose compatibility with the existing ecosystem. However if you're making a large webapp that's going to be used in production and have features added over time, then you should definitely consider these languages:

  • Dart is made by google and used by them for large projects.
  • CoffeeScript is an alternative syntax for JavaScript that is more concise and readable.
  • TypeScript Is a small addition to JavaScript that adds static types and better IDE tooling. It is 100% backwards compatible with JavaScript and has the potential for adding lots of productivity with no upfront cost.
  • Elm is a very cool language based on the functional-reactive style. It has an innovative data-handling model and no runtime exceptions.

There are more, but I'll stop there since those are the biggest.

Emscriptem, ASM.js, and Webassembly

TL;DR: If you want to make video games, write them with Unity and they'll run everywhere, including the web.

One big problem with all these "compile-to-js" languages is that Javascript is kinda slow. It is weakly typed and so the javascript engines have to do crazy on-the-fly recompilations as the data changes for maximum performance.

If only there was some kind of low-level language which we could run in the browser but which didn't need any kind of optimizing engine. Like an assembly language for the web.

Enter ASM.js: ASM.js is a very ugly subset of javascript that looks like this:

function strlen(ptr) {
  ptr = ptr|0;
  var curr = 0;
  curr = ptr;
  while (MEM8[curr]|0 != 0) {
    curr = (curr + 1)|0;
  }
  return (curr - ptr)|0;
}

Notice all the |0? Those are valid Javascript which casts the values to integers. A smart JavaScript engine will pick up on that and produce much faster code. ASM.js also does some other things like manually managing it's own memory in a TypedArray which means no pauses for Garbage Collection. With these optimizations paired with a browser that's also been optimized for ASM.js, you can usually get within 1/2 the performance of native code.

Another important tool is Emscriptem which compiles C/C++ code to ASM.js. (I'm simplifying here. Go check it out if you want the full story.) Thanks to the great performance of ASM.js, people have been able to compile entire video games for the browser. In fact, Unity, which is one of the most popular video game engines, can export to asm.js as one of it's official targets!

ASM.js is just about as far as you can push regular JavaScript. But thankfully, the browser vendors have come together to give us something even better: WebAssembly.

WebAssembly is a cross-platform assembly language that's safe to run with untrusted code. This means that, someday soon, almost any language will be able to compile for the browser without sacrificing speed or having subtle quirks due to JavaScript's limitations.

The future is bright for assembly languages on the web. ASM.js already works in all modern browsers and WebAssembly works in Firefox Nightly and Chrome Canary. If you want to have a taste of the future go check out this video game demo which has both ASM.js and WebAssembly versions.

If you want to be a web developer

If you're looking to get into front end development, then JavaScript is still the way to go. JavaScript is one of the few languages that actually has a job deficit, so it's a very good career move.

Whatever company you get a job for will probably already have decided whether to use vanilla JS or some other language, and won't be interested in changing. If they use some alternate language, then their strategy will probably be to hire JS developers and train them in.

No. Javascript is the current "official" language because of historical reasons.

I just wanted to make it clear that you can use other languages, but just have to be aware of the tradeoffs.

Write a reply...

This answer has received 1 appreciation.

TL;DR: Because, standards.

One of the biggest pain point among front-end developers is cross-browser compatibility; and nothing would get them more enraged than seeing a browser deviate from a standard. If I had a nickel for every time I heard @alkshendra and @fazlerocks curse IE <9, I would have amassed quite a good amount of fortune. :)

As @jiyinyiyong pointed it out, a browser doing things "uniquely" is a big no; it fragments the concept of "open" web. If one browser does it, all browsers should fall in line, and it would mean the creation of a new standard, which is a long and painful process. On a related note, see @leaverou's answer to Why does it take so long for new specs to get browser adoption?

Google did propose an addition of support for multiple VMs into Webkit. One of the comments in the thread hits it spot on:

Previous branches have been used to bring up interestingly complicated features, or features that had the potential to cause dramatic stability issues during their early work (such as the old svg-experimental branch). This project appear to be largely a make work project as it's already possible to have bindings for multiple languages (as the C++, GLib, ObjC, V8 and JSC bindings demonstrate).

It seems an academic exercise to see if we can create a general architecture to make more bindings, as is exporting support for proprietary extensions like vbscript, python or dart to the web. As the 90s demonstrated such "features" are bad for developers, and bad for the open web. This may not be apparent to people who have not spent years working in the environment but random additions frequently cause significant pain down the road, even in the cases where the overall result was a "good" thing -- such as canvas - for the subsequent standardisation caused us quite a bit of compatibility problems, even though it was a very compact and contained api.

— Oliver

Write a reply...

This answer has received 2 appreciations.

A lot of answers are pretty good but miss the core of the question: why did we end up with JS specifically?

Originally there was only HTML. The arrival of JS even pre-dates that of CSS, to the extent that at some point there were actual plans to create a styling language based on JS (JSSS = JavaScript Style Sheets, not to be confused with JSS which is a recent styling library for JS).

The history of JS has been explored in great detail elsewhere but the important takeaways are that back when "the web" was split between Netscape and Microsoft, Netscape wanted to create a scripting language for web pages around the same time Sun tried to establish Java as the universal language for writing real applications.

At the time "build cross-platform applications" and "breathe life into web pages" were two different problem sets and the licensing deal that resulted in JS being marketed as "JavaScript" so Sun would let it live alongside the Java plugin for Netscape is an example of how deep the divide ran.

Web pages are HTML documents, no sane person would try to create applications with that, right? At the time the primary use cases for JS were doing mouseover effects on images, creating popup windows and animating the status bar (before someone found a way to exploit that feature for nefarious purposes and browsers no longer supported it).

But Java (and Shockwave/Flash) were inherently limited by living inside their opaque sandboxes where JS could access the entire page. Meddling with JS was also very easy because there was no need for compilation or expensive software. It was also "not a real programming language" so non-programmers had less barriers to dip their toes in or copy code snippets from their peers.

Let's emphasise that: Java and Shockwave and Flash were not competitors to JS. "Real programmers" didn't like JS. It was just a "scripting language" for "scripting web pages" so designers could add some interactivity to their "pretty pictures". The only direct competitor was VBScript and VBScript was only supported by Microsoft (who also supported a reverse engineered clone of JavaScript called JScript).

Ultimately standards are what helped JS survive and flourish. Standards helped nip the threat of fragmentation (e.g. via JScript) in the bud. But what gave JS the initial edge was simply the contempt "real programmers" had for "scripting languages" and the inclusive environment this created for beginners as well as the ability to instantly see the effect of your experiments.

Write a reply...

This answer has received 1 appreciation.

Technical reasons? Not really. But human/political reasons definitely. The history of JavaScript is a great yarn, both Eich and Crockford tell it pretty well (https://www.youtube.com/watch?v=t7_5-XYrkqg and https://www.youtube.com/watch?v=Rj49rmc01Hs) and it should give an idea of the sort of games that were being played.

From an author's point of view - the web was created in the early days by a ton of people, only a handful of whom were Serious Programmers(tm) who liked Java. You can write a few lines of HTML and JavaScript in a text file, run it in a browser and it works. That was never the case with Java and there may not be much reason beyond that. Barring the obvious one, that most web people I know hate writing Java as much as Java people hate writing JavaScript.

As a sidenote I think ease of use also played a huge part in PHP's success, because it was so commonly installed on web servers you could just rename your .html files .php and suddenly you could do new and awesome tricks! ;) People didn't care about the purity of language, they were too busy making stuff in the crazy wild west of the web.

The funny thing of course is that JavaScript gets more like Java all the time, in ways both superficial and substantial. Most React projects don't run in the browser, the source code has to be converted into something that runs in the browser.

Which is basically where Web Assembly comes in - if you're transpiling into a target language you basically never see, why not make that language faster?

I don't see the average author writing things directly in wasm; although I will probably be wrong ;) I think we're entering a period of time where people will write whatever language they like and transpile it into JavaScript (and eventually wasm) during deployment.

To put it another way: nobody who hates JavaScript has to write it any more, so it barely matters why Java didn't "win". Anyone who wishes Java won can still write Java for the server, or find some flavour of x-to-javascript that suits them.

Write a reply...

The primary "technical" reason is that the web platform is in a transitional phase as far as foundational technologies required for cross language support are concerned.

NPAPI (plagued by security issues) is well on its way towards deprecation, and WebAssembly is still in its infancy.

Once WebAssembly matures and is more widely supported it is inevitable that ecosystems will evolve around frameworks and libraries targeting the web in various languages. In fact, rust community is actively working on preliminary support for WebAssembly.

Alternative route is to compile languages to javascript target. There are of course lot of languages that do this today, eg. there is Bridge.NET for C#, JSweet and GWT for Java, Opal for ruby, Transcrypt for python etc. However, the primary issue is that none of these languages were originally intended to be compiled to javascript and hence when they are ported to javascript the implementations end up being subtly different from the original implementations and/or the runtime characteristics end up being quite different from the original language. And porting the libraries in the ecosystem is almost always a very cumbersome endeavour.

The major problematic aspect, that is always present when you write interop layers to target javascript libraries, is that you invariably introduce a second layer of abstraction that beginners have to struggle with.

Sure you can use React with Opal and the integration layer works really well (I have used it myself) but if a beginner is trying to learn react through opal it is almost double the effort because he/she will first have to understand the original react concepts (which are explained through javascript API references) and then would have to learn how to apply these concepts through the Opal interface, which has a lost of subtly different characteristics (underscored names, different way to associate event handlers, block oriented DSL rather than JSX etc.).

To be fair, none of these subtleties are bad per se, because without them the usage will not be idiomatic ruby, but it is undeniable that they add a cost to learning curve.

The above is explicitly not a criticism towards immense work that has gone into libraries like hyperloop. To their credit, getting started with hyperloop requires adding just a few dependencies to a Gemfile and your asset processing pipeline is up and running in seconds. When I first tried it I was amazed as to how frictionless the initial experience was compared to things like webpack.

But having said that, the ground reality is that unless there is a strong commercial incentive, no one puts in the effort to maintain exhaustive parallel documentations for interop layers that mirror each release of wrapped libraries.

This is precisely the reason why it is extremely unlikely that these ecosystems will ever catch on with the popularity and momentum that javascript ecosystem has.

Write a reply...

Thing is, every browser, the big ones, like Chrome, Firefox, InternetExplorer, as well as the small ones, like Lync, Midori, etc. all have to be able to display your site. So, people went ahead and thought about it. What kind of information should be important enough so that every browser should be able to handle it? And those smart people decided, that HTML (not Jade or JSON or...) and CSS (not Sass, Less, etc.) and JS (not Ruby, C#, etc) should be that minimum standard which has to be supported by all browsers so a website can be displayed correctly. While that is one decision on standards, no one hinders you to use a different language for the web. Go ahead and use C#! But you will see, that unless you get C# standardized, normale people with mainstream browsers will not be able to execute your scripts.

Standardizing a new language is a very painful procedure. It includes explaining, why the language in question is better suited to the web than JavaScript. Is it because you prefer that language? Then screw you! No one cares about your opinion! That might sound harsh, but the only thing which is relevant to the world is facts. If you present facts to W3C which proof that your language is good enough for the web, they might accept it (a thing at which Google and Microsoft and many others failed...).

So, the thing is: JavaScript was chosen as a standard, because of reasons. You either accept the standard and build a site which everyone can view, or you do lots of research and explain to the world, why an interpreter for a different language should be included in every major browser. That's quite hard, and you will have to proof definite shortcomings of JavaScript , or rather ECMAScript (which cannot be overcome by a standard update, like ES8), which make the existence of a different programming language in a browser plausible for normal conditions (no special cases allowed).

@niagr Wheter JavaScript is a good language and fitting for the web or not is not really open for discussion anymore. It's a standard, so it will be used. Fighting that standard today might require a life-long and very hard fight against many big companies and many important people, which would yield no real benefit for any of us. JavaScript is OK as a language and there are quite a few people (me included) who really like it! As for why it was selected as a standard in the first place, @chilimatic already gave you the answer :)

Write a reply...

Waiting for WebAssembly - the dreams are coming true

Cheers !

Write a reply...

I found a really good write up on a persons experience with Java vs other standard web languages.

https://www.quora.com/Why-is-Java-NOT-used-for-web-front-end-rather-than-PHP-Python-Ruby-etc-in-sites-like-Facebook-Quora-Twitter

Write a reply...

Not sure I can compete with the some of the excellent detail already provided, but I think, for me, it boils down to compiled languages versus interpreted/scripted ones.

Websites, needing to be platform agnostic (and the evolving list of browsers ever growing), were always going to favour the latter to stand any chance of adoption.

Javascript briefly contested this title with VBScript, but has long been king on the client-side, hence it's increasingly broad adoption. Server side scripting is, of course, a slightly different battle, but results in pure HTML (and JS) arriving at the client browser.

Interestingly, new kids on the block like Typescript, a lot closer to traditional high level (compiled) languages, still rely heavily upon ECMAScript standards to produce bundled i.e. compiled JS.

Write a reply...

Well, for java you have the applets i think if you need some extra functionality, or flash too. But i think the point of the browser is keep things clear.

Write a reply...

I guess one reason may be caused by the fact that web browsers are not provided by only one company so no one is allowed to use a closed language for his own only profits.

Write a reply...

Join a friendly and inclusive Q&A network for coders

  • 🖥Pick the technologies you like & read great content through your feed.
  • 💬Ask a question when you want to learn more about anything.
  • 🚀Share what you know & build your portfolio.
Sign up nowLearn more

loading ...