Square Brackets

in JavaScript

This is an entry in Marek's JavaScript Compendium . Last updated 2020-04-08.

Square brackets are punctuation marks that always come in a pair: the opening square bracket [ and the closing square bracket ].

[];

Square brackets have 3 possible meanings.

Array Expressions

Square brackets are used in array expressions.

An empty array is created with an empty array expression. Empty arrays are the only situation where a pair of square brackets can be exist without anything in between them.

An array expression
[alpha, bravo, charlie];

An empty array expression
[];

Property Access

Square brackets are one of the two possible ways to access a property. The square bracket method allows you to provide the property name

Access an array value by its index
alpha[0];

alpha[i];

Access a property
bravo["length"];
bravo[charlie];

Computed keys in an object expression

When creating an object, you can use square brackets to provide a computed value for a key.

const customPropertyName = "alpha";

const gammaObject = {
  [customPropertyName]: "bravo",
};

Destructuring an array

You can use the square brackets in the left-hand-side of an assignment. This destructures the assignment, assuming that the value on the right-hand-side is an array.

const [first, second] = charlie;

Summary

That covers the different situations where square brackets can appear.

Read about the other types of brackets in JavaScript below.