Friday, 8 December 2017

JavaScript | Common mistakes by developers in JavaScript

Mostly developers face many issues because of silly programming mistakes.

Mistakes are,

Equality checks
We check the variables for certain values, but there are two types of operators, we can use. I suggest using strict operators over type converting.

Type converting operator like == converts operands, if they are not of the same type. To demonstrate or test, you can try the following statements and see the output.

Example
"1" == 1
Output: true

So, the mistakes of using == operator result in TRUE value for 1==”1”, which can be wrong in a real scenario. Therefore, it is always advisable to use type strict operators.

Strict operators like === don’t convert operands and returns true, if the operands are strictly equal.

"1" === 1
Output: false

Concatenation
In Javascript, we use "+" operator for concatenation & addition. Now, another common mistake is to use mix numbers & string operands.

Example
var y = ‘10’;  
var x= 1 + y;
Output: 110  

Use function parseInt in such scenario to rescue you, otherwise you’ll spend time in debugging.

var x= 1 + parseInt(y);
Output: 11

Float point numbers
Programming languages are not always correct to match the floating point numbers.

Example
var a = 0.1;  
var b = 0.2;  
var c= a + b;  
(a === 0.3)
Output: false because h is 0.30000000000000004  

Floating numbers are saved in 64 bits. Hence, the right way to do is:

var h = (f * 10 + g * 10) / 10; // h is 0/3  
(h === 0.3)
Output: true 

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...