Table Of Contents
JavaScript Types
Planted:
Status: seed
Creating a Value
A value can be created in 2 different ways:
/index.js
Console
Using the constructor form results in an object wrapper around the primitive value.
This gives access to the helpful properties & methods such as toUpperCase
for a string.
/index.js
Console
Native Constructors
Each native constructor has its own prototype object.
These contain properties & methods unique to their object subtype.
For example: String.prototype.toUpperCase
.
When the constructor form is used, the returned object's prototype property is set constructor's prototype object.
This is how you get access to the properties & methods.
Date
The Date(..) constructor accepts optional arguments to specify the date/time to use. If omitted, the current date/time is used.
- To get the current Unix timestamp (the number of seconds since Jan 1, 1970):
Date.now()
. Note, this value is in milliseconds. - To get the timestamp of a specific date:
new Date("2020-07-04").valueOf()
. Note, this value is in milliseconds. - To get a date in ISO 8601 string format (international standard), invoke
toISOString()
method.
/index.js
Console
Error
An error object captures the current execution stack context into the returned object.
Stored in property stack
.
This includes the function call-stack and the line-number where the error object was created.
/index.js
Console
RegExp
If you require a variable in a regex, it must be created using the constructor form.
/index.js
Console
Number
JavaScript using binary floating-point numbers. This can result in the following bugs:
/index.js
Console
The representations for 0.1
and 0.2
are not exact.
When added, the result isn't 0.3
, it closer to 0.30000000000000004
.
Number.EPSILON
is predefined with this tolerance value that can be used as a workaround:
/index.js
Console
Special Values
NaN
- Not a Number+Infinity
-Infinity
-0
/index.js
Console
Boxing
A primitive like “abc”
is not an object.
However, you can call methods on it like "abc".length
.
This is possible through a technique called boxing.
When the interpreter sees a property or method call on a primitive, it calls the constructor form & passes in the primitive value, creating an object.
This object has properties & methods linked to it via the prototype chain.
Inspecting
Primitives
The typeof
operator inspects the type of the given value & returns one of seven string values (except for null
).
/index.js
Console
To test for a null
value using its type:
/index.js
Console
Note, variables don't have types. Only values do.
When using typeof
against a variable, it's asking what's the type of the value in this variable?
Object Subtypes
/index.js
Console
[[Class]]
Objects are tagged with an internal [[Class]]
property.
A classification (not related to class-oriented coding) corresponding to the built-in native constructor.
It can only be accessed through Object.prototype.toString(..)
.