DevNotes
@devnotes ·
JavaScript Part 7: Objects
Arrays hold lists. Objects hold the details of one thing, like a user or an order. Nearly all real data, including everything an API sends you, is objects and arrays of objects.
Making one and reading it
Each entry is a key and a value, with a colon between them. You read a value with a dot, or with square brackets and the key as a string. Brackets are for when the key is stored in a variable:
Changing it
Reading a key that doesn't exist gives undefined. Reading a key on something that is itself undefined crashes:
?. (optional chaining) stops and gives undefined when the part before it is missing. It's very useful with data from an API, where some fields may not be there.
Objects inside objects, and arrays of objects
Methods
A function stored in an object is called a method:
Inside a method, this is the object the method was called on. this has some tricky rules in other places, so for now, use it only inside methods like this one.
Destructuring: unpacking values
You'll see this all the time in React, so get comfortable with it now.
Spread: copy with changes
...student copies every key into a new object, and age: 22 replaces one of them. The original stays as it was. Arrays work the same way: [...fruits, "kiwi"] is a new array with one extra item. React relies on this a lot.
JSON
When data travels between a server and your page, it travels as JSON: text that looks just like a JavaScript object.
In JSON, keys always use double quotes, and there are no functions or comments.
Try it
Make an object for your favourite film with a title, a year and an array of actors. Print a sentence like "Lagaan (2001) stars Aamir Khan and Gracy Singh" using a template literal, and join(" and ") on the actors. (join turns an array into one string, with your text between the items.)
Next: JavaScript Part 8: Change the page with the DOM
Join WIK to like and reply to DevNotes and see more like this.