HTML and CSS Reference
In-Depth Information
If you invoke this function with two numbers, the result is as expected:
> add(1,1)
If you accidentally pass a string as one of the parameters however, the result is very differ-
> add(1,"1")
Instead of adding the numbers, JavaScript has performed string concatenation between the
number and the string. It is unlikely that this is the result expected. This is one reason why
the typeof operator is so important in JavaScript, it allows the function above to be rewrit-
ten as follows:
function add(v1, v2) {
if (typeof v1 === "number"
&& typeof v2 === "number") {
return v1+v2;
} else {
throw "both arguments must be numbers";
This at least ensures data type issues will be identified at run-time, even if it does not high-
light these issues to the programmer who wrote the code allowing the function to be called
Using the “+” operator on different data types produces a variety of random res-
ults in JavaScript:
{} + [] = 0
[] + {} = Object
Search WWH ::

Custom Search