14
JavaScript clean coding Code integrity, readability and efficiency Thor J. Nydal, Senior Software Consultant

Java script best practices v4

Embed Size (px)

DESCRIPTION

code integrity, readability and efficiency

Citation preview

Page 1: Java script best practices v4

JavaScript clean coding

Code integrity, readability and efficiency

Thor J. Nydal,Senior Software Consultant

Page 2: Java script best practices v4

Global variables

Declared in top scope:

var variableA = 0;

variableA = 0;

window.variableA = 0;

Page 3: Java script best practices v4

Problems of global variables

• May lead to unpredictable behaviour due to cross-module interference which is hard to cover through tests

• Use of global variables in subroutines is alsoimpeding performance

Page 4: Java script best practices v4

How to encapsulate variables

Solution to global variable issues:

/** anonymous closure, creates a virtual environment */(function() {

var data= {};function start() {}

})();

/** ECMA5 decl. singleton/namspace */var MyApp = {

data: {},start: function() {}

};

/** class decl. */var MyApp = function() {

var data = {};function _init() {}this.start = function() {}

};

Page 5: Java script best practices v4

Function declaration vs. expression

declaredFunction(); // will runfunction declaredFunction() {…

}

expressedFunction(); // runtime errorvar expressedFunction = function() {…

}

Page 6: Java script best practices v4

The problem with null in JavaScript

A JavaScript beginner will typically mix null and undefined:

(function() {…var car = CarRegister.getCar(id); // function normally returns a car object or

null, but in some situations also undefined

If (typeof car === ’object’) { // by checking that the result is an object, theprogrammer believes he is safe showCarInfo(car);

} else {showNotFoundMessage();

}})();

Page 7: Java script best practices v4

Handling null objects & undefined

Because getCar(…) also returns undefined, this is not enough:

If (car !== null) {showCarInfo(car);

}

The key here is to know that a null object is falsey and to extend the initial condition:

If (data && typeof data === ’object’) {// real object or array (not null and not undefined)

}

Page 8: Java script best practices v4

By habit, use strict comparision

var x = 1, y = ’1’;x == y // truex === y // false

var x , y = null;x == y // truex === y // false

var x = [’’, null, undefined];x == ’,,’ // truex === ’,,’ // false

Page 9: Java script best practices v4

Batch DOM interaction

Because the browser DOM and JavaScript engine runs seperately, and because of a performance bottleneck between the two, batch DOM operations should be batched to minimize browser reflow.

Page 10: Java script best practices v4

Use ECMA5 notation

Creating JS objects & arrays:

var object = new Object(); var object = {};

var array = new Array() var array = [];

Page 11: Java script best practices v4

Absolute programming principles?

The extent to how far YAGNI and DRY principles are pursued, is determined by the scope of the developement project in terms of software system strategy, lifetime etc.

However, there is never any good reason to describe anythingso it can be misunderstood. Therefore, the KISS prinsiple, which can be read as ”keep it simple and straightforward” is universal.

The SRP principle can also be seen as absolute for a professional programmer as there is never any good reasonto structure an app, regardless of size, in an unintuitive/unlogical way.

Page 12: Java script best practices v4

Use a templating/MVC framework

Provides:• Object check functions which handles both

undefined & null• By following its general outlines, you will be

helped to avoid creating global variables• An MVC framework will helps a programmer to

batch DOM operations more

Follow the JS application framework way to declaremodules and variables

Page 13: Java script best practices v4

Summary

• Be aware of the mentioned pitfalls of plain JavaScript, but learn theJS application framework used in your project with its utils so youcan focus on the business logics

• Make it a habit to use strict operators to make clearer code• Even if following an MVC framework, think transaction cost when

dealing with DOM operations and create better UI response at thesame time

• Developement and design principles are not neccesarrily absolute• Coding is an iterative process, even in the scope of deciding on how

to formulate a single variable – express yourself in a unambigiousgrounded way to reduce cross-cultural confusion and to indirectlyimprove team performance through more collaborative code

• Awareness and dicipline is required to follow mentioned guidelines

Page 14: Java script best practices v4

References

• Crockford, D. (2008) JavaScript: The Good Parts: The Good Parts. OReilly.

• Martin, R. (2008) Clean code: A handbook of agile software craftsmanship. Prentice Hall.