You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Objects are data structures that allow us to store related data and functionality together
Objects are made up of key/value pairs
The key in an object is always a string
The value can be any valid JavaScript value (primitive, array, object, or function)
In arrays, you use the index to access a value:
constarr=[1,2,3];console.log(arr[1]);// 2
With objects, you use the key to access the value:
constmyObj={firstName: 'Lorem',lastName: 'Ipsum'};// we have two options for accessing values// dot syntaxconsole.log(myObj.firstName);// Lorem// square bracket syntaxconsole.log(myObj['lastName']);// Ipsum
If you know the name of the property, use dot notation
If the name of the property is dynamic (eg. stored in a variable), use square bracket syntax
Passing Values to Functions
Primitive types are passed to functions by value. This means that a copy is made and used by the function. The original value is unchanged.
Objects are passed to functions by reference. This means that the internal values of the object can be changed by the function, but the object itself cannot be reassigned.
constmyObj={firstName: 'Lorem',lastName: 'Ipsum'};constchangeKey=function(obj){obj.firstName='Jane';// this does change the value of the firstName key}changeKey(myObj);console.log(myObj.firstName);// JaneconstreplaceObj=function(obj){obj={};// this won't work}replaceObj(myObj);console.log(myObj);// { firstName: 'Jane', lastName: 'Ipsum' }
Functions Inside Objects
Since objects are key/value pairs, and functions are values, we can store functions inside of an object
We can make reference to the other properties in an object by using this to refer to the object itself
constmyObj={firstName: 'Lorem',lastName: 'Ipsum',sayFullName: function(){console.log(`My full name is ${this.firstName}${this.lastName}`);}};myObj.sayFullName();// My full name is Lorem Ipsum
A function inside an object is often referred to as a method
Object iteration with for..in
JavaScript gives us an easy way to iterate through an object's keys: the for..in loop
NOTE: We cannot use for..of to iterate through an object; it will result in an error
constobj={a: 1,b: 2,c: 3};for(constkeyinobj){// we can use the key to access the valueconstvalue=obj[key];}