Objects By Chloe

An object is a data type in JS, made up of name:value pairs.
Objects can be linked to real life objects. E.g. A person would be an object:
var person ={
height: 161,
eyes: "brown",
hair: "blonde",
};

Each object can process data, send and receive messages.
Objects are a vital data type to be familiar when coding and are used across many of the coding languages.
There are two ways of constructing an object.The Object literal is the preferred way of defining an object as it reduces confusion and possible errors occuring within the code.

Object Literal:
This simply uses the {} to define the variable as an object.
E.g.
var book = {
Title: "Harry Potter and the Chamber of Secrets",
Author: "J K Rowling",
NumberOfBooks: 7.
Favourite Book: function() {
return `My favourite book is ${this.Title}`},
}
Object Constructor:
This uses the 'new' keyword to create the object
E.g.
var book = new Object(
Title: "Harry Potter",
Author: "J K Rowling",
NumberOfBooks: 7.
FavouriteBook: function() {
return `My favourite book is ${this.Title}`},
);
Objects can be split into three sections, using the above as an example:

1. The Object
'book' would be the object.

2. Property
Each property is made up of name:value pairs
'Title: "Harry Potter"' would be a property.
Title being the property name and Harry Potter being the property value.
Properties can contain any datatype. E.g. strings, boolean, numbers and often refers to to characteristics of the object.

3. Methods
A method is made up of the method name i.e. Favourite book, and the method value i.e `My favourite book is ${this.Title}`
A method is a task that the object can perform.

The 'this' keyword

When using 'this' in an object it refers to the current object it is defined in. For our example it is 'book'.

Accessing Object Properties

To access an objects property value you can use two methods:

1.DOT NOTATION
Using our ongoing example, if you wanted to acces the property value for the Number Of books, you would do the following:
book.NumberOfBooks and it would return 7.
This method is easier and faster to read.

2. BRACKETS NOTATION
book['NumberOfbooks'] => 7.
This method must be used if an objects property contains any kind of special characters.
.

Adding, Modifying and Deleting Object Properties

To ADD a new property to an object, you assign a new value to a property using the assignment operator i.e =
To do this you use either the dot notation or [] notation.
Using the ongoing example:
book.character = "Hermione Granger"
OR
book['character'] = "Hermione Granger"

To MODIFY an object you assign a new value to an existing property using the same method as above.
book.character = "Ron Weasley"
OR
book['character'] = "Ron Weasley"

To DELETE an object property use the delete keyword.
E.g. delete book.Author.
The author property would then be removed from the object.