Imagine a bacon-wrapped Ferrari. Still not better than our free technical reports.
See all our reports

JavaScript: Explain it like I’m a Java Developer

JavaScript: All vs. Good parts

We can’t explain all of JavaScript in a single blog post. If you’re dealing with web application development in any capacity, and our Java Tools and Technology Landscape report does show that majority (71%) of Java developers fall in this category, chances are you’ve stumbled across JavaScript.

No doubt you already know that Java and JavaScript, despite being similarly named, don’t share a great deal in common with each other. The static typing, simple syntax with straightforward rules, and the verbosity of Java is vastly different from the dynamism, lack of any coherent rules and quirks of JavaScript.

However, JavaScript is the programming language of the web and recently got its fair share of attention on the server side with the development of Node.js and JVM’s own Nashorn JavaScript engine.

In this post, I don’t want to just ramble on about how good or bad JavaScript is, or repeat the thousands of JavaScript tutorials that are freely available to anyone. I want to list some things that are important for the understanding of JavaScript as a language and to understand from which side to approach a horse JavaScript project.

So in this post we will cover the following language-level issues:

  • The universality of JavaScript
  • Functional programming issues in JavaScript
  • Inheritance differences from Java

Additionally, you’ll find tooling recommendations that you wouldn’t want to start any JavaScript project without: from code quality analysis & testing frameworks to build systems.

The good things to know

Write once – run mostly anywhere!

JavaScript is no doubt the language of the web, compilation target to numerous other programming languages and the ultimate way to prove that sometimes people just have too much free time. However, this is not a bad thing. Every computer capable of browsing a modern website is equipped with a JavaScript engine that is both performant and available. On top of that, JavaScript code can be run on the backend.

Nashorn, which is a lightweight high-performance JavaScript runtime baked into the JVM we all know and love, is totally capable of interpreting JavaScript scripts and integrating them with the Java code of your project.

Given this freedom of being available for runtime on every machine JavaScript is a perfect continuation of the Java experience.

Functional programming: Functions are first class citizens, Recursion is not so

Functions in JavaScript are first class citizens. They are values to be stored to variables, passed around to other functions and executed when the moment is right.

This opens a door into the world of functional programming, which is the preferred way of structuring JavaScript programs.

Note that objects in JavaScript are just big maps of whatever, and every attribute of the object sits in the same map: functions, properties, constructors; so mutability raises an even bigger concern compared to Java, where you can at least be sure that your method and field structure is somewhat stable.

This in turn makes the functional programming approach even more lucrative: small understandable functions that combine and immutable data structures are the way to go in JavaScript.

Not to be unfounded, here’s how you define a reduce function in JavaScript, the example is taken from Eloquent JavaScript book.

function forEach(array, action) {
  for (var i = 0; i < array.length; i++) {
    action(array[i]); //apply action to every element of the arra.
  }
}

function reduce(combine, base, array) {
  forEach(array, function (element) {
    base = combine(base, element); // and here we apply function passed as ‘combine’ parameter to ‘base’ and ‘element’
    });
return base;
}

function add(a, b) { // btw, this is how you define a function in JavaScript
  return a + b;
}

function sum(numbers) {
  return reduce(add, 0, numbers);
}

Note: we didn’t use the recursive version of reduce here. JavaScript doesn’t feature any tail call optimisation, which means that every recursive version of the function contributes to the stack depth, and just like in Java it will blow up if you recurse too deeply.

Inheritance: just like in the real world

Inheritance in JavaScript is prototypal. It means that you don’t have types that extend other types, but actually have instances that inherit functionality from other instances.

Imagine an object A being like a map, we touched this matter a bit above but here’s a different angle, and then another map-like object B is said to inherit everything from A.

What it means is that B has access to what A consists of, its methods, fields and so forth.

In practice I’ve never seen anybody actually using plain prototypal inheritance. Usually when one needs inheritance, one just emulates classes – so you can use all the widespread knowledge and patterns of working with class-based inheritance.

— Rene Saarsoo, XRebel Frontend Engineer at ZeroTurnaround


I’m not really sure what a Java developer should take from this, but beware of this difference in the inheritance organisation and pay extra attention to parent objects not to accidentally change the behavior of the whole program.

Avoid these at all costs

Listing dubious JavaScript design decisions is easier than one might think. The most obvious thing to avoid in a JavaScript program is obviously global variable declarations.

Note that in JavaScript, defined variables are pushed to the top of the scope in which they are defined, so whenever you define a variable without using the var keyword. It means that every variable defined this way will float to the top of the global scope ensuring conflicts and unexpected headache for you and your teammates.

Alternatively, enable the strict mode. Just write “use strict” at the top of the script file and your unintentional global variable declarations will become errors.

Another important difference of JavaScript from Java is that the former is a dynamically typed language. What it really means is that everything can be anything. It is obvious, but cannot be emphasized enough: don’t reuse the same variables for values of different types!
Tracking a variable that was a String once, but now is a floating point number or a function gives little pleasure, trust me!

Also, I don’t want to go deeply into types and truthy-falsy values discussion, but be alert of implicit type conversions that the JavaScript engine throws at you.

