Chapter 2. Values

arrays, strings, and numbers are the most basic building blocks of any program, but JavaScript has some unique characteristics with these types that may either delight or confound you.

Let’s look at several of the built-in value types in JS, and explore how we can more fully understand and correctly leverage their behaviors.

Arrays

As compared to other type-enforced languages, JavaScript arrays are just containers for any type of value, from string to number to object to even another array (which is how you get multidimensional arrays):

var a = [ 1, "2", [3] ];

a.length;       // 3
a[0] === 1;     // true
a[2][0] === 3;  // true

You don’t need to presize your arrays (see “Array(..)”), you can just declare them and add values as you see fit:

var a = [ ];

a.length;   // 0

a[0] = 1;
a[1] = "2";
a[2] = [ 3 ];

a.length;   // 3
Warning

Using delete on an array value will remove that slot from the array, but even if you remove the final element, it does not update the length property, so be careful! We’ll cover the delete operator itself in more detail in Chapter 5.

Be careful about creating “sparse” arrays (leaving or creating empty/missing slots):

var a = [ ];

a[0] = 1;
// no `a[1]` slot set here
a[2] = [ 3 ];

a[1];       // undefined

a.length;   // 3

While that works, it can lead to some confusing behavior with the “empty slots” you leave in between. While the slot appears to have the undefined value in it, it will not behave the same as if the slot is explicitly set (a[1] = undefined ...

Get You Don't Know JS: Types & Grammar now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.