JavaScript’s Magical Tips Every Developer Should Remember
By: Tarun Gupta
Tags: Programming, Technology, Productivity, JavaScript, Software Engineering

JavaScript is the most popular technology for full stack development. While I have been focusing mainly on Node.js, and somewhat Angular.js, I have realised that there are always some tricks and tips involved in every programming language irrespective of its nature of existence.

I have seen (so many times) that we programmers can tend to make things over complicated, which in-turn leads to problems and chaos in the developing environment. It is beautifully explained by Eric Elliott in his post.

Without further ado let’s get started with the cool tips for JavaScript:

Use “var” when creating a new variable.

Whenever you are creating a new variable always keep in mind to use “var” in front of the variable name unless you want to create a global variable. This is so because if you create a variable without using “var” its scope will automatically be global which sometime creates issues, unless required.

There is also the option to use “let” and “const” depending on the use case.

→ The let statement allows you to create a variable with the scope limited to the block on which it is used.

Consider the following code snippet.

function varDeclaration(){

let a =10;

console.log(a); // output 10

if(true){

let a=20;

console.log(a); // output 20

}

console.log(a); // output 10

}

It is almost the same behaviour we see in most language.

function varDeclaration(){

let a =10;

let a =20; //throws syntax error

console.log(a);

}

Error Message: Uncaught SyntaxError: Identifier ‘a’ has already been declared.

However, with var, it works fine.

function varDeclaration(){

var a =10;

var a =20;

console.log(a); //output 20

}

The scope will be well maintained with a let statement and when using an inner function the let statement makes your code clean and clear.

I hope the above examples will help you better understand the var and let commands.

→ const statement values can be assigned once and they cannot be reassigned. The scope of const statement works similar to let statements.

function varDeclaration(){

const MY_VARIABLE =10;

console.log(MY_VARIABLE); //output 10

}

Question: What will happen when we try to reassign the const variable?

Consider the following code snippet.

function varDeclaration(){

const MY_VARIABLE =10;

console.log(MY_VARIABLE); //output 10

MY_VARIABLE =20; //throws type error

console.log(MY_VARIABLE);

}

Error Message : Uncaught TypeError: Assignment to constant variable.

The code will throw an error when we try to reassign the existing const variable.

2. Always use “===” as comparator instead of “==” (Strict equal)

Use “===” instead of “==” because when you use “==” there is automatic type conversion involved which can lead to undesirable results.

3 == ‘3’ // true

3 === ‘3’ //false

This happens because in “===” the comparison takes place among the value and type.

[10] == 10 // is true

[10] === 10 // is false

'10' == 10 // is true

'10' === 10 // is false

[] == 0 // is true

[] === 0 // is false

'' == false // is true

'' === false // is false

3. ‘undefined, null, 0, false, NaN, ‘’ (empty string)’ are all false conditions.

4. Empty an array

var sampleArray = [2, 223, 54, 31];

sampleArray.length = 0; // sampleArray becomes []

5. Rounding number to N decimal places

var n = 2.4134213123;

n = n.toFixed(4); // computes n = "2.4134"

6. Verify that your computation will produce finite result or not.

isFinite(0/0); // false

isFinite('foo'); // true

isFinite('10'); // true

isFinite(10); // true

isFinite(undefined); // false

isFinite(); // false

isFinite(null); // true

Lets take an example to understand the use case of this function, suppose you have written a database query over a table which contains large amount of data and after the execution of query you are not certain about all the possible result values of that query. The data of query changes on something that you put dynamically in the query. In such a case you are not sure about finite property of the result and if you use that result directly it can give you infinite condition, which can break your code.

Hence, it is recommended to use isFinite() before any such operations so that infinite values can be handled properly.

7. Use a switch/case statement instead of a series of if/else

Using switch/case is faster when there are more than 2 cases, and it is more elegant (better organised code). Avoid using it when you have more than 10 cases.

8. Use of “use strict” inside your file

The string “use strict” will keep you from worrying about declaration of a variable which I mentioned in 1st point.

// This is bad, since you do create a global without having anyone to tell you

(function () {

a = 42;

console.log(a);

// → 42

})();

console.log(a);

// → 42

“use strict” will keep you away from making above mistake. Using “use strict”, you can get quite a few more errors:

(function () {

“use strict”;

a = 42;

// Error: Uncaught ReferenceError: a is not defined

})();

You could be wondering why you can’t put “use strict” outside the wrapping function. Well, you can, but it will be applied globally. That’s still not bad; but it will affect if you have code which comes from other libraries, or if you bundle everything in one file.

9. Use && and || to create magic

“” || “foo”

// → “foo” undefined || 42

// → 42 function doSomething () {

return { foo: “bar” };

}

var expr = true;

var res = expr && doSomething();

res && console.log(res);

// → { foo: “bar” }

Additionally, don’t forget to use a code beautifier when coding. Use JSLint and minification (JSMin, for example) before going live. This will help you maintain a coding standard in your project and make it as standard as possible.

The above is a mere reflection of the power of JavaScript.