7

This is not a simple question, but I was thinking, what advantages are really there in the JavaScript language?

We all use JavaScript on the browser, of course, there is no other choice (you can use transpilers, but in the end its still javascript), and I know, it's a relatively easy language to learn, but, imagine we could use any language instead of JavaScript, in which situation would JavaScript still be a better choice? Not only in the browser, but on other places too?

I don't want to consider the community and the libraries around the language, or its learning curve. I want to consider the language itself. What can JavaScript do that other languages can't, or what JavaScript does better than most others?

Don't take me wrong, I love javascript and work with it every day, but I couldn't answer that question.

Thanks!

closed as primarily opinion-based by James McLeod, gnat, Philipp, Ampt, Steven Burnap Mar 12 '15 at 19:52

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 36
    You basically hit on it already. JavaScript is essentially the Comcast of programming languages: no matter how much it sucks, you really don't have much of a choice but to use it for a specific domain, because it's the only game in town. – Mason Wheeler Mar 12 '15 at 3:48
  • @gbjbaanb I suddenly have flashbacks to Netscape Enterprise Server from '94... back in the youthful days of JavaScript and its, well, specifications would be too strong a word. – user40980 Mar 12 '15 at 13:39
  • 6
    As someone whose main work is in JavaScript, I completely agree. It's like C++, or Democracy - It's the worst language, except there's no good alternatives. (Although like C++, I get the sense once someone is a pro, often they'll be misguided into believing its systems make sense, and chastise people who get confused and/or try to twist the language) – Katana314 Mar 12 '15 at 13:48
  • @Katana314 There are plenty of good alternatives, with the one exception of web browsers. – Andy Mar 12 '15 at 16:41
  • 1
    It was up against VB Script back, what can I say – John Mar 12 '15 at 16:44
13

In the early days of Netscape, there was a new technology that was all the rage. Java. This wasn't the Java that we know and love (for some definition of 'love') today, but rather Java Applets.

Java applets had a serious flaw though - they couldn't interact with the page that enclosed them. This severly limited their utility. And so, the makers of the leading web browser at the time took it upon themselves to write a simple scripting language that was embedded within the browser that would be able to bridge the gap between the page itself and the applet. And thus JavaScript was born.

The key role of JavaScript in those days was to be able to invoke methods in the applet container and also be able to be invoked by the applet itself... and some DOM tinkering to make that interaction useful. It was based on a very simple functionalish language with some syntax that wasn't foreign to the Java coders it was courting.

Read the above again. The thing JavaScript provided was interaction with Java applets in the web page. No other languages did this.

And that is why JavaScript and not Python or Perl or TCL or any of its contemporary scripting languages is in the browser. Those other scripting languages weren't designed with this bridge in mind and grafting that bridge into the language involved too much modification to those languages - and whats more, they were outside of the control of Netscape.

So, for back then...

  • It was a small language that provided a key piece of browser technology at a critical time
  • Lots of people learned it as part of the browser stack

So what does it do better now? Being easy to access and accessible for new programmers and provide rapid feedback for doing visible things (doing things on a web page) that hasn't been around since the days of low res graphics in Basic in the early '80s. Sure you can do neat things with Python or Lua or Ruby... but you can't just toss it in a web page and say "look what I did" the way you can with JavaScript. Everyone who has a computer or smart phone can see it and appreciate what was done.

5

Javascript ressembles a Scheme like language, with a different syntax, a weird prototype semantics, and ugly rules (like for evaluation of {} + [] etc...). It was probably (for economical and social reasons) under-specified and under-designed. Later, the common implementation (inside browsers) became a de facto standard and inspired the more official specifications.

Once Javascript appeared in the Web landscape, it has been tried and has grown because of an extenality - the business network of all the corporations using it. Once a lot of people is using it, there is not enough incentive to replace it by something better.

