Introduction
JavaScript is the language of the Web. This series of articles will talk about my observations, learned during my decade of software development experience with JavaScript. What mistakes developers generally make and what differences they should be aware of.
Part 4 will focus in detail on JavaScript's common mistakes. Before moving further let us look at the previous articles of the series:
Mistake 1: Equality checks
Type converting operator like == converts operands if they are not of the same type. To demonstrate or test you could try the following statements and see the output.
- 1 == 1 // true
- "1" == 1 // true
- 1 == '1' // true
- 0 == false // true
Strict operators like === don’t convert operands and returns true if the operands are strictly equal.
- 1 === 1 // true
- "1" === 1 // false
- 0 === false // true
Mistake 2: Concatenation
Javascript uses + operator for concatenation & addition. Now, another common mistake is to use mix number & string operands. For ex-
- var y = ‘10’;
- var x= 1 + y; // will give 110
Use function parseInt in such a scenario to rescue you, otherwise, you’ll spend time in debugging.
- var x= 1 + parseInt(y); // will give 11
Mistake 3: Float point numbers
- var f = 0.1;
- var g = 0.2;
- var h= f + g;
- (h === 0.3) // 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) // true
Mistake 4: Not using var to declare variables
Scenario 1
- var foo = ‘test’;
- console.log (foo); // will print test
Scenario 2
- foo = ‘test’;
- console.log (foo); // will print test
Q: What is the difference between two approaches?
Scenario 1
- function func1() {
- var foo = 'test';
- console.log(foo); // will print test
- };
- func1();
- console.log(foo);

Scenario 2
- function func1() {
- foo = ‘test’;
- console.log(foo); // will print test
- }();
- console.log(foo); // will print test

Mistake 5: Usage of undefined as a variable


I hope you’ll find it useful and you can give your suggestions in the comment box if you know some other mistake patterns.
Read more articles on JavaScript
Mohit SharmaPosted May 26, 2016, 7:31 AM
Nice
Amit DavePosted May 3, 2016, 6:56 AM
Nice article!
Guest UserPosted Apr 28, 2016, 3:19 AM
Thanks everybody
Sunny SharmaPosted Apr 26, 2016, 5:47 PM
Floating numbers are saved in 64 bits... nice share!
Debasis SahaPosted Apr 26, 2016, 10:18 AM
Nice One..
Vignesh ManiPosted Apr 26, 2016, 8:08 AM
Nice one
Guest UserPosted Apr 26, 2016, 7:20 AM
Thanks guys! please let me know what you would like to read more on JS.
NitinPosted Apr 26, 2016, 5:15 AM
thanks for sharing
Gowtham RajamanickamPosted Apr 26, 2016, 4:11 AM
good one
Nishant MittalPosted Apr 26, 2016, 4:10 AM
Well Said Common Mistakes..still sometimes we use to do ...good one