Tips for getting stuff done

As I mentioned in the beginning there is more to programming than knowing the syntax and quirks of the language in use. Project rarely fail because the language is lacking. More often failures are related to the general project architecture inefficiencies. Here are some tools that can help you with delivering the project.

Static code analysis

Most projects are different and their complexity and requirements contribute a huge amount of details to how you want to approach the codebase. However, there is one goal that is consistent between all of them: code quality.

Yeah, I get it, the most important thing for any developer is to ship things. But don’t compromise on the quality, don’t get into a state when you are embarrassed for the code you pushed and reluctant to share it with the teammates.

Luckily, JavaScript has a decent solution for this – JSHint. JSHint is a static analysis tool for JavaScript, a lot like FindBugs for Java code. JSHint can run on you codebase and highlight the suspicious or problematic places which, even if they don’t contribute a bug right now, will become hard to maintain in the future. It’s really straightforward to enable it on the project. Do yourself a favor – if you do write JavaScript code, make it safer and less embarrassing by using JSHint.

REPL

Repl stands for read-eval-print loop and is a great tool for more dynamic languages. If you’ve looked at Scala or Groovy you definitely recognise the concept.

One way to fire up a JavaScript repl is to open your browser’s console which comes with an interface to evaluate JavaScript snippets.

js-browser-console screenshot

Another tool that can be of convenience is jjs , which comes bundled with JDK 1.8.

jjs example

It is a command line tool that gives you access to Nashorn JavaScript engine in the JDK and is fully capable of evaluating even the trickiest of JavaScript scripts.

Tests

In a project of any value, you will want to run some tests. Tests are especially important in a language with dynamic typing, so for JavaScript endeavours, it’s good to get ahold of a testing framework of your choice. I can recommend Jasmine – a behavior-driven development framework for testing JavaScript.

jasmine-example

In Jasmine, you describe your test-suites with describe and it blocks that access the code you want to test. After the code under test does its job, you expect things.

This is obviously not a tutorial, but I wanted to give you a glimpse at how elegant JavaScript code can look like. Jasmine is one of the best practices for JavaScript projects and we personally use it at ZeroTurnaround for our product development. Especially for JavaScript heavy in-app interactive profiler XRebel.

Build tools

Last, but not least valuable thing that your project will need is a build tool. If you’re using JavaScript in some Java project then sure you can get away with the Java build tool of your choice and it’ll most likely be enough. But for a standalone JavaScript project there’s no need to bring in the monstrosity of Maven.

One build tool to consider for JavaScript projects is Gulp. It’s a plugin-based build system that you specify tasks for. Tasks can be something like “copy .js files from under src dir into dest” or “minify my javascript code for production use”. What rocks is that Gulp works with streams of files with tasks acting as filters, so you can apply those two tasks in one efficient sweep.

There are tons of plugins available and you’ll find the collaboration on a project much easier with the build system in place.

Conclusion

We ran through some peaks of the gigantic land of JavaScript and tried to shed some light on concepts and tools that a Java developer dealing with JavaScript should know about. Naturally, this is not a full list of things to learn, but if you’re preparing for a headfirst dive into a JavaScript project, these will get you started and embracing the peculiarities of the JavaScript will help you not to get frustrated too often.

Do you know a secret or best practice that can lead a JS developer to a happier place? No doubt it should be shared! Leave a comment below or find and chat with me on Twitter: @shelajev. I’d love to hear your thoughts!


READ MORE POSTS BY ME!

 

  • David Leppik

    As a Java/Scala developer who has been doing a ton of JavaScript in the last several years, I’ve found that TypeScript is a good way to approach JavaScript. TypeScript is a superset of JavaScript that compiles to plain, canonical JavaScript. It adds type safety and Java-like classes and interfaces.

    What’s more, I can use my JetBrains IDEs for both Java and TypeScript. The feature set isn’t quite as rich for TypeScript as for Java and Scala, but TypeScript’s type safety lets it do much better code completion than it can do with JavaScript.

    The debuggers in web browsers support TypeScript. This isn’t unique to TypeScript– there’s a standard JavaScript source code map format so that any compressed or compiled JavaScript can be mapped back to its original source code in the debugger.

  • Cynic

    I’m sorry but I refuse to read light gray text on white. Gray on white is already bad enough, this page is just ludicrous.

  • balder

    Maybe in your console of the browser, do some REPL and make all gray go green with a black backgound!

  • Cynic

    Or maybe, site designers could use more sensible colors. Like the ones on this Disqus component.

    Low contrast reduces readability and increases read time.
    It may look fine for you. But it won’t for older people and in small or low quality screens.

  • Cynic

    And this site fails both AA and AAA from contrast guidelines from W3C.
    Simply changing the font weight to normal and it passes AA and the visual stays practically the same.

  • theshowmecanuck

    I agree with cynic. balder, maybe it looks OK to you, but to a lot of people, me included, the light greay on white is very difficult to read. very difficult. To the point I have to skip a lot of articles when the contrast is too low. Like this one. I was going to mention it, but someone else beat me to the punch.

  • ash

    Lol how bad are your eyes? It’s very easy to see…