Archive for September, 2013

NaN…what?

NaN is the only value in Javascript that is not equal to anything, including itself.
if(NaN !== NaN){
  alert("what??? how???  huh???");
}
Therefore, one way you could check if a variable has the value of NaN is to do something like this:
if(yourVar !== yourVar) { // thanks Vigen Sarksyan for this suggestion
  alert("yourVar has a value of NaN");
}
While this will work, it is not recommended as most people will think you wrote this by mistake and assume there is a bug in your code. The correct way to check if a variable contains a NaN is by calling the isNaN function:
if(isNaN(yourVar)) {
  alert("yourVar has a value of NaN");
}
This is much more readable and produces the same result.

Also note the fact that while NaN stands for “Not a Number”, calling typeof(NaN) returns “number”…so it’s a number that is not a number 🙂

Removing values from nested Arrays in MongoDB

Deleting values from beep nested array by calling the ‘update’ function can be tricky to get right when using MongoDB. Suppose you have this structure:
{
  _id: 'someID',
  foo: [
    {
      bar: [
        {
          title: 't1'
        },
        {
          title: 't2'
        }
      ]
    },
    {
      bar: [
        {
          title: 't3'
        },
        {
          title: 't4'
        }
    }
  ]
}
Now suppose we want to remove the object with title ‘t1’ from the array it is in. I first tried doing this:
 db.myCollection.update({ _id : 'someID' },
                        { $pull : { 'foo.bar' : { 'title' : 't1' } } }); 
However, this did not seem to work. Adding a ‘.$’ after foo seemed to do the trick:
 db.myCollection.update({ _id : 'someID' },
                        { $pull : {'foo.$.bar' : { 'title' : 't1' } } });
I hope this saves you some time. Good luck!