Left ArrowBack

notes / JavaScript / types

types

A square with the letters 'JS' & the word 'types' next to it.

JavaScript Types

Last Tended

Status: seed

A list of the types in JavaScript
The text 'abc' on the left, new String('abc') on the right

Creating a Value

A value can be created in 2 different ways:

/index.js

Console

// literal form
const strPrimitive = "abc";

// constructor form 
// use the 'new' keyword & call a native constructor
const strObject = new String("abc");

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

const strObject = new String("abc");

console.log(strObject.toUpperCase())
A screenshot of the browser console showing the String Prototype object

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.

A code snippet detailing the prototype chain

Date

The Date(..) constructor accepts optional arguments to specify the date/time to use. Format used below is ISO 8601 format - YYYY-MM-DDTHH:mm:ss.sssZ (international standard).

/index.js

Console

// Create date object of today
const today = new Date()
console.log(today)


// Create date object of specified date
// Argument is in ISO 8601 format (time can be omitted)
const july4th2020Midnight = new Date('2020-07-04');   
console.log(july4th2020Midnight)


// Get Unix timestamp (the number of seconds since Jan 1, 1970)
// Value is in milliseconds
const todayTimestamp = new Date().valueOf()   // or Date.now()
console.log(todayTimestamp)


// Get date in ISO 8601 string format
const iSO8601 = new Date().toISOString()
console.log(iSO8601)

// Determine if a date is valid
function isValidDate(date) {
  return date instanceof Date && !isNaN(date);
}

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

function func(x) {
	if (!x) {
		throw new Error("x wasn't provided");
	}
}

func()

RegExp

If you require a variable in a regex, it must be created using the constructor form.

/index.js

Console

const url = 'https://google.com'
const name = "google";
const namePattern = new RegExp(`\\b(?:${name})+\\b`, "ig");
console.log(url.match(namePattern))

Number

JavaScript using binary floating-point numbers. This can result in the following bugs:

/index.js

Console

const result = 0.1 + 0.2 === 0.3;
console.log(result)

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

const result = 0.1 + 0.2 - 0.3 < Number.EPSILON;
console.log(result)

Special Values

  • NaN - Not a Number
  • +Infinity
  • -Infinity
  • -0

/index.js

Console

const result = Number.isNaN(1 / "a")
console.log(result);
A flowchart starting with 'abc'.length & ending with 3.

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.

An desert airfield with empty silos organised into rows & columns.

Inspecting

Primitives

The typeof operator inspects the type of the given value & returns one of seven string values (except for null).

/index.js

Console

console.log(typeof null)
console.log(typeof undefined)
console.log(typeof true)
console.log(typeof 42)
console.log(typeof "42")
console.log(typeof { foo: `bar` })
console.log(typeof Symbol())

To test for a null value using its type:

/index.js

Console

const a = null;
console.log(!a && typeof a === "object")

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

console.log(typeof function myFunc(){})

[[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(..).

/index.js

Console

console.log(Object.prototype.toString.call([]))
console.log(Object.prototype.toString.call(/regex-literal/i))
console.log(Object.prototype.toString.call("abc"))
console.log(Object.prototype.toString.call(42))
console.log(Object.prototype.toString.call(true))
console.log(Object.prototype.toString.call(null))
console.log(Object.prototype.toString.call(undefined))

instanceof

/index.js

Console

const strPrimitive = "abc"
console.log(typeof strPrimitive)
console.log(strPrimitive instanceof String)

const strObject = new String("abc");
console.log(typeof strObject)
console.log(strObject instanceof String)

Where to Next?

A sci-fi robot taxi driver with no lower body