Home > Articles

JavaScript - Create an Array

  • Print
  • + Share This

An introduction to how to create an array in JavaScript (JS).

Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE.
* See informit.com/terms

From the book

The popular way in which all the cool kids create arrays these days is to use an open and close bracket. The example that follows is a groceries variable that is initialized to an empty array:

An empty array
Click to view full-sized image

You have your variable name on the left, and you have a pair of brackets on the right that initializes this variable as an empty array. This bracket-y approach for creating an array is better known as the array literal notation.

Now, you will commonly want to create an array with some items inside it from the very beginning. To create these non-empty arrays, place the items you want inside the brackets and separate them by commas:

A non-empty array
Click to view full-sized image

Notice that the groceries array now contains Milk, Eggs, Frosted Flakes, Salami, and Juice. I just have to reiterate how important the commas are. Without the commas, you'll just have one giant item.


Learn how to program with JavaScript with JavaScript Absolute Beginner’s Guide.

  • + Share This
  • 🔖 Save To Your Account