Properties in Square Brackets

There is another way to read a property: square brackets with the key in quotes.

const stock = {
    apples: 12,
    lemons: 0,
    peaches: 30
};

console.log(stock["peaches"]);
30

stock["peaches"] means the same as stock.peaches; it's just longer. So why use it? Because you can put any value inside the brackets, a variable too. Then you don't need to know the key when you write the program:

const stock = { apples: 12, lemons: 0, peaches: 30 };

const fruit = "apples";
console.log(stock[fruit]);
12

JavaScript first looks into the variable fruit, finds the text "apples" in it, and then reads the property apples. This is most useful in functions, where the key comes as an argument:

const stock = { apples: 12, lemons: 0, peaches: 30 };

function isInStock(fruit) {
    return stock[fruit] > 0;
}

console.log(isInStock("apples"));
console.log(isInStock("lemons"));
true
false

Each call reads a different property, and the function works for any fruit, even one you add to the object later.

Typical mistakes:

  • stock.fruit doesn't look into the variable fruit. It looks for a property whose key is fruit, doesn't find one, and you get undefined. The same happens with stock["fruit"]: in quotes, "fruit" is just text, not the variable.
  • stock[apples] without quotes looks for a variable apples, which doesn't exist: ReferenceError: apples is not defined.

So: when you know the key as you write the code, use a dot. When the key is in a variable, use square brackets, without quotes. Square brackets work for changing values too: stock[fruit] = 5;.

Instructions

The function printStock should print how many pieces of the given fruit are in stock, but it prints undefined. Fix it so that the first two lines are apples: 12 and peaches: 30.

Complete the function sell: it should decrease the stock of the given fruit by 1. The program sells two peaches and one apple, so the last two lines should then be peaches: 28 and apples: 11.

Start programming for free

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

Or sign up with:

4/9