Skip to content

Instantly share code, notes, and snippets.

@DevGW
Last active April 5, 2023 14:40
Show Gist options
  • Save DevGW/68f417be0150467700810ff74ca5c926 to your computer and use it in GitHub Desktop.
Save DevGW/68f417be0150467700810ff74ca5c926 to your computer and use it in GitHub Desktop.
Javascript :: Objects #js
// way to define object: with {}:
pusheen = {
name: 'Pusheen',
age: 7,
'color': 'gray'',
'cat sound': 'meow'
};
// left side is 'keys' and must use quotes only if the key is two words with a space in between
// can refer to them using brackets
console.log(pusheen['age']) <--- must use quotes because using bracket notation
// if you use quotes in key during object def then must use it when called:
console.log(pusheen['color'])
>gray
// or dot notation but NOT with keys that are in quotes!:
console.log(pusheen.age)
console.log(pusheen.'color') <--- unacceptable; must use bracket notation for this
>7
// can use concatenation with bracket notation but not with dot notation
console.log(pusheen['sound' + " " + 'sound']);
// can add to object easily:
pusheen['owner'] = "Meg";
// or
pusheen.owner = "Meg";
// remove a key entry:
delete pusheen.owner;
// or
delete pusheen['owner'] <--- must use quotes because using bracket notation
// other examples:
pusheen.age++
// for loops
for (let key in pusheen) {
console.log(key); // outputs all the keys
console.log(pusheen[key]); // outputs all the values
//but cannot use console.log(pusheen.key) because JS recognizes that as a string
console.log("Her " + key + " is " + pusheen[key]);
}
>Her name is Pusheen
>Her age is 7
>Her color is gray
>Her cat sound is meow
console.log(Object.keys(pusheen));
>[ 'name', 'age', 'color', 'cat sound' ]
let keys = Object.keys(pusheen);
for (let i=0; i < keys.length; i++) {
console.log(pusheen[keys[i]]);
}
// object keys can also hold arrays:
pusheen.color = ['gray', 'tabby']
console.log(pusheen.color[1]);
>tabby
// object keys can also hold other objects (NESTED OBJECTS):
pusheen.siblings = {
sister: 'Mary',
brother: 'Joe'
};
console.log(pusheen.siblings.sister);
>Mary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment