Objects are sometimes referred to as dictionaries.
Objects can contain properties. These can be variables, arrays, other objects and functions or any mix of these. The syntax of a simple object (with just variables) is:
const objectName = {
key1 : 18,
key2 : "string",
key3 : true
}
With an array:
const objectName = {
key1 : [18, 'this is a string', true, 'beak', 8937],
key2 : "string",
boolean : true
}
Built in objects
There are many objects built into JavaScript and more created by the browser. These include things such as the console
object and the document
object. These work the same as objects we create. To access one part the above object we use dot notation:
objectName.key2
If the object property is a function defintion then when it’s called it’s followed by brackets:
objectName.myFunction()
The document object has everything that resides on the page. If you type document.images
into the console you get a list of all the images on the page. You can get other elements using methods of the document object. A method is simply a function that resides in an object.
Methods are functions stored as object properties. w3schools
document.getElementByName('h2');
document.getElementByClassName('folk');
document.getElementById('folk');
document.querySelector('h2');
document.querySelector('#folk');
document.querySelectorAll('.folk');
Adding
You can add new keys to an object in two ways: with period and with square brackets. The first way only allows single word key names (ie. no spaces).
objectName.sugar = true;
The other method allows strings for the key:
objectName["type of sweetner"] = "sugar";
Accessing part of an object
is very similar:
console.log(objectName.sugar);
or
console.log(objectName["type of sweetner"]);