Scheme (and Common Lisp) and Python have their advantages (but I prefer Scheme syntax over Javascript's).

For example, DSSSL was heavily inspired by Scheme.

4

The question is actually two questions rolled into one:

  • Why a scripting language?
  • Of all scripting languages, why javascript?

Why a scripting language?

The major idea behind the use of scripting languages is this:

Applications often need customization, and some times the level of customization offered by options and styles is not enough. By including a scripting language in your application you allow your users to heavily customize your application, without having to give them the source code of your application and without forcing them to learn and use software development tools like compilers.

Also, scripting languages generally have the advantage of being highly self-contained. Adding a scripting language to any application is relatively easy: you instantiate some scripting engine within your program, you give it a series of interfaces that will be visible by the scripts, and then you give it a script to run. The script is (for all practical purposes) physically incapable of accessing any functionality of your execution environment other than the interfaces that you supplied.

Also, scripting languages are generally more high-level than regular programming languages, meaning that they are somewhat more removed from the actual machine. (Scripting language programmers are generally not concerned with how many bits long their ints are.) This, in combination with their high level of containment, makes scripting languages highly portable: if you keep the interfaces available to your script minimal, then all you need to do in order to make your scripts runnable on a multitude of operating environments out there is to implement those minimal interfaces on each targeted operating environment.

All this makes scripting languages ideal for running on browsers, which are native to all sorts of diverse systems out there, and where you obviously do not want potentially malicious code downloaded from any place that you visit on the web to have access to your computer. So, javascript running on a browser generally has a very small view of the world; basically, its entire world usually consists of the document model of the current page, plus a few other services for communicating with the interwebz, usually with the server from which the script originated. Contrast this with a real language, which generally comes together with rich libraries that (fortunately or unfortunately, this is not the right place for this discussion,) allow code to do pretty much anything it pleases on the machine on which it is running.

Of all scripting languages, why javascript?

That having been said, the question of why javascript in particular still remains. I suppose that the answer to this question is a lot less technical. It probably only has to do with history and politics.

Javascript was invented by a USAian, who at the time was working for Netscape, which at the time was the one company making the one browser that everyone was using to access that brand new thing known as the internet. So, it caught on. When microsoft launched their own browser shortly thereafter, they tried to play the same trick with a scripting language of their own invention: vbscript. Luckily, it flopped.

Python was available at around the same time as javascript, (if not slightly earlier,) but its creator was Dutch, and he was not affiliated with any major companies at that time, so that's probably the only reason why our browsers are (unfortunately) running javascript instead of Python.

-2

I don't want to consider the community and the libraries around the language, or its learning curve. I want to consider the language itself. What can JavaScript do that other languages can't, or what JavaScript does better than most others?

One of the merits of JS is that - compared to something like LUA or 'simpler' scripting languages - it's pretty hard to find something that's not possible to do in JS. It might (will?) be awkward, complex, and a very hard to use, but you generally will be able to build a library that does what you want.

Besides that, Javascript is an abomination of a language. It is very hard to master, and basic concepts like scoping, iteration or truthiness are dodgy at best. From a language standpoint, it (imho) doesn't compare favorably to ruby, python, or groovy - at whatever level you want to use it.

However, because of browsers and HTML, Javascript developers are all over the place. So if you want to expose a scripting layer, it's a more pragmatic solution that going with an (arguably) better language for which you can't find developers.

Unfortunately, that's not an answer on the merit of the language itself...

  • 2
    " it's pretty hard to find something that's not possible to do in JS" Well that's true in any language really. – Andy Mar 12 '15 at 17:29
  • @Andy Right. What I meant by that is that while they're awkward, JS has namespaces, scoping, objects, function pointers, recursion, functional as well as declarative programming paradigms, dynamic evals, etc. Compare to 'simpler' languages designed for embedding (eg. LUA, Basic, VB) it is rich enough to build complex abstractions. Consider that list: codegolf.stackexchange.com/questions/44680/…, there are plenty of languages that fall in the 'too simplistic' category. JS doesn't. – ptyx Mar 12 '15 at 18:33
-2

What can JavaScript do that other languages can't, or what JavaScript does better than most others?

JavaScript has first-class functions with lexical closures. That makes it quite powerful.

You can leverage the functional programming paradigm. For instance, rather than doing:

var array = [1, 2, 3, 4, 5],
    results = [],
    index,
    iteree;

for (index = 0; index < array.length; index += 1) {
    iteree = array[index];
    if (iteree % 2 === 0) {
        results.push(iteree);
    }
}

You can do:

var array = [1, 2, 3, 4, 5],
    results = array.filter(function (iteree) {
        return iteree % 2 === 0;
    });

You can write event-based systems:

element.addEventListener('click', function (event) {
    console.log('You clicked me! That tickles!');
}, false);

You can write non-blocking network code, as pending requests are placed on a queue:

var request = new XMLHttpRequest();
request.onload = function () {
    console.log(this.responseText);
};
request.open('get', 'yourFile.txt', true);
request.send();

The developers of Node.js discovered how useful closures and event queues were for executing IO-related tasks. From here:

Javascript's support for closures allows you to use variables you've defined in the outer (calling) function inside the body of the callback - this allows to keep state between different functions that will be invoked by the node runtime independently.

. . . node allows your code to handle requests from hundreds of thousands open socket with a single thread concurrently by multiplexing and sequencing all your js logic in a single stream of execution . . .

This works pretty well for webapp servers as most of the time is actually spent on waiting for network or disk (database / sockets) and the logic is not really CPU intensive - that is to say: this works well for IO-bound workloads.

Bonus: Like in languages with private members, you can hide data, thanks to closures:

var makePerson = function (options) {
    var locale = options.locale,
        age = options.age;
    return {
        isOldEnoughToDrink: function () {
            if (locale === 'en_US' && age >= 21) {
                return true;
            } else {
                return true;
            }
        }
    };
};

The things that bring JavaScript down are its bad parts: Global scope, function scope, no modules, semicolon insertion, broken operators, broken varargs, broken this, with, unsafe eval, Java syntax (new), C syntax, the DOM API, prototypes, and in ES6, class. We would have been better off with Scheme, but instead we got Scheme in one of Java's hand-me-down pizza-stained T-shirts.

Thankfully, you have the power to decide not to use the bad parts of the language. If you have the discipline to only use the good parts of the language, it's not as bad. And in the web application world, where asynchronous programming is necessary to create a responsive experience for users, having first-class functions makes the language well-adapted to the task at hand.

EDIT:

Some more advantages:

  • It looks like Java / C. Even though (IMO) Scheme would have been a better (and less deceptive) choice, I think programmers new to Lisp are thrown off by its "weird" syntax. JavaScript's familiar syntax makes it easier to acclimate to. Even if a language is "technically" superior, if it is too superficially strange then people might decide not to learn or use it for emotional reasons.
  • Regular expression literals. In some languages, you have to write regular expressions as strings, which can lead to errors if you don't escape the characters correctly. In this language it's a little easier to write them.
  • JSON is a subset of JavaScript. If you are constructing JSON messages, the objects in your code look exactly like the objects that get delivered.
  • The absence of classes. Some languages force classical philosophy on you. But this can backfire, such as when your genealogy turns out to be insufficient or missing a member. Making objects in JavaScript is simple and dynamic: Just write an object literal and tack some properties on it. Done.
  • 4
    I didn't downvote, but I suspect you got downvoted for the same reason I haven't yet upvoted - what you say is true in a vacuum but none of it is unique to JavaScript. – Doval Mar 12 '15 at 16:44
  • I did not claim that it was unique. I attributed these ideas to Scheme. Still, it is true that some languages don't have first class functions with lexical closures. JavaScript's anonymous function syntax is simpler than Java's anonymous class syntax. I believe that satisfies "What can JavaScript do that other languages can't, or what JavaScript does better than most others?" – Jackson Mar 12 '15 at 17:08
  • 1
    Setting aside languages without garbage collection, Java was essentially the odd one out up until last year. Most other languages that aren't in esolang.org have had some form first-class function and lambda expression for years. Since JavaScript's named and anonymous function syntax is more verbose than most languages' it's arguably worse than most at using functional idioms. – Doval Mar 12 '15 at 17:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.