Look at the code snippet below:

function foo() {
  var a = "5";
  var b = "4";
  alert(a + b);
}

This will result in 54 being alerted.  Nothing strange here.

Now look at this:

function foo() {
  var a = "5";
  var b = "4";
  alert(a - b);
}

This will result in 1 being alerted. So, what is happening here?

This has got to do with the way JavaScript resolves types.  + is overloaded in JavaScript. Operator +  works with Strings as well as Numbers. So whenever a + is involved in an operation, if one of the operands is a String the other is converted to a String. That is why, in the first operation we got 54.  But, whenever we try a mathematical operation other than +, JavaScript tries to convert the operands to a Number and then does a mathematical operation on the operands. If one of the operands cannot be converted to a Number, the result of the operation will be NaN (Not a number).

Can you work out as to what the below will alert?

function foo() {
  var a = "5";
  var b = "4";
  alert(+a + +b);
}
Advertisements