Exercise

Before I wrap up this section on arrays, let’s take a quick break to test out our knowledge and push our brains a little bit. Let’s see if you can put together the principles from what we have learned of JavaScript so far, in order to complete this exercise.

  • Open up chrome inspector tools and head over to the console.
  • Create an object containing information about an animal.
  • Create a new array and pass this object into the array at a position of your choosing.
  • Now attempt to log to the console one of the values from your object, but by accessing it through your array.

The final step of this exercise asks you to perform something that we haven’t discussed yet. However, using the principles that we have learned about JavaScript so far, some assumptions can be made as to how we might achieve the end result. Did you manage to work it out? If so, great work – you’re clearly starting to understand how JavaScript operates and how we access and manipulate variables. If you didn’t get it, it’s no problem at all. This was something entirely new to you, so it’s not a concern as long as you understand the solution you are about to see and how and why it works.

var animal = {

name: “Rolley”,

colour: “brown”,

age: 12

}

var arrayOfThings = [

“Paul”, animal, 22

];

console.log(arrayOfThings[1].name); // Logs “Rolley”

If you’re wondering what’s going on in the last statement of this solution, then allow me to break it down for you. The first part of the parameter that we pass to the console.log function, is arrayOfThings[1]. This locates and retrieves the second position in our array, which is assigned to our object. Now that we have our object, we can use the ‘.name’ syntax to pick a value off of our object. In this case we request the value of the ‘name’ variable. Which then returns the value ‘Rolley’, which then gets printed to the screen.

In JavaScript we can continue this process of using the.name notation to chain on further actions. Let’s see another example where we might want to perform an action on that value. Let’s say we want to find out the length of the name. We can simply add on.length to the end of our statement, which will then look into the value and return its character count, just like so: