Introduction
Of course, 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 a quest.
Concatenation
We all know that JavaScript uses the’+’ operator for both addition and concatenation. While concatenating a string with the numbers, the developer has to take care of the 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 the 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)
-
- }
Using variables without declarations
It's a very common mistake not to declare the variables in JavaScript code, as it allows us to use the variables without a declaration. I strongly recommend declaring 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 the same but in the 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 the 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 comparison), 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 a direct comparison.
- 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. I Hope, you enjoyed my content and I would be happy to hear your valuable feedback/comments.