Objects
An object stores related data as key-value pairs.
const student = {
name: "Asha",
age: 20,
skills: ["HTML", "CSS"],
greet() {
return `Hi, I am ${this.name}`;
}
};
console.log(student.name); // dot notation
console.log(student["age"]); // bracket notation
student.city = "Karad"; // add property
delete student.age; // remove property
console.log(student.greet());Destructuring and spread
const { name, skills } = student; // pull out properties
const [first, second] = skills; // pull out array items
const copy = { ...student, age: 21 }; // copy and override
const all = [...skills, "JavaScript"]; // copy and extendLooping over objects
Object.keys(student); // ["name", "skills", "city", "greet"]
Object.values(student);
Object.entries(student); // [[key, value], ...]Optional chaining
console.log(student.address?.city); // undefined, no error
console.log(student.address?.city ?? "Unknown");JSON
JSON (JavaScript Object Notation) is a text format for exchanging data between servers and apps.
<script>
const data = { name: "Asha", marks: [80, 90] };
const text = JSON.stringify(data); // object -> string
const back = JSON.parse(text); // string -> object
document.write(text + "<br>" + back.marks[1]);
</script>Keys in JSON must be in double quotes, and functions cannot be stored in JSON.
Practice
Create an array of three book objects (title, author, price). Print the titles of books cheaper than 500, then print the whole array as JSON.
Practice tasks
Reading is not enough. Try these without copying code, then compare with the lesson.
- Create an object for a student and read properties with dot and bracket notation.
- Convert it to JSON and back.
- Loop over its keys with Object.keys.
Common mistakes
- Using dot notation for keys that contain spaces.
- Trying to JSON.parse invalid JSON.
Quick check
What does JSON.stringify do?
Turns a JavaScript value into a JSON string.
Are JSON keys quoted?
Yes, always with double quotes.