var animal = {
name: “Buster”, // property
age: 6, // property
type: “Husky”, // property
colour: “blue”, // property
// method
speak: function() {
console.log(”Woof”);
}
}
Notice how everything is a property, except the function, which is a method (while still also being a property). This is because the function performs an action, just like when we used the search() method before, it performed an action.
Thinking back to how we used the properties and methods of our strings and numbers earlier on in this chapter. How do you think you might get access to the age of the animal we have created here?
That’s right, by making use of animal.age. By calling animal.age, we are saying to JavaScript ‘look into the animal variable/object and give me the age’. Now let’s think about if we wanted to call the speak method of the object? That’s right, just as before, we simply call animal.speak() and JavaScript will perform the function in question and would log ‘Woof!’ to the console. Remember, parentheses must be added to run a function; in this instance if we leave off the parentheses, JavaScript would just return the function definition, meaning it would just show us the code used to create the function.
Another method for accessing an object’s property is by using the following syntax: animal[’name’]; this is entirely identical to animal.name. It’s entirely your choice as to which method you use.
And that’s objects! Simple, powerful and effective. They can seem confusing at first, but in reality they are actually very simple. They are just buckets of data. If you are really struggling to conceptualize it, then simply just imagine them as a container for multiple variables. A way to store variables within variables.
Let’s put what we have learned into practice with the following exercise: