5:1 Objects
Objects in JavaScript let you store complex data, they're often used by other data sources you may want to use to create generative art, so they're essential to understand.
What are objects
Objects are a type of variable that can store more complex data. They allow you to say what kind of data you are storing and associate different kinds of data with each other.
Why would you want to do that! Well take the example of your breakfast. Let describe a typical british fry up:
let breakfast = {
eggs: 3,
bacon: 2,
toast: 1
}
If we want to get a value from the object we do this:
// print how many eggs in the console
console.log(breakfast.eggs);
// will print 3
Structure of objects
As you can see from the previous slide objects are structured differently from normal variables. Look at this object:
let pencilCase = {
pencils: 5,
pens: 3,
colour: "green",
}
We've made a pencil case object for our green pencil case that contains 5 pencils and 3 pens. Looking above the object uses curly brackets to contain pairs of things. Each of which has a key (also called a name) and a value. These are separted by a colon and each pair is separated by a comma.
We access values in objects using dot notation. That means we to get the value of one of the keys, for example to get the value of pens within pencilCase we do the following:
let numberOfPens = pencilCase.pens; //will equal 3 in this case
What else can we do with objects
Objects can store anything, numbers, strings (text), other objects, arrays, functions. In fact in JavaScript most things are objects.
Lets make our breakfast object more useful by storing some more values.
let breakfast = {
eggs: {
number: 3,
style: "poached"
},
bacon: {
number: 2,
style: "cripsy"
},
bread: {
number: 1,
style: "toast"
}
}
We have created an object containing other objects. This is useful as we can break things down into very reusable parts. To tell the chef how to cook the eggs he can do this:
console.log(breakfast.eggs.number, breakfast.eggs.style);
// prints: 3, poached