This blog post is dedicated to JavaScript newbie and JavaScript lover.
NaN is a "Not a Number" in JavaScript.
1. NaN error
- NaN error is very common for JavaScript developer. When you are looking some calculation that time generally come.
- One thing remember when you are working with JavaScript and declare any variable (var i;) and that variable value default as 'undefined'. so its a good practice to assign default value to the variable.
So take care it and don't forget to assign default value to variable else it will create a problem on some statement.
- When variable value is undefined and use that variable and calculate with some other variable that time getting NaN.
Let's see example.
2. isNaN function
- It's a global function in JavaScript to check if a value is a NaN value.
When you writing JavaScript code for calculation of numeric values and its a safe way to handle numeric value and check value is not a NaN value using IsNaN function.
Let's see example how to handle NaN value in JavaScript.
Hope this is useful for newbie of JavaScript.
NaN is a "Not a Number" in JavaScript.
1. NaN error
- NaN error is very common for JavaScript developer. When you are looking some calculation that time generally come.
- One thing remember when you are working with JavaScript and declare any variable (var i;) and that variable value default as 'undefined'. so its a good practice to assign default value to the variable.
//var first = undefined; var first; //So when you do console.log(first); its print in console 'undefined' console.log(first);
So take care it and don't forget to assign default value to variable else it will create a problem on some statement.
var first = 0; consol.log(first) //Console output is 0When getting NaN error?
- When variable value is undefined and use that variable and calculate with some other variable that time getting NaN.
Let's see example.
var first; var second = 4; console.log(first + second); //Output is NaN //As we prevent NaN, declare variable with default value //in our case first variable value is undefined so let assign value to variable. first = 0; console.log(first + second); //Output is 4
2. isNaN function
- It's a global function in JavaScript to check if a value is a NaN value.
When you writing JavaScript code for calculation of numeric values and its a safe way to handle numeric value and check value is not a NaN value using IsNaN function.
Let's see example how to handle NaN value in JavaScript.
var first; var second = 4; var sum = first + second if (isNaN(sum)){ console.log("value is a NaN"); }else{ console.log('Value is not a NaN'); }
Hope this is useful for newbie of JavaScript.
0 comments:
Post a Comment