{
key: value
property: value
method: function () {}
}
Object is a value type that contains key value pairs inside curly barces. Keys are also known as properties and everything in JavaScript that isn’t a primitive type is an object. Primitive types are Strings, Numbers, Booleans, Undefined, Null and Symbols (ES6). Yes, arrays are objects. Functions are objects too. The difference between functions and objects is that functions can be called.
When variables are used in objects they’re called properties and when functions are used inside and object they’re called methods.
to create an object, we assign a variable to an object literal
1var students = {};
NOTE: [ ]
create an array, { }
create an object. Pay attention if you’re a beginner, i have already mixed these in code, code didn’t work..
1var students = {
2 name: "Dave"
3};
property/key doesn’t need to be in quotes.
1var students = {
2 name: "Dave",
3 grades: [99, 85, 80, 79]
4};
separate each key:value pair with a ,
the last pair doesn’t need one.
FYI, there are multiple ways in which you can create an object
myObj = {}
Object.create()
the methodnew
keyword new Car()
You access values by their property names:
person['name']
person.name
You create and modify data the same way, with an =
sign
person.name = "Anna"
person.age = 27
if a property exists, it’ll update the value. if it doesn’t, it’ll create the property AND update the value.
You can use array methods (like .join()
) on an object property
1for (var key in object) {
2 // do something
3}
key
is the property name, this will change every time it loops. this doesn’t have to called key
, you can call it jojo
, x
, k
, prop
or whatever. object
is the object name, the object you want to loop through.
You need bracket notation person[key]
to access property values in a for in
loop. person.
inside a for in loop will look for a property that is literally named key
in the object.
person[key]
CORRECTperson.key
WRONG - will look for one property literally called key
instead of looping through propertiesperson["key"]
WRONG - will get the key
property if it existsFYI, you can console.log()
multiple strings separated with a ,
1console.log(key, ' : ', person[name]);
or just use template strings
1console.log(`${key} : ${person[name]}`;
Constructor functions create objects. They are used with the new
keyword, which creates the objects, sets this
within the function to the object (i.e. this
refers to the new object), and return the object.
1// Object constructor function
2function Vehicle(year, make, model) {
3 this.year = year;
4 this.make = make;
5 this.model = model;
6 this.getFullDescription = function() {
7 return `${this.year} ${this.make} ${this.model}`
8 }
9}
10
11// create a new instance of the object using the `new` keyword
12let myCar = new Vehicle('2016', 'Honda', 'Civic')
Factory functions return objects but they don’t need to use the new
keyword and they don’t set this
inside the function to the object being created. They just create and return an object
1// Factory function (using ES6 enhanced object literal syntax)
2function createVehicle(year, make, model) {
3 return {
4 year,
5 make,
6 model,
7 getFullDescription() {
8 return `${year} ${make} ${model}`
9 }
10 }
11}
12
13// create a new instance of the object
14let myCar = createVehicle('2016', 'Honda', 'Civic')
JSON is just a string that is formatted as a JS Object. Servers are really good at sending and receiving strings (like HTML/CSS). Once a browser gets the string, it converts it to a pure JS object.
1// Object literal
2let car = {
3 make: 'Honda',
4 model: 'Civic',
5 year: 2016
6}
7
8// Bracket notation
9console.info(`I have a ${car['year']} ${car['make']} ${car['model']}`)
10
11// Dot notation
12console.info(`I have a ${car.year} ${car.make} ${car.model}`)
13
14// When property key is a variable (e.g. inside loops)
15// console.info(`I have a ${car[year]} ${car[make]} ${car[model]}`)
16
17
18// Object literal
19let employee = {
20 // properties
21 firstName: 'Harry',
22 lastName: 'Denver',
23 //method
24 fullName: function () {
25 return `${this.firstName} ${this.lastName}` // this refers to the object that owns the function
26 }
27}
28
29// reference a property
30console.info(`Our manager is ${employee.firstName}`)
31
32// call a method
33console.info(`His full name is ${employee.fullName()}`)
34
35// Object constructor function
36function Vehicle(year, make, model) { // notice the capital V? it's convention for constructor functions
37 this.make = make; // notice the semicolons and equal signs
38 this.model = model;
39 this.year = year;
40 this.getFullDescription = function () {
41 return `${this.year} ${this.make} ${this.model}`;
42 }
43}
44
45// create new instances with the new keyword
46let myCar = new Vehicle('2015', 'Honda', 'City')
47let mySistersCar = new Vehicle('2013', 'Toyota', 'Corolla Fielder')
48
49console.info(`${myCar.getFullDescription()}`)
50console.info(`${mySistersCar.year} ${mySistersCar.make} ${mySistersCar.model}`)
51
52// factory functions?
53function createVehicle(year, make, model) {
54 return {
55 make: make,
56 year: year,
57 model: model,
58 getFullDescription: function () {
59 return `${year} ${make} ${model}`
60 }
61 }
62}
63
64let myCar2 = createVehicle('2015', 'Honda', 'Civic') // no `new` keyword
65let mySistersCar2 = createVehicle('2013', 'Toyota', 'Corolla Fielder')
66
67console.info(`${myCar2.getFullDescription()}`)
68console.info(`${mySistersCar2.getFullDescription()}`)
69
70
71// ES6 Enhanced Object literal syntax
72function createVehicle(year, make, model) {
73 return {
74 make, // if the property name and value variable name are the same, you don't have to type both
75 year,
76 model,
77 getFullDescription() { // we can remove the function keyword
78 return `${year} ${make} ${model}`
79 }
80 }
81}