[Javascript] Some Weird Facts About Javascript



Arguments Object:

The arguments object is an Array-like object corresponding to the arguments passed to a function.
function argumentFunction(){
 console.log(arguments[0]); 
 console.log(arguments[1]); 
 console.log(arguments[2]); 
}
argumentFunction("1","2","3");
output:
1
2
3
function Add() {
  var sum = 0;
  for(var j = 0; j < arguments.length; j++) {
    sum += arguments[j];
  }
  return sum;
}
Add(1, 2, 3, 4); // returns 10
Note: It is not an Array however it is similar to an array and it has length property in it.

Importance Of {} :

function method1() {
   return
   {
      name: 'foo'
   }
}
function method2() {
   return {
      name: 'foo'
   }
}
typeof method1() === typeof method2()   // return false
The first function return undefined and second method will return the object as expected. Parentheses play a major role so it should be handled with caution. 

Note: it’s good practice to put the opening parentheses on the current line.

Floating Number :

0.1+0.2  //0.30000000000000004
0.1+0.3  //0.4
0.2+0.4  //0.6000000000000001
0.2+0.5  //0.7
0.3+0.6  //0.8999999999999999
0.3+0.7  //1
Try 0.1+0.2 in your javascript environment and it is not going to return 3, however, 0.1+0.3 will return 0.4. 

0.1+0.2 == 0.3 will return false so we should be careful.

Sum of Arrays and Objects :

{} + [] // 0
[] + {} // "[object Object]"
[] + [] // ""
{} + {} // "[object Object][object Object]"
from the above code, we can come to a conclusion that 
{} + []  == [] + {} // returns false.
Equality Operators


These are some of the weird facts about Javascript. however, there are many and if you find anything weird please share it in the comment section.


If you enjoyed this article, Please share it with your developer friends and in social media. 
Follow our facebook page for latest updates.

Comments

  1. > "Note: It is not an Array however it is similar to an array and it has length method in it."

    The length is not a method, but a property instead. (because is not a function)

    Another issue is that I think you have a misunderstood in your "Importance Of Parentheses" section.
    This {} are called curly braces. The parentheses are this ones ().

    By the way, following Crockford's advice related to automatic semicolons insertion would also help to prevent that kind of problems.

    ReplyDelete

Post a Comment