O'Reilly logo

JavaScript Enlightenment by Cody Lindley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 9. Array()

Conceptual Overview of Using Array() Objects

An array is an ordered list of values, typically created with the intention of looping through numerically indexed values, beginning with the index zero. What you need to know is that arrays are numerically ordered sets, versus objects, which have property names associated with values in non-numeric order. Essentially, arrays use numbers as a lookup key, while objects have user-defined property names. JavaScript does not have true associative arrays, but objects can be used to achieve the functionality of associate arrays.

Below, I store four strings in myArray that I can access using a numeric index. I compare and contrast it to an object-literal mimicking an associative array.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var myArray = ['blue', 'green', 'orange', 'red'];

console.log(myArray[0]); // logs blue using 0 index to access string in myArray

// versus

var myObject = { // a.k.a. associative array/hash, known as an object in JavaScript
   'blue': 'blue',
   'green': 'green',
   'orange': 'orange',
   'red': 'red'
};

console.log(myObject['blue']); // logs blue

</script></body></html>

Notes

  • Arrays can hold any type of values, and these values can be updated or deleted at any time.

  • If you need a “hash” (a.k.a. associative array), an object is the closest solution.

  • An Array() is just a special type of Object(). That is, Array() instances are basically Object() instances with a couple of extra functions (e.g., .length and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required