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):
vara=[1,"2",[3]];a.length;// 3a[0]===1;// truea[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:
vara=[];a.length;// 0a[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):
vara=[];a[0]=1;// no `a[1]` slot set herea[2]=[3];a[1];// undefineda.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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access