Coding ยท ยท

Objects

In JavaScript, you generally are choosing to do things with arrays or objects. Actually, technically in JavaScript arrays and functions are special types of objects.

While an array is an ordered (not the same as sorted) set of items, objects aren't ordered. Think of objects as key-value stores, where you store as many values as you'd like, each with a different key (which can be a number or a string).

Syntactically, you'll notice that objects use {} while arrays use [].

let stuff = { // makes a new object
  name: 'Mr Gordon', // name is a key/attribute/property of 'stuff'
  age: 21
}
stuff.height = '181cm' // change the value stored in the key 'height'
console.log(stuff.age) // prints 21
console.log(stuff['age']) // also prints 21
let key = 'age'
console.log(stuff[key]) // also prints 21
console.log(stuff.key) // undefined
delete stuff.age // stuff.age no longer exists
stuff = {} // resets/empties the object

You can also start with an empty object:

let stuff = {}
stuff.blah = 'yes'
stuff.nope = 'no'
for (let i = 0; i < 5; i++) {
  stuff[i] = `hello ${i}`
}

Note that you can't push() to objects, but you can use either strings or numbers as keys.

Iterating over objects

You can iterate over the keys in an object:

for (let key in stuff) {
  console.log(key) // e.g. 'name'
  console.log(stuff[key]) // e.g. 'Mr Gordon
}

Sometimes its useful to turn the keys into an array:

console.log(Object.keys(stuff)) // [name, age, height]
Object.keys(stuff).forEach(key => console.log(`His ${key} is ${stuff[key]}`))

Object values can be anything, including numbers, strings, arrays and even functions or nested objects:

stuff.walk = () => console.log('I can walk!') // a function
stuff.walk()
stuff.favNumbers = [11, 21, 42] // an array
stuff.schoolsTaught = { thing: "so cool", blah: "yes" } // a nested object

Keys can be referenced with .keyName or ['keyName']

console.log(stuff.schoolsTaught.thing)
console.log(stuff['schoolsTaught']['thing']) // does same as line above
console.log(stuff.schoolsTaught['thing']) // does same as line above
console.log(stuff['schoolsTaught'].thing) // does same as line above
let prop = 'schoolsTaught'
console.log(stuff[prop].thing) // but stuff.prop.thing wouldn't work

JSON and a very simple database

JSON (JavaScript object notation) is a portable data format that can be used in any language, not just JavaScript. Turn any object (including an array, but excluding functions) into it with JSON.stringify() and convert back to a JavaScript object with JSON.parse(). Bun even includes a method we can use when reading a JSON file which saves us from having to JSON.parse() it.

Save this file as database.js:

// read JSON in from the .json file
let fileName = 'db.json'
let db = {}
let file = Bun.file(fileName)
if (await file.exists()) db = await file.json()

// change the database
db.something = 'hello there'
if (!db.count) db.count = 1
else db.count++

// show the current contents of the database
console.log(db)

// save our 'database' back to the .json file
Bun.write(fileName, JSON.stringify(db))

Run it with bun database.js. Then run it again. And again. You should see the count going up. You'll also notice a file in the folder called db.json, which you can see the contents of with cat db.json. You can delete this simple database with rm db.json.