May 8, 2014

Even if you don’t have to directly work with JavaScript I think it’s worth investing your time in learning JavaScript and I want to encourage you to do that with that little overview article. So if you are a java-developer and you want to catch a bit with JavaScript this is a good place to start.

I also must warn you that I’m not aiming to cover every aspect of JavaScript in this article. Instead I just want to focus on most confusing concepts for Java developers, because well… yeah… JavaScript can be confusing. Especially when it tries to pretend something which it isn’t.

Object-oriented, but no classes #

Alright, here is the thing to start with. There are no classes in JavaScript. Almost everything is an object. Even arrays, even function, but there are no classes as cornerstone language construct. While Java forces you to describe behaviour of your objects before you can initiate them, JavaScript doesn’t. That means that you can create any objects at any time and modify them, adding or deleting properties, assigning functions and so on as your code runs.

var boy = {}; boy.age = 9; boy.growUp = function() { this.age += 1; }

Comparing to Java this is bit more flexible and much more convenient. And what’s more that doesn’t mean you can’t emulate classes (e.g. objects that can create another objects with predefined behaviour) if you want to. Although this approach is not being encouraged by JavaScript community there are numerous ways, how one can implement semi-classical inheritance.

There is no native support for modularity in JS (like packages in Java) until ECMA6. But still there are several third-party solutions or you can come up with your own.

Prototype inheritance #

JavaScript doesn’t have classes, but this doesn’t mean that it doesn’t have inheritance. In its own way, of cause. Putting it simply every object is inherited from some other through special hidden property called prototype (you can access it via ‘proto’ property). When you attempting to execute obj.someFunction(), JavaScript trying to find such function in obj properties. If it is not there, then it takes its prototype and then the prototype of prototype and so on, till it gets to the top object with no prototype. So basically it search for any property all the way up of prototype chain. This is why JS is sometimes referred to as prototype-oriented language (in opposite to object-orient).

Just a few words of precaution. JavaScript often tries to pretend something which it isn’t. Just to name a few examples. You may find some keywords like ‘class’ that are reserved (which mean that you can’t use them as variable names) but still not used at all. Another example is mysterious “typeof” which returns a string for every object you pass to it. You can except it to work like ‘ instanceof ’ in Java but this is not exactly so. Because there is no ‘types’ in javascript this operator just compares its operand to one of predefined values and returns predefined strings. These issues often confuses developers and you must be aware of them.

Having that said lets continue with object inheritance. In JavaScript you can initiate an object using the keyword new (which is not the only one way). But (yeah, you guessed it) it works not exactly as you might expect. new operator is used only with functions which may sound strange. Well it is. But that is how things work in JavaScript.

function builder() { this.x = 5; }; builder.prototype.y = 7 a = new builder(); a.x; // 5 a.y; // 7

Every function has a prototype property. When you crate an object with new then its prototype (proto) is set to functions prototype property. Also this inside of a function block is referred to object itself. Here is another example that may clarify a little this confusing logic:

function Obj() { this.a = 5; }; Obj.prototype.a = 7; obj = new Obj(); obj.a; // 5 obj.__proto__; // {a: 7} Obj.prototype.f = 10; obj.f; // 10 obj.__proto__; // {a: 7, f: 10}

I don’t think that my explanation of this obscure

concept is clear enough, so I suggest you to read this.

Dynamic typing #

Java is strongly statically typed. If you try to compile code such as:

Long num; num = "5";

you will fail. Cause you created a variable, and you specified a particular type of that variable. “5” is of type of String and not of type Long.

JavaScript will allow you to do such things, because you can’t specify type of variable in JavaScript. You just create a variable and then you are free to assign it any value you want.

var a = 5; a = "hello there"; a = function () { console.log("Hello there"); }

This gives you great flexibility and ability to do almost anything at runtime. But comparing to Java this approach is more error-prone. No one will warn you now if you by accident assigned the wrong value to your variable. In reality that means that you should write a bit more tests for your code. Which is actually not that bad, you know :)

Visibility Scopes #

Another feature of JavaScript which tends to trick Java (in fact not only Java) programmers is the notion of scope (you know the portion of code inside curved brackets {…} and all the bindings). In JavaScript when you are opening curved bracket it is not guaranteed that you opening a new scope. Consider following example.

var x = 5; if (true) { var x = 10; } console.log(x); // => 10

See, in this case declaring a variable inside of an if-block makes absolutely no effect. The variable is declared only once and inside a block it just gets a new value. Also if you defined a variable inside an if block this variable will be also accessible after you leaved that block.

This behaviour is normal in JavaScript because the only way you can define a new scope is by creating a new function. That’s why technique of creating an anonymous function and calling it immediately (function() {…})() is so widespread among JS programmers.

var x = 5; if (true) { (function() { var x = 10; }) (); } console.log(x); // => 5

Strictly speaking this behaviour is considered as weird by so many developers that they decided to fix it in ECMA6

Books and resources #

Comments on reddit

106 Kudos