Objects

A Computer is An Object
Computer Properties
-
storage: 1 TB
-
type: macBookPro
-
memory : 16GB
-
yearReleased: 2020
An Object is an unordered collection of properties & methods that are stored using key, value pairs
Syntax for Object Literals
let computer = {
type: 'macBookPro',
storage: '1TB',
memory: '16GB',
yearReleased: '2020',
}
Objects Traits
-
keys are always strings
-
keys must be unique
-
values can be any data type
let testObject = {}
testObject['color'] = 'green'
key | value |
---|---|
color
'green'
testObject.number= 10
number
10
Syntax for Setting Properties
const idName = 'id'
id
testObject[idName] = '2525'
'2525'
- bracket notation
- dot notation
- bracket notation
Getting Object Values
We can access propertiies using a similar notation to what we used to set the key,value pairs
key | value |
---|---|
color
'green'
number
10
id
'2525'
testObject
let val1 = testObject['color']
val1 = 'green'
let val2 = testObject.number
bracket notation
dot notation
val2 = 10
What about Methods?
Methods are just functions

Method Syntax
Set method inside the Object Literal
let testObject = {
sayHello: function(){
console.log('Hello testObject')
}
}
testObject.sayHello()
'Hello testObject'
let testObject = {
sayHello: function(){
console.log('Hello testObject')
}
}
testObject.sayGoodbye = function(){
console.log('Goodbye testObject')
}
OR
testObject['sayGoodbye'] = function(){
console.log('Goodbye testObject')
}
Set method outside of Object
testObject.sayGoodbye() Invocation
'Goodbye testObject'
Object Recap
a. objects are collections that store properties as unique keys & value pairs
b. we can get and set properties by using either bracket notation or dot notation
c. methods are just functions encapsulated inside an object.

Objects
By JD Richards
Objects
- 35