Programming

JavaScript objects: key and value

Write an object, read it with a dot and brackets, add a property and delete one.

All lessons · JavaScript lessons: learn from scratch

Write an object

An object keeps several pieces of information together. Each property is a key and a value. A colon goes between them, and properties are separated by commas. = is wrong here.

let telebe = {
  ad: "Əli",
  yas: 20
};
console.log(telebe.ad); // Əli
console.log(telebe.yas); // 20

Read and change

You read with a dot and change with equals. A missing property gives undefined. Inside square brackets the key must be in quotes. Without quotes JavaScript looks for a variable.

let mehsul = { ad: "Kitab", qiymet: 12 };
mehsul.qiymet = 15;
console.log(mehsul.qiymet); // 15
console.log(mehsul.reng); // undefined
console.log(mehsul["ad"]); // Kitab

Add, delete, array

A new property is added with a dot. delete removes it. An object can hold an array, and an array can hold objects. The first item's index is 0.

let telefon = { marka: "Honor", qiymet: 600 };
telefon.reng = "Qara";
delete telefon.qiymet;
console.log(telefon.qiymet); // undefined

let mallar = [
  { ad: "Qələm", qiymet: 2 },
  { ad: "Dəftər", qiymet: 5 }
];
console.log(mallar[1].qiymet); // 5

Questions

What goes between a key and a value? A colon. Equals is only used later, when you change the value.

Why is the comma needed? It separates properties. If you forget it, the code throws an error.

What does a missing property give? undefined. That says the information is not there.

Why does a[ad] fail? There are no quotes. The correct form is a["ad"]. a.ad also works.

Author: Nibras Code