Type Checking Techniques in JavaScript: Part 1 of 2

One of the early milestones in grocking any programming language is knowing how to use its data types. Should be easy for a small scripting language like JavaScript, right? And yet because of the elusive var keyword, implicit type conversion system, and dubious type checking tools, working with types can be a confusing task for even experienced developers.

Before we cover type checking in detail we must thoroughly review data types in JavaScript, the purpose of Part 1. In this short post I’ll quickly cover the conceptual differences between primitive and object types, identify the types, and compare the built-in, custom, and host objects. Because this topic has been so muddied over the years I’m going to profusely site sources.


 Primitives vs Objects

Like many languages, JavaScript has both primitive and object types. Let’s explore the fundamental differences between these two:

  Primitive types Object types
Has properties / methods? No Yes
Mutable values? No Yes
Memory allocation Fixed size Dynamic size
Variable holds Actual data value Memory address to object

[1]

 Primitive Types

The current JavaScript language spec defines 6 primitive types[2]

In action, examples are

var val;         // undefined is default variable value
val = 10000;     // number
val = 'woohoo';  // string
val = true;      // boolean
val = null;      // null         
val = undefined; // can also be assigned
val = Symbol();  // symbol

It’s worth mentioning here that variables are dynamically typed, able to be reassigned different types without explicit type casting.


 Object type

All objects belong to a single type: the object type. JavaScript has many objects that fall into three categories within this single “object” type[2]:

Built-in Objects have properties and methods defined within the JavaScript spec. Most are instantiated through constructor functions using the new operator, while three are static: JSON, Math, and Global. All the built-ins are stored on the Global object during page load before any JavaScript code executes[3]. They are[2]

We use these often.

// instantiate built-in object
var date = new Date();

Custom Objects are the objects we define as developers. We can define them in 3 ways:

Constructor functions and prototypes

function Product(sku, status) {
    this.getSku = function() { return sku; };
    this.stockStatus = status;
}
Product.prototype.getStatus = function() {
     return this.stockStatus;
};
var product = new Product('ABC1234', 'InStock');

Object literals

var product = {
    sku: 'ABC1234',
    status: 'InStock',
    getSku: function() { return this.sku; },
    getStatus: function() { return this.status; }
};

Object.create()

var product = Object.create(null, {
    sku: {
        value: 'ABC1234',
    },
    status: {
        value: 'InStock',
    },
    getSku: {
        value: function() { return this.sku; },
        enumerable: true
    },
    getStatus: {
        value: function() { return this.status; },
        enumerable: true
    }
});

It’s worth noting built-in and custom objects are also together called Native objects in the spec[4]. Objects that are not native are called Host objects.

Host Objects are provided by the host (browser) environment. Like built-in objects they’re stored on the Global window object. Most are static, unable to be instantiated with new, while others can be. Examples of host objects are:

// instantiate Host object, from AngularJS source code
function createXhr() {
    return new window.XMLHttpRequest();
}


 Primitive Wrapper Objects

You may have seen primitive types invoke object properties. Like it’s distant cousin Java, JavaScript has the concept of wrapper objects. This allows variables holding number, string, or boolean primitive types to temporarily access their corresponding object type’s properties and methods[5].

var str = 'booyah'; // primitive string
str.length;      // accesses String object's property, returns 6
str.charAt(0);   // accesses String object's property, returns 'b'



We’ve covered the differences between primitive and object types, the three different categories of objects, and identified what those types are. Pretty straightforward, right? Now we’re ready to explore the crooked paths of JavaScript’s type checking tools.

If you have comments or questions, please feel free to reach out on LinkedIn. I’d enjoy hearing from you.


 References:

[1] - Flanagan, D. (2006). JavaScript: The definitive guide (5th ed., pp. 54-55). Cambridge: O'Reilly.

[2] - EMCAScript 5.1 spec, http://www.ecma-international.org/ecma-262/5.1/#sec-4.2

[3] - EMCAScript 5.1 http://www.ecma-international.org/ecma-262/5.1/#sec-15

[4] - EMCAScript 5.1 http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.6

[5] - Flanagan, D. (2006). JavaScript: The definitive guide (5th ed., pp. 40-41). Cambridge: O'Reilly.

 
30
Kudos
 
30
Kudos

Now read this

Designing Normalized SQL Tables

SQL databases are reliable for complex queries, partial updates, transactions, and decoupling data modeling from application specific contexts. In this post we’ll cover how to normalize tables in 1NF, 2NF, and 3NF. We have a table. Name... Continue →