Saturday, May 5, 2012

JavaScript Tips and Tricks -3

Floating point-
Binary floating-point numbers are inept at handling decimal fractions, so 0.1 + 0.2 is not equal to 0.3.
So in following code the alert will be "false".
function testFunction() {
    alert(0.1 + 0.2);
    if (0.1 + 0.2 == 0.3)
    alert("true");
    else
    alert("false");           

To tackle such issues, convert it into integer and then do the arithmetic. 
following code will give you the result as true -
function testFunction() {
    alert(1 + 0.2);
    if (1 + 0.2 == 1.2)
    alert("true");
    else
    alert("false"); 
}
Which means the issue is with 2 fractional numbers.

NaN-
NaN stands for "not a number", even though-
typeof(NaN) === 'number' // true
It also gives surprise result while using comparator -
NaN === NaN // false
NaN !== NaN // true
Javascript provides separate function 'isNaN' to check if the current value is NaN or not, here are the examples-
  • isNaN(NaN) // true
  • isNaN(0) // false
  • isNaN('oops') // true
  • isNaN('0') // false
isFinite is another function which can be used to check if it is NaN or not -
  • alert(isFinite(NaN)); // false
  • alert(isFinite(0)); // true
  • alert(isFinite('oops')); // false
  • alert(isFinite('0')); //true
The only problem with this function is, it will try to convert every input to a number, so in order to use it, we will have to check if the input is of type 'number' first, then check if it is finite.
The NaN can be produced by attempting to convert a string to a number when the string is not in the form of a number. For example:
alert(+'0'); // 0
alert(+'oop'); // NaN
If in any arithmetic operation any of the operand becomes NaN, then the result of that artihmetic operation will always be NaN.

JavaScriptObjects-
JavaScript's objects are never truly empty because they can pick up members from the prototype chain. In the following example if you check, the first 2 alert will give you a expected number as 1, but the last one will give you some crazy string with 1 appended in its last.The reason is that the count object inherits from Object.prototype, and Object.prototype contains a member named constructor whose value is Object. The += operator, like the + operator, does concatenation rather than addition when its operands are not numbers. Object is a function, so += converts it to a string somehow and concatenates a 1 to its end.
function testFunction() {
    var text = "This is one of the example of JavaScriptObject constructor";
    var words = text.toLowerCase().split(/[\s,.]+/);
    var count = {};
    for (i = 0; i < words.length; i += 1) {
    word = words[i];
    if (count[word]) {
        count[word] += 1;
    } else {
        count[word] = 1;
    }
    }
    alert(count['this']);
    alert(count.example);
    alert(count.constructor);