JavaScript objects: Create, read, and update properties

A JavaScript object groups related values as named properties. Write an object literal with braces, read a known name with dot notation, or use brackets when the name comes from a variable. Assignment updates an existing writable property or adds an ordinary missing one.

Create an object with a literal

Each entry pairs a name with a value. Separate entries with commas. const prevents assigning another object to the variable, but the stock property of this ordinary object can change.

const product = {
  name: 'Notebook',
  price: 1200,
  stock: 3
};

console.log(product.name);          // 'Notebook'
console.log(product['price']);      // 1200
product.stock = 2;
console.log(product.stock);         // 2

Add properties and read a variable key

Start with {} when you only know the values later. Use brackets for names such as font-size and for a key held in a variable. settings.key reads a property literally named key. See the property access rules.

const settings = {};
settings.theme = 'dark';
settings['font-size'] = 16;

const key = 'theme';
console.log(settings[key]);       // 'dark'
console.log(settings.key);        // undefined
console.log(settings['font-size']); // 16

Compare {} and new Object()

Both expressions below create ordinary objects. Use a literal to write initial properties directly. Two independently created objects are distinct even when they contain the same values. With an argument, the Object constructor may behave differently.

const first = {};
const second = new Object();
first.count = 1;
second.count = 1;

console.log(first.count, second.count); // 1 1
console.log(first === second);          // false

Distinguish missing, undefined, and inherited properties

A value of undefined leaves two possibilities. timezone is present with no assigned meaning yet, while currency is absent. Use Object.hasOwn() to check properties stored directly on the object.

{
  const settings = { theme: 'dark', timezone: undefined };
  console.log(settings.timezone, settings.currency); // undefined undefined
  console.log(Object.hasOwn(settings, 'timezone'));  // true
  console.log(Object.hasOwn(settings, 'currency'));  // false
  console.log('toString' in settings);                // true
  console.log(Object.hasOwn(settings, 'toString'));   // false
}

The in operator also checks inherited properties. An ordinary object inherits toString, so in reports it while Object.hasOwn() does not.

Try a complete inventory example

Save the full example in UTF-8 as object-example.html and open it in a browser. Choose a property in the menu. The program reads its name from the selection and uses brackets to get its value.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Create an object and read its properties</title>
</head>
<body>
<label for="property">Property to inspect</label>
<select id="property">
  <option value="price">price</option>
  <option value="name">name</option>
  <option value="stock">stock</option>
  <option value="color">color</option>
  <option value="missing">missing</option>
</select>
<button id="sell" type="button">Sell one</button>
<button id="reset" type="button">Reset</button>
<pre id="output" aria-live="polite"></pre>
<script>
const product = { name: 'Notebook', price: 1200, stock: 3 };
product['color'] = 'Blue';

const propertySelect = document.querySelector('#property');
const output = document.querySelector('#output');

function showProduct() {
  const key = propertySelect.value;
  const selected = Object.hasOwn(product, key)
    ? `${key} = ${product[key]}`
    : `Property ${key} is missing.`;
  output.textContent = `${selected}\nStock: ${product.stock} / Value: ${product.price * product.stock}`;
}

propertySelect.addEventListener('change', showProduct);
document.querySelector('#sell').addEventListener('click', () => {
  if (product.stock > 0) product.stock -= 1;
  showProduct();
});
document.querySelector('#reset').addEventListener('click', () => {
  product.stock = 3;
  propertySelect.value = 'price';
  showProduct();
});
showProduct();
</script>
</body>
</html>

The initial price is 1200, with 3 in stock and a total value of 3600. Select color for Blue or missing for a message indicating absence. Each sale reduces stock to a minimum of zero. Reset restores stock to 3 and selects price.