Dot and Bracket Access

With a dot, the key is written in your code. stock.mouse always means the key mouse. But sometimes you only know the key when the program runs. It may come from the input or from a variable. For this, you use brackets [ ]:

const stock = { laptop: 12, mouse: 50 };
const product = "mouse";
console.log(stock[product]);
console.log(stock.product);

Output:

50
undefined

JavaScript first works out the value inside the brackets. Here product holds "mouse", so stock[product] reads the key mouse. But stock.product looks for a key that is really called product. There is no such key, so the result is undefined.

A simple rule: use a dot when you know the key while you write the code. Use brackets when the key is stored in a variable.

Brackets also work for adding or changing a property, and for keys with a space in them:

<!-- continues -->
stock[product] = 45;
stock["usb cable"] = 7;
console.log(stock);

Output:

{ laptop: 12, mouse: 45, 'usb cable': 7 }

When keys come from the input, a key may be missing. A missing key gives undefined. You can use ?? from the Operators section to replace it with a default value:

<!-- continues -->
console.log(stock["camera"]);
console.log(stock["camera"] ?? 0);

Output:

undefined
0

Use ?? here, not ||. If a product has a stock of 0, || would treat that 0 as missing. ?? only replaces null and undefined, so a real 0 stays 0.

Sometimes the object itself is missing. Reading a property of null or undefined crashes the program. Optional chaining ?. avoids that. It reads the property only if the value before it exists. Otherwise it gives undefined:

const order = null;
console.log(order?.customer);
console.log(order?.customer ?? "no customer");

Output:

undefined
no customer

You can read a?.b as "b, if a exists". Together, ?. and ?? let you read data that might be missing without crashing.

In the exercise, look up products by names from the input, and use ?? to give missing products a stock of 0.