Book Image

Jasmine JavaScript Testing Update

By : Paulo Vitor Zacharias Ragonha
Book Image

Jasmine JavaScript Testing Update

By: Paulo Vitor Zacharias Ragonha

Overview of this book

Table of Contents (15 chapters)

JavaScript – the bad parts


There are many complications when dealing with client JavaScript code; the obvious one, is that you cannot control the client's runtime. While on the server, you can run a specific version of your Node.js server, you can't oblige your clients to run the latest version of Chrome or Firefox.

The JavaScript language is defined by the ECMAScript specification; therefore, each browser can have its own implementation of a runtime, which means there could be small differences or bugs between them.

Besides that, you have issues with the language itself. Brendan Eich developed JavaScript in just 10 days, under a lot of management pressure at Netscape. Although it got itself right in its simplicity, first-class functions, and object prototypes, it also introduced some problems with the attempt to make the language malleable and allow it to evolve.

Every JavaScript object is mutable; this means that there is nothing you can do to prevent a module from overwriting pieces of other modules. The following code illustrates how simple it is to overwrite the global console.log function:

console.log('test');
>> 'test'
console.log = 'break';
console.log('test');
>> TypeError: Property 'log' of object #<Console> is not a function

This was a conscious decision on the language design; it allows developers to tinker and add missing functionality to the language. But given such power, it is relatively easy to make a mistake.

Version 5 of the ECMA specification introduced the Object.seal function, which prevents further changes on any object once called. But its current support is not widespread; Internet Explorer, for example, only implemented it on its version 9.

Another problem, is with how JavaScript deals with type. In other languages, an expression like '1' + 1 would probably raise an error; in JavaScript, due to some non-intuitive type coercion rules, the aforementioned code results in '11'. But the main problem is in its inconsistency; on multiplication, a string is converted into a number, so '3' * 4, is actually 12.

This can lead to some hard-to-find problems on big expressions. Suppose you have some data coming from a server, and although you are expecting numbers, one value came as a string:

var a = 1, b = '2', c = 3, d = 4;
var result = a + b + c * d;

The resulting value of the preceding example is '1212', a string.

These are just two common problems faced by developers. Throughout the book, you are going to apply best practices and write tests to guarantee that you don't fall into these, and other, pitfalls.