Keys point to values "Look up" (like a dictionary)
var person = {
name: 'Martin',
hair: 'brown',
height: 188
}
console.log(person.name) // 'Martin' accessed via _dot notation_
console.log(person['name']) // 'Martin' accessed via _bracket notation_
Objects hold data and methods to act on that data.
person // variable lookup, object is returned
. // property lookup operator
name // at this location
We can even act on the data we get back:
console.log('Height in inches:', person.height / 2.54)
But wait, what's happening in console.log()
? console
is an object!! Hiding before our eyes.
> console
Console {
log: [Function: bound consoleCall],
warn: [Function: bound consoleCall],
error: [Function: bound consoleCall],
table: [Function: bound consoleCall],
...
}
console
's keys are mapped to functions! We can output to the console using console.log('hi)
, 'console.warn('uh oh')
, or console.error('yikes')
, all of which are keys present in the console
object, mapping to functions that consume the argument we pass into it in quotes (in this case 'hi'
, 'uh oh'
, and 'yikes'
). We invoke functions in javascript using parentheses:
var person = {
name: 'Martin',
height: 188,
hair: 'brown',
laugh: function() {
return console.log('hahahahaha')
}
}
person.laugh() // 'hahahahaha' from the invoked function
person.laugh // ƒ () {
// console.log('hahahahahaha')
// }
I think that we are starting to see the power of objects as groups of data and functions to act on that data. Let's give our person
some friends:
var person = {
name: 'Martin',
height: 188,
hair: 'brown',
friends: [],
addFriend: function(newFriend) {
person.friends.push(newFriend)
}
}
person.addFriend('Scott')
person.friends // ['Scott']
Cool! We're able to transform data within our person
object using functions that we can group with the data itself.
What happens if we assign person
to another variable?
var person = {
name: 'Martin',
...
}
var martin = person // martin now contains a *reference* to the person object
martin.height = 180
person.height // 180 ~waaaaaaaat is happening~
The only way you can create a new instance of an object is to use a constructor function. These usually have capitalized names.
function Person(name) {
return {
name: name,
height: 180,
hair: 'brown',
friends: [],
addFriend: function(newFriend) {
this.friends.push(newFriend)
}
}
}
var martin = new Person('martin')
console.table(martin) // martin is born, also sweet table!
var scott = new Person('scott')
console.table(scott) // scott is his own man!
Objects are fun + powerful javascript friends, and we'll be using them a lot in our web development journeys.