Creating Arrays

You create an array by writing its elements between square brackets [ ], separated by commas:

const shoppingList = ["apples", "chocolate", "bread rolls"];

Elements can be of any type: text, numbers or booleans (true and false). You can even mix them in one array. An array can also be empty, with no elements at all. You'll learn how to add elements to it later in this lesson.

const prices = [45, 12.5, 30];
const mixed = ["text", 123, true];
const nothingYet = [];
console.log(prices);
console.log(mixed);
console.log(nothingYet);

This prints:

[45, 12.5, 30]
["text", 123, true]
[]

The console shows text elements in quotes, and numbers and booleans without them, just as they are written in code. In practice, though, an array usually holds values of one kind, such as a list of names or a list of prices.

A common mistake is a missing comma between elements. With the code ["apples" "chocolate"], the program doesn't run at all and ends with SyntaxError: Unexpected string.

You'll often want to print an array with a label. Be careful how you join the label and the array. With +, JavaScript first turns the array into text, and the brackets and quotes disappear. If you separate the label and the array with a comma, console.log() prints the array as usual, with brackets and quotes, and puts a space after the label:

const shoppingList = ["apples", "chocolate", "bread rolls"];
console.log("To buy: " + shoppingList);
console.log("To buy:", shoppingList);

This prints:

To buy: apples,chocolate,bread rolls
To buy: ["apples", "chocolate", "bread rolls"]

A template literal turns the array into text too: `To buy: ${shoppingList}` also gives To buy: apples,chocolate,bread rolls. So when you print an array with a label, use a comma.

Instructions

Create an array with the elements "Josh", "Tim" and "Emily", in this order, and store it in a variable named coworkers (with const, as in the examples).

Print the array with the label Coworkers:, so that the console shows Coworkers: ["Josh", "Tim", "Emily"].

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

2/11

Next