Some Useful JavaScript Tips,Tricks and Best Practices

As you know, JavaScript is the top programming language in the world, the language of the web, of mobile hybrid apps (like PhoneGap or Appcelerator), of the server side (like NodeJS or Wakanda) and has many other implementations. It’s also the starting point for many new developers to the world of programming, as it can be used to display a simple alert in the web browser but also to control a robot (using nodebot, or nodruino). The developers who master JavaScript and write organized and performant code have become the most sought after in the job market.

 

In this article, I’ll share a set of JavaScript tips, tricks and best practices that should be known by all JavaScript developers regardless of their browser/engine or the SSJS (Server Side JavaScript) interpreter.

 

Don’t forget var” keyword when assigning a variable’s value for the first time.

Assignment to an undeclared variable automatically results in a global variable being created. Avoid global variables.

Use “===” instead of “==”

The == (or !=) operator performs an automatic type conversion if needed. The === (or !==) operator will not perform any conversion. It compares the value and the type, which could be considered faster than ==

[10] === 10    // is false

[10]  == 10    // is true

'10' == 10     // is true

'10' === 10    // is false

 []   == 0     // is true

 [] ===  0     // is false

 '' == false   // is true but true == "a" is false

 '' ===   false // is false 

undefined, null, 0, false, NaN, '' (empty string) are all falsy.

 

Use Semicolons for line termination

The use of semi-colons for line termination is a good practice. You won’t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser. For more details about why you should use semi-colons.

 

Create an object constructor

function Person(firstName, lastName){

    this.firstName =  firstName;

    this.lastName = lastName;        

}  

var Khalid = new Person("Khalid", "Ansari");

 

Be careful when using typeof, instanceof and constructor.

typeof: a JavaScript unary operator used to return a string that represents the primitive type of a variable, don’t forget that typeof null will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”.

constructor: is a property of the internal prototype property, which could be overridden by code.

 

instanceof: is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it’s found and false if not.

 

var arr = ["a", "b", "c"];

typeof arr;   // return "object" 

arr  instanceof Array // true

arr.constructor();  //[]

 

Define a Self-calling Function

This is often called a Self-Invoked Anonymous Function or Immediately Invoked Function Expression (IIFE). It is a function that executes automatically when you create it, If you want to use this function you can write in the following way: 

 

(function(){

    // some private code that will be executed automatically

})();  

(function(p,q){

    var r = p+q;

    return r;

})(40,50);

 

Get a random item from an array

var items_array = [12, 548 , 'a' , 2 , 5478 , 'toogit' , 8852, , 'freelance' , 2145 , 119];

var  randomItem = items[Math.floor(Math.random() * items.length)];

 

Get a random number in a specific range

This code snippet can be useful when trying to generate fake data for testing purposes, such as a salary between min and max.

var x = Math.floor(Math.random() * (max - min + 1)) + min;

 

Generate an array of numbers with numbers from 0 to max

var numbersArray = [] , max = 100;

for( var i=1; numbersArray.push(i++) < max;);  // numbers = [1,2,3 ... 100] 

 

Generate a random set of alphanumeric characters

function generateRandomAlphaNum(len) {

    var rdmString = "";

    for( ; rdmString.length < len; rdmString  += Math.random().toString(36).substr(2));

    return  rdmString.substr(0, len);

}

 

Shuffle an array of numbers

var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];

numbers = numbers.sort(function(){ return Math.random() - 0.5});

 

A better option could be to implement a random sort order by code (e.g. : Fisher-Yates shuffle), than using the native sort JavaScript function

 

A string trim function

The classic trim function of Java, C#, PHP and many other language that remove whitespace from a string doesn’t exist in JavaScript, so we could add it to the String object.

String.prototype.trim = function(){return this.replace(/^s+|s+$/g, "");};  

A native implementation of the trim() function is available in the recent JavaScript engines.

 

Append an array to another array

var array1 = [12 , "foo" , {name "Joe"} , -2458];

var array2 = ["Doe" , 555 , 100];

Array.prototype.push.apply(array1, array2);

 

Transform the arguments object into an array

var argArray = Array.prototype.slice.call(arguments);

 

Verify that a given argument is a number

function isNumber(n){

    return !isNaN(parseFloat(n)) && isFinite(n);

}

 

Verify that a given argument is an array

function isArray(obj){

    return Object.prototype.toString.call(obj) === '[object Array]' ;

}

Note that if the toString() method is overridden, you will not get the expected result using this trick.

Or Use..

Array.isArray(obj); // its a new Array method

You could also use instanceofif you are not working with multiple frames. However, if you have many contexts, you will get a wrong result.

var myFrame = document.createElement('iframe');

document.body.appendChild(myFrame);

var myArray = window.frames[window.frames.length-1].Array;

var arr = new myArray(a,b,10); // [a,b,10]  

// instanceof will not work correctly, myArray loses his constructor 

// constructor is not shared between frames

arr instanceof Array; // false

 

Get the max or the min in an array of numbers

var  numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411]; 

var maxInNumbers = Math.max.apply(Math, numbers); 

