HTML and CSS Reference
In-Depth Information
> var a = {};
> a instanceof Object
true
> a instanceof String
false
In JavaScript all objects inherit from the base
Object
, so the first result, comparing
String
, makes sense, as
does the third, comparing
a
, the empty object. In contrast, neither
Object
nor
a
inherits from
String
, so this should
return
false
(for details on how to structure inheritance and object-oriented (OO) code in JavaScript, see the section
“Inheritance the JavaScript Way”).
Type Coercion
JavaScript is a dynamically typed language, with automatic type conversion, meaning that types are converted as
needed, based on the operations being performed. Now, this type conversion is a little . . . misbehaved. Let's take a
look at the following example:
> x = "37" + 3
"373"
> x = 3 + "7"
"37"
> x = 10 - "3"
7
Wait, what?
JavaScript will automatically convert between numbers and strings, but the way it does so depends on the
operators involved. Basically, if the
+
operator is involved, it will convert any numbers to strings and assume that
+
means “concatenate.”
However, any other operators will instead convert strings to numbers and assume that the operators involved are
arithmetic.
What about an expression with more operators?
> x = "10" + 3 / 4 - 2
98.75
Can you tell what steps JavaScript took to get the result
98.75
? Personally, it took me a few seconds to step
through and figure it out.
In general, you should avoid automatic coercion between types, and instead be explicit. JavaScript has a couple
of handy built-in functions to convert from strings to numbers,
parseInt
and
parseFloat
:
> parseInt("654", 10)
654
> parseInt("654.54", 10)
654
> parseInt("654", 8)
428
> parseFloat("654")
654
> parseFloat("654.54")
654.54