My question is about the Mozilla developer page: typeof operator
In the example chapter, whenever a comparison of the following form is done they comment it:
typeof Number(1) === 'number'; // but never use this form!
Although they never explain why. It's easy to see why it's a silly way of going about type-checking, but I'm curious as to the reason why they went out of their way to make that comment multiple times.
Any clues are welcome.
Note: Is it because Number() is a constructor called without the new operator? (my first guess)
Ps: Code examples were tested in Firefox's console version 27.0
They do explain why. On that same page, (a little bit past what you copied), it says
typeof new Boolean(true) === 'object'; // this is confusing. Don't use!
typeof new Number(1) === 'object'; // this is confusing. Don't use!
typeof new String("abc") === 'object'; // this is confusing. Don't use!
Notice how the new
keyword is there. In your example, there is no new
keyword. Kind of hard to spot, isn't it? So what they're trying to say is that since one's type is number
and the other's type is object
but the two look so similar, it's can be confusing what you mean.
Many problems can arise from thinking an object is a number because it acts like a number in some ways. For example, type checking with typeof
and comparisons with ===
.
Although, I can see that it isn't expressed very clearly on that page.
It is because of the lack of new
. Writing new Number(1)
creates a Number object with the value 1. This is seldom needed. However, Number(1)
does not create a Number object — instead, it just returns the number 1. This is confusing (since it visually looks like object creation) and unnecessary since you can just write 1
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With