javascript objects array notation

JavaScript Objects: Array Notation

In JavaScript, an object is like a box that stores information using key-value pairs. Think of it like a dictionary, where each word (the key) has a definition (the value).

There are two main ways to look inside this box and get the information you need: dot notation (like person.name) and array notation (like person["name"]). While dot notation is more common and easy to read, array notation is super useful in situations where dot notation just won’t work.

In this article, we’ll explore array notation—how it works, when to use it, and how it helps you work with JavaScript objects in a flexible way. Let’s dive in!

What Is Array Notation?

Array notation is a way to access values inside an object using square brackets ([]). Instead of writing object.key, you write object["key"]. The key goes inside the quotes, just like a string.

This is helpful because it lets you use keys that might not work with dot notation—like keys with spaces or symbols—or even use variables as keys.

Here’s a quick example to show the difference:

const person = { name: "Lucia", age: 25 };

console.log(person.name);       // Using dot notation: "Lucia"
console.log(person["name"]);    // Using array notation: "Lucia"

Both lines do the same thing—they get the value of the "name" property—but the second one uses array notation.

When and Why to Use Array Notation

While dot notation is great for simple cases, array notation is more flexible. There are times when you must use it. Let’s look at three common situations:

1. When the key has spaces or special characters

If a key has a space, hyphen, or starts with a number, dot notation won’t work. But array notation handles it just fine.

const car = { "car color": "red", "model-year": 2022 };

console.log(car["car color"]);    // Works
console.log(car["model-year"]);   // Works

You can’t use car.car color or car.model-year because JavaScript will get confused.

2. When using variables as keys

Sometimes you won’t know the key name ahead of time. Maybe you’re storing it in a variable.

const key = "age";
const user = { age: 30 };

console.log(user[key]); // 30

Dot notation (user.key) would look for a property literally named "key", which isn’t what we want.

3. When accessing properties dynamically (like from user input)

Let’s say a user types a property name, and you want to look it up:

const person = { name: "Luna", city: "Paris" };
const input = prompt("What do you want to know about Luna?");

console.log(person[input]);

Here, array notation lets you work with dynamic property names. Dot notation can’t do this.

So whenever you need special keys, variables, or dynamic access, array notation is the way to go!

Accessing Properties with Array Notation

To use array notation, you simply write the object name, followed by the key in square brackets and quotes:

object["key"]

The key must be a string (or a value that becomes a string), and it tells JavaScript which property you want to get.

Let’s look at a basic example:

const person = { "name": "Tom", "age": 20 };

console.log(person["name"]); // "Tom"
console.log(person["age"]);  // 20

You can also use array notation to access keys that contain spaces, hyphens, or other special characters—something dot notation can’t handle:

const obj = { "first-name": "Tom", "favorite color": "blue" };

console.log(obj["first-name"]);      // "Tom"
console.log(obj["favorite color"]);  // "blue"

Dot notation would break in these cases, but array notation handles them without any trouble.

Setting Properties with Array Notation

You can also add or update properties in an object using array notation. Just like with dot notation, you use the assignment (=) sign to set a value.

Here’s how to do it:

const obj = {};
obj["color"] = "blue";

console.log(obj); // { color: "blue" }

In this example, we created an empty object and added a "color" property using array notation.

You can also use this to change the value of an existing property:

obj["color"] = "green";

console.log(obj); // { color: "green" }

Array notation is super helpful when you want to add properties dynamically, like when the key comes from a variable or user input:

let key = "animal";

obj[key] = "dog";

console.log(obj); // { color: "green", animal: "dog" }

It gives you a lot of flexibility when working with objects!

Using Variables as Keys

One of the coolest things about array notation is that you can use variables as keys. This means you don’t have to hardcode the property name—you can store it in a variable and use that instead.

Here’s how it works:

const key = "score";
const player = {};

player[key] = 42;

console.log(player);       // { score: 42 }
console.log(player["score"]); // 42

In this example, the value of the key variable is "score", so player[key] = 42 is the same as writing player["score"] = 42.

This is super useful when you’re building objects dynamically, like based on user input, API data, or loops.

You can even do it in a loop like this:

const data = {};
const fields = ["name", "age", "country"];

for (let i = 0; i < fields.length; i++) {
  data[fields[i]] = "unknown";
}

console.log(data); // { name: "unknown", age: "unknown", country: "unknown" }

With array notation, your code becomes flexible and powerful!

Looping Through Object Keys

When you want to go through all the keys in an object, you can use a for...in loop. This loop gives you one key at a time, and you can use array notation to get the value that matches each key.

Here’s an example:

const obj = { a: 1, b: 2 };

for (const key in obj) {
  console.log(key + ": " + obj[key]);
}

In each loop, the variable key holds the name of a property. Since it’s a variable, we must use array notation (obj[key]) to get the value. Dot notation (obj.key) wouldn’t work because it would look for a property literally named "key"—which doesn’t exist.

This trick is great when working with objects where the property names aren’t fixed or known ahead of time.

Nested Access with Array Notation

Sometimes objects are stored inside other objects. This is called nesting, and you can still use array notation to access deeply nested values.

Let’s look at this example:

const data = { user: { "first name": "Sam" } };

console.log(data["user"]["first name"]); // "Sam"

Here’s what’s happening:

  • data["user"] gives you the inner object: { "first name": "Sam" }
  • Then, ["first name"] gets the value "Sam" from that object

You can also mix dot notation and array notation if you want:

console.log(data.user["first name"]); // "Sam"

This works because "user" is a simple key (no spaces), so dot notation is fine. But "first name" has a space, so array notation is needed there.

Using array notation helps you safely access tricky property names—even deep inside an object.

Using Array Notation with JSON

When you work with JSON (JavaScript Object Notation), it’s often in the form of a string. Before you can use it as an object in JavaScript, you need to parse it into an actual object. After that, you can access the properties using array notation, just like any other object.

Here’s an example:

const json = '{"fruit":"apple"}';
const obj = JSON.parse(json);

console.log(obj["fruit"]); // "apple"

In this example:

  1. We have a JSON string (json).
  2. We use JSON.parse() to turn the string into a regular JavaScript object (obj).
  3. Then, we access the "fruit" property using array notation (obj["fruit"]), which gives us the value "apple".

This is especially helpful when working with data from APIs or files, where the data often comes in JSON format.

Conclusion

In this article, we’ve seen how array notation offers a flexible way to access and manipulate properties in JavaScript objects. Whether you’re dealing with keys that have spaces, special characters, or even dynamic properties from variables, array notation has you covered.

To quickly summarize, array notation shines when:

  • You need to access properties with unusual characters (like spaces or hyphens).
  • You want to use variables as keys.
  • You’re working with dynamic properties (such as user input or data from external sources like JSON).

Both dot notation and array notation have their places in JavaScript, and understanding when and how to use each will make you a more confident programmer. Don’t be afraid to experiment with both and see how they fit into your projects!

Scroll to Top