Web Development

Best Practices

Best Practices is section 23 and last section of Beginner’s Guide to JavaScript.

Other than to following coding conventions and using debugging there are many more to follow, which we are categorize as best practices. If you follow these things you’ll be able to produce a maintainable code as well as improve performance. As we have covered up all the technical material regarding to JavaScript, this is the ideal time to reveal the best practices as the last section. After this you can startup your own JavaScript project. We may have discussed some of these things along the way in our previous sections. Anyway this section put together all of them in one place.

Avoid Global Variables

Avoid using global variables. This includes all data types, objects, and functions. Global variables and functions can be overwritten by other scripts. Use always local variables instead.

Always Declare Local Variables

All variables used in a function should be declared as local variables. Local variables must be declared with the var keyword, otherwise they will become global variables.

Never Declare Numbers, Strings, or Booleans as Objects

Always treat numbers, strings, or booleans as primitive values. Not as objects. Declaring numbers, strings, or booleans as objects, slows down execution speed, and produces nasty side effects.

var x = “John”;             // Always this way – Good
var y = new String(“John”);             // Never this way – Bad

Don’t Use new Object()

  • Use {} instead of new Object()
  • Use “” instead of new String()
  • Use 0 instead of new Number()
  • Use false instead of new Boolean()
  • Use [] instead of new Array()
  • Use /(:)/ instead of new RegExp()
  • Use function (){} instead of new function()

var x1 = {};           // new object
var x2 = “”;           // new primitive string
var x3 = 0;            // new primitive number
var x4 = false;        // new primitive boolean
var x5 = [];           // new array object
var x6 = /()/;         // new regexp object
var x7 = function(){}; // new function object

Beware of Automatic Type Conversions

Beware that numbers can accidentally be converted to strings or NaN (Not a Number). JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type.

var x = “Hello”;     // typeof x is a string
x = 5;               // changes typeof x to a number

When doing mathematical operations, JavaScript can convert numbers to strings.

var x = 5 + 7;       // x.valueOf() is 12,  typeof x is a number
var x = 5 + “7”;     // x.valueOf() is 57,  typeof x is a string
var x = “5” + 7;     // x.valueOf() is 57,  typeof x is a string
var x = 57;       // x.valueOf() is -2,  typeof x is a number
var x = 5“7”;     // x.valueOf() is -2,  typeof x is a number
var x = “5”7;     // x.valueOf() is -2,  typeof x is a number
var x = 5“x”;     // x.valueOf() is NaN, typeof x is a number

Subtracting a string from a string, does not generate an error but returns NaN

“Hello”“Dolly”    // returns NaN

Use === Comparison

The == comparison operator always converts (to matching types) before comparison. The === operator forces comparison of values and type.

0 == “”;        // true
1 == “1”;       // true
1 == true;      // true

0 === “”;       // false
1 === “1”;      // false
1 === true;     // false

Never End a Definition with a Comma

Some JSON and JavaScript engines will fail, or behave unexpectedly. So never ever do this.

points = [40, 100, 1, 5, 25, 10, ]; //bad

person = {firstName:“John”, lastName:“Doe”, age:46, } //bad

Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to undefined. Undefined values can break your code. It is a good habit to assign default values to arguments.

[code languague=”js”] //method 1
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}

//method 2 – simpler way
function myFunction(x, y) {
y = y | 0;
}
[/code]

We guess you know the operator in the 2nd method. That’s the OR operator, remember ?

Avoid Using eval()

The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it. Because it allows arbitrary code to be run, it also represents a security problem.

Reduce Activity in Loops

Loops are often used in programming. Every statement inside a loop will be executed for each iteration of the loop. Search for statements or assignments that can be placed outside the loop.

Reduce DOM Access

Accessing the HTML DOM is very slow, compared to other JavaScript statements. If you expect to access a DOM element several times, access it once, and use it as a local variable as follows.

obj = document.getElementByID(“demo”);
obj.innerHTML = “Hello”;

Reduce DOM Size

Keep the number of elements in the HTML DOM small. This will always improve page loading, and speed up rendering (page display), especially on smaller devices. Every attempt to search the DOM (like getElementsByTagName) is will benefit from a smaller DOM.

Avoid Unnecessary Variables

Don’t create new variables if you don’t plan to save values. Often you can replace code like this.

var fullName = firstName + ” “ + lastName;

document.getElementById(“demo”).innerHTML = fullName;       //bad

document.getElementById(“demo”).innerHTML = firstName + ” “ + lastName      //good

Delay JavaScript Loading

Putting your scripts at the bottom of the page body, lets the browser load the page first. While a script is downloading, the browser will not start any other downloads. In addition all parsing and rendering activity might be blocked. The HTTP specification defines that browsers should not download more than two components in parallel.

An alternative is to use defer=”true” in the script tag. The defer attribute specifies that the script should be executed before the page has finished parsing, but it only works for external scripts.

If possible, you can add your script to the page by code, after the page has loaded.

[code languague=”js”] Avoid Using with

Avoid using the with keyword. It has a negative effect on speed. It also clutters up JavaScript scopes. The with keyword is not allowed in strict mode.


 

Now… Now… We are at the end of this tutorial. Hope you found almost everything regarding to JavaScript; shorten for JS, to startup a JS project. You know all the technical concepts, best practices and coding conventions. So why waiting…? Start Now. We’ll be back with our next tutorial.

So till then stay tuned… Keep in Touch!!

 

PLEASE DON’T FORGET TO SUBSCRIBE FOR NEW UPDATES.

 

Join Our Newsletter Today

Stay updated with all latest updates.
Give it a try, you can unsubscribe anytime.
Subscribe
SUBSCRIBE NOW

About the author

Sandeep Likhar

Sandeep Likhar from Indore India, Blogger, eBook Designer and Founder of LetsDnD. Having five years of experience in industry as a Digital Publishing Expert and eBook Converter providing services to Authors, Publishers and distributors worldwide. Proficient in converting books into various formats HTML, epub, mobi, word, PDF including all major online platforms iTunes, Kobo, Kindle, Createspace, B&N, Smashwords and more.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz
DON’T MISS OUT!
Subscribe To Newsletter
Be the first to get latest updates and exclusive content straight to your email inbox.
Stay Updated
Give it a try, you can unsubscribe anytime.

Join Our Newsletter Today

Stay updated with all latest updates.
Give it a try, you can unsubscribe anytime.
Subscribe
SUBSCRIBE NOW