var minInNumbers = Math.min.apply(Math, numbers);

 

Empty an array

var myArray = [12 , 222 , 1000 ];  

myArray.length = 0; // myArray will be equal to [].

 

Don’t use delete to remove an item from array

Use splice instead of using delete to delete an item from an array. Using delete replaces the item with undefined instead of the removing it from the array.

Instead of…

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ]; 

items.length; // return 11 

delete items[3]; // return true 

items.length; // return 11 

Use

var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ]; 

items.length; // return 11 

items.splice(3,1) ; 

items.length; // return 10 

 

Clearing or truncating an array

An easy way of clearing or truncating an array without reassigning it is by changing its length property value:

const arr = [11,22,33,44,55,66];

// truncanting

arr.length = 3;

console.log(arr); //=> [11, 22, 33]

// clearing

arr.length = 0;

console.log(arr); //=> []

console.log(arr[2]); //=> undefined

 

Simulating named parameters with object destructuring

Chances are high that you’re already using configuration objects when you need to pass a variable set of options to some function, like this:

doSomething({ foo: 'Hello', bar: 'Toogit!', baz: 42 });

function doSomething(config) {  

const foo = config.foo !== undefined ? config.foo : 'Hi';  const bar = config.bar !== undefined ? config.bar : 'Me!';  const baz = config.baz !== undefined ? config.baz : 13;  // ...

}

This is an old but effective pattern, which tries to simulate named parameters in JavaScript. The function calling looks fine. On the other hand, the config object handling logic is unnecessarily verbose. With ES2015 object destructuring, you can circumvent this downside:

function doSomething({ foo = 'Hello', bar = 'Toogit!', baz = 13 }) {  // ...}

And if you need to make the config object optional, it’s very simple, too:

function doSomething({ foo = 'Hello', bar = 'Toogit!', baz = 13 } = {}) {  // ...}

 

Object destructuring for array items

Assign array items to individual variables with object destructuring:

const csvFileLine = '1997,John Doe,US,john@doe.com,New York';const { 2: country, 4: state } = csvFileLine.split(',');

 

 

What is the difference between Java and JavaScript?

 

These are two different programming languages.

 

Javascript is a language that has gained tremendous popularity as a language on the web browsers to create dynamic and interactive web pages.

 

Java is a language that has got a similar popularity when you build a “backend” system, which is a fancy word for “almost anything”.

 

Despite the common prefix, they are not related; there creators are different and so are their origin stories (as highlighted by other answers). 

- JavaScript is a genius marketing scam that polluted the world of browsers exceptionally well. The browser reads JavaScript’s code line by line and executes it.

 

- Java is a general purpose language that is used almost everywhere, from Android mobile apps and cryptography to OS and cloud computing. Java’s code is stored in bytecoded format and then gets JIT compiled before the actual execution. In other words, it translates the bytecode to machine code.

 

- Java is class based. JS is prototype based. All objects, like Array or Function inherit from the Object.prototype which remains on top of the chain.

 

- JavaScript uses dynamic type checking (checks the variables while the code executes), unlike Java’s static checking system (variables are verified at compile time), which is more bug free.

 

- The word “Script.” It’s a joke, in case you didn’t get it.

 

 

Top Recommended Freelancers

More than 1,000,000 freelancers ready to tackle any kind of project
  • Sanket K.

    Application Developer (Java/Spring/SQL)
    $18 /hr, India
  • Vinay J.

    Software Engineer
    $17 /hr, India
  • Nancy R.

    Data analyst of different software like R studio
    $49 /hr, Kenya
  • Winnie N.

    Student
    $4 /hr, Kenya
  • Hasnain

    Full stack Developer
    $3 /hr, Pakistan
  • Irfan B.

    Backend Developer
    $17 /hr, United Arab Emirates
  • Altaf H.

    Web Dev
    $7 /hr, Pakistan
  • Aditya K.

    React Native Developer
    $10 /hr, India
  • Sarathi

    Software Enggineer
    $21 /hr, India
  • Nagendra Y.

    Software Consultant
    $19 /hr, Italy
  • Usha M.

    web designer
    $4 /hr, India
  • Akanksha A.

    Front End Web Developer
    $1 /hr, India

I am a techie at heart and love to explore new technologies. I have helped various companies evaluate their technology stack and help them improve. My responsibilities include "Platform selection and technical design", "Provide options", "Grow technical leader"and "Own the development methodology"

Khalid A. | CTO



Related Articles

Frontend Developer Job Description Template: Find...
Web Development

A front-end web developer is a responsible professional who makes the user-facing parts of websites and web applications. They are in charge of deploying visual and interactive ele...

Read More
Guide to Hiring a Great NodeJS Developers
Web Development

In today’s online world, businesses are earning profit from interactive websites and scalable applications. As an owner of such a business, you must pay attention to the trending t...

Read More
Natural Language Processing in Python
Web Development

NLP is a branch of data science that consists of systematic processes for analyzing, understanding, and deriving information from the text information in a smart and efficient mann...

Read More