Coercion
Abstract operation
Fundemantal building block for type conversion (coersion). Javascript implicitly performs automatic type conversion as needed. To clarify the semantics of certain constructs it is useful to define a set of conversion abstract operations.
These operations are not a part of the ECMAScript language; they are defined solely to aid the specification of the semantics of the ECMAScript language.
Instead of thinking them like actual methods we can think of them as set of algorithms, to aid specification.
ToPrimitive(hint)
It takes a hint paramater and trys to convert non primitive value to desired hint type.
ToString
ToNumber
ToBoolean(argument)
It converts argument to a value of type Boolean according to simple lookup table.
All the falsy values are: ""
, 0, -0
, null
, NaN
, false
, undefined
.
Everything else returns true.
Boxing
We can do thing like "foobar".length
, (5).toString()
on primitive values. We
access different properties on primitive values.
Well it turns out the we do not acces properties of primitive number rather it's
object counterpart is created by coersion. This special kind of coersion is
called Boxing
.
Fundamental objects (aka: Built-in Object, Native Functions)
You may be wondering what "object counterpart" is. It refers to fundemantal objects.
This is like the kind of bolted on object orientedness of JavaScript, the almost
Java-like mutation of JavaScript where we have in all of those cases where we
have primitive values, we now also have object representations with similar
behaviors. Like in Java when you want to make a string and you call it new String()
.
We have things like that in JavaScript.
Wrappers for primitives: Boolean
, Number
, String
.
Use new
for: Object()
, Array()
, Function()
, Date()
, RegExp()
, Error()
Don't use new
for: String()
, Number()
, Boolean()
Thanks to Boxing
we can use primitive values like they are objects. The notion
of "eveything is an object in Javascript" comes from here but as we can see it
is not correct. These are primitive values but they feel like objects.