Ofcourse, I agree that JavaScript may be quite simple and indeed easy to build basic client side functionality into a Web page and it’s a straight forward simple task for any experienced guy but still many JavaScript developers might face issues, while missing some basic understanding of JavaScript behavior.
Here, I am discussing some problems, which I faced some time back and sharing with you to aware, so that you can avoid such quest.
Concatenation
We all know that JavaScript uses ’+’ operator for both addition and concatenation. While concatenating string with the numbers, the developer has to take care of priority.
For example
- Var a = ‘10’;
- Var b = a+1;
We have to use parseInt() to convert the string to the integer
- Var a = ‘10’;
- Var b = parseInt(a)+1;
Working with floating point numbers
We all are aware that programming languages use binary form to store the data. While saving floating point numbers, we need to take care of such operations.
Ex
- var a = 0.2, b= 0.1;
- Var c = a+b;
- If(c ===0.3) {
- //some statements
- }
Using variables without declarations
Its very common mistake not to declare the variables in JavaScript code, as it allows us to use the variables without declaration. I strongly recommend to declare the variables, which can be either local or global depending on the scenario. Even the compiler doesn’t throw any exception.
Example
- function printMessage(){
- Var message = “hello world”;
- Alert(message);
- }
- function printMessage(){
- message = “hello world”;
- Alert(message);
- }
However, In both the snippets, the output will be same but in second snippet, the message variable will be treated as global and it is available outside the method as well, which means changing the value of a message variable outside the method reflects the output.
Using of Equality comparison operator
While comparing JavaScript variables, we can use either of ‘==’ and ‘===’. Before using these operators, one should know the real scenario. Unless you wanted to use ‘==’ (type insensitive comparision), I prefer to use ‘===’ (type strict operator)
Some examples are given below.
- 100 === 100
- “100” === 100
- 0 === false
- false === false
-
- 100 == 100
- 100 == “100”
- 1 == true
- 0 == false
Check variable is undefined or not
While checking the variable is undefined or not, we need to use typeof method instead of direct comparision.
- If (num === undefined){
- Var num = 10;
- }
This will throw an error that Uncaught ReferenceError: num is not defined. Instead, use the snippet given below.
- If ( typeof num === “undefined”){
- Var num = 10;
- }
Thanks for reading. Hope, you enjoyed my content and I would be happy to hear your valuable feedback/comments.