Java to JavaScript, a habits tale

Lessons from a slow learner

Personal patterns

Habits in programming are not an often considered subject. We talk about skills, paradigms, syntax, and frameworks regularly, but habits are the reason we have coding style. They are the personal patterns we use to express solutions to problems. This is a post about learning to use Javascript and recognising my old Java habits were more a hindrance than a help. It’s also a chance for me to capture what I’ve learned and share with others who have recently ventured into the sea that is the JavaScript universe.

I’ve been using both Java and Javascript for about the same length of time but my journeys could not be more different. My pathway through Java was structured and comprehensive (the Royal Melbourne Institute of Technology has a great software engineering course). My approach to JavaScript could be compared more with that 5 a.m. stumble you make to the bathroom with your eyes half closed in the darkness.

I assumed (I suppose like many do) that because the two languages look similar, they must behave similarly. Well after trying to learn some JS technologies — Angular, React, Node — and realising that I just wasn’t quite getting it, I thought it high time to fill in some metaphorical holes.

Enter Douglas Crockford.

I got a copy of the book ‘JavaScript, The good parts’ by good Ol’ Doug. Some chapters presented things I knew, others were real eye openers. Doug’s book wasn’t the first tool I’d used to get to know the language, but it was the tipping point in a rather drawn out attempt. There are quite a few resources that have recently helped me develop my javascript nous. Some recommendations are: LearnCode YouTube channel, this medium blog post, W3Schools for straight-up vanilla code-examples, Ray Villalobos, JavaScript and jQuery book, Sayanee Basu’s Build Podcast. Being the language of the web, there are so many good resources available online. From all the new things I’ve picked up, there are a few which really took a while to sink in. Here are a few of the gems I found that really make Javascript unique.

Functions fly First Class.

Actually, functions are First Class. Huh? What the hell does that mean? In Javascript, functions are objects. They can be defined and stored in a variable just like any other object. That also means they can be passed as parameters to other functions. Consider this Javascript function:

function twoNumbers(name, mySummingAlgorithm) {
console.log(‘Hi, my name is ‘ + name);
console.log(‘The sum of all the numbers between 7 and 82 is: ’)
mySummingAlgorithm(7, 82);

What’s it doing? It takes, as parameters, a name and a function that can be called. That means that each user of the function can give it a different name and a different way to add up consecutive numbers. Awesome! Kind of reminds me of function pointers from C, but in a much lighter syntax.

EVENT — ually it runs

Javascript lives in the browser and runs in an event-driven environment. When the browser loads, it reads in all of the Javascript and stores it in memory. Some code may be executed immediately, while other code just sits there waiting. While this environment is foreign in Java, it’s simplicity in Javascript makes it feel natural. Beware though, this is the root of asynchronous activity, i.e. multiple things happening out of order and at different times. What kind of events are we talking about here? Anything that happens in a browser — clicking, typing, scrolling, hovering, dragging, loading, requesting. Only when an event takes place does Javascript take action.

You are the Object of my affection

In Java, there is just one way to create new objects and that’s with the new keyword. You declare a variable, and assign it an instance of the new Object like so

Coordinate lastPosition = new Coordinate();

Javascript has a new keyword too, but it has some less desirable side-effects. If you declare a new variable but forget to use the new keyword, then the this variable will be bound to the global scope (If that is unclear, don’t worry too much, just know it’s a bad thing). Javascript has a bunch of other ways though that you can create an object. There is the object literal pattern, the prototypal pattern, and the constructor pattern. The prototypal pattern is probably the most flexible and offers encapsulation. Rather than labelling objects and methods as public and private like you would in a Java class, Javascript functions use the position of elements within the object to hide information. Put simply, everything before the return statement is hidden and everything after the return statement is the API. Hiding methods and instance variables inside a Javascript closure is the same as applying Java access modifiers. Closure, huh? What’s that? Well I’m glad you asked.

Closure. Keeping variables alive since 1995

This topic comes up a lot when reading about Javascript. If you understand the event driven nature of Javascript, then closure follows perfectly. I might quote Will over at who said it best. A closure is anything that

‘retains state and scope after it executes’.

I mentioned before that Javascript files are loaded in at runtime, but the code is only fired off when an event occurs. This means for example, some variables which were initialised inside a function will be needed later, even though the scope of that function is now closed off. Here’s an example:

document.ready(function() {
const count = 0
const addToCount = () => {

$(‘button’).on(‘click’, addToCount)

In this case, the Javascript file is loaded by the browser and reads from the top. The document.ready() wrapper basically just says, wait until the page is loaded and then execute the following code. That code will only be executed once. Let’s see what it does. The variable count is initialised to 0. A function called addToCount() is assigned to a click event, and that’s it. The actions inside addToCount() will only be executed when the event occurs. Now here’s the question: how does addToCount() access the count variable? Surely, when the count variable was initialised at the start, it was in the scope of a function that is now finished and forgotten, right? Well, that’s just what closure is, it allows variables to retain their value and continue existing even after their scope has closed. Javascript is smart enough to see the addToCount() function relies on the count variable, so it keeps that reference in memory. Cool huh?

Modules. A bit like Classes. But not really.

In Java, variable name collisions are easy to avoid. You simply don’t have a two variables with the same name in any class. In Javascript, there is no separation of code through classes. When multiple Javascript files get read into the browser, they all go into the soupy mess that is the global scope. So if I write a file which has a variable called ‘count’, and you have a file with a variable ‘count’, and they are both loaded into the browser together, then we are going to have some problems. Modules are a way to avoid name collisions. They provide some structure to your code and give you some control over the API. Basically, everything in a module gets wrapped in an object. That object is the top level domain for all your code. For example you might call your module myApp like so,

var myApp = function(){
// all your code here

Then when using your module, just like a class, everything is called through the myApp object in dot notation like so:


Now the global scope only has one new object in it called myApp. Hopefully none of the other code on the page uses that name.

Properties. Gimme something new.

This one is wild. For a Java developer, a field or instance variable is a fixed part of the object at hand. It is declared at the top of a class and then those variables can be accessed by dot notation. Javascript objects are dynamic, which means you can simply call the dot notation and create the variable. Anytime an assignment is used, it works. If the variable exists, then it is overwritten with the new value. If it doesn’t exist then it is created! This may seem mundane to the seasoned Javascript dev, but to a Java developer getting to know the language, this is awesome.

A Habits tale

Our habits when coding go deeper than just tab vs space and where you put the curly braces, it’s the mindset and approach you bring to the problem. Many of these Javascript topics were mysterious to me until I began learning some of the patterns. I learned them, internalised them, used them, and they then became my personal patterns. Not because I own them, but because they are my habits. If you want more on some of these topics, there are some great resources on patterns for Javascript, and even programming patterns in general. Learn some patterns, create new habits, write code well.