Tuesday, October 15, 2019

5 JavaScript Features That I Miss in Java

Over the years, I have developed a lot of passion for Java programming. There is a lot of things in life that are more fun than Java (like Scandivania, pictured 😉), but out of those things I get paid for, Java is certainly near the top of my list.
I also used to do a lot of backend server programming where Java was predominant back then. Still I was amazed at how often I'd hear my fellow technologists say things like:
  • "JavaScript is a flawed language"
  • "it is a language for script-kiddies"
  • "there is much hype about JavaScript"
I used to wonder, was JavaScript really that bad? But I wasn't able to tell until I had an opportunity to work on a couple of JavaScript projects myself. Since then I have learned that JavaScript, despite it has a dark side, definitely does have a bright side too. Here I put together a list of JavaScript features that are so cool I wish they were available in Java too.

For every feature I give an example in JavaScript, and an equivalent code in Java, to my best effort. Please share in comments if you can do better. For some of the examples I used TypeScript because the JavaScript code with no types would have appeared to be shorter and more concise, and I wanted to keep the comparison as fair as possible.

I only added explanation where I felt it was necessary.

1. Template String Literals

JavaScript Java

2. Destructuring Assignment

JavaScript Java

3. Spread Operator

Suppose that you have two unrelated types with some overlapping properties, for instance Student and Customer. How can you copy all overlapping properties from the customer object to the student object?
TypeScript Java
Strictly speaking, the JavaScript object will receive all properties from the customer object, not just the overlapping ones. For most practical purposes this will not play any significant role though.

4. Default Parameters

Write a function that returns a logarithm of a given number to a given base, with the base defaulting to 10 if not provided.
TypeScript Java

5. JavaScript Object Initializer

JSON has been increasingly popular for data interchange, and for good reason. Initializing objects in JavaScript is even more concise than in JSON!
JavaScript Java

Conclusion

I am not arguing that JavaScript is superior to Java or vice versa. JavaScript and Java have quite different execution mode, runtime model, design philosophy and history. Yet more often than not, you will be able to make a choice between those two languages based on your personal or team preferences. In this post I just wanted to show that JavaScript can be pretty sexy, even to diehard Java developers.

What are your favorite JavaScript features? Do you have another opinion about Java or JavaScript? Let me know in the comments below!