I've just heard about objects. How do I use them and do they work with Arrays?

JavaScript objects are collections of data with key-value pairs. A 'key' is a label for a bit of data. In the example below; name, age and hobbies are all keys. A 'value' is the bit of data you want to store. In this example, key 'name' has value is 'Angus'. var myObject = {   name: "Angus",   age: 43,   hobbies: ["dancing", "guitar", "skiing"] }; We could find the value for any key-value pair just by knowing the name of the key: console.log(myObject.name) Which would print: Angus Reading data from objects is that simple! You can even read from arrays by putting the position of the array that you want to print in square brackets at the end of the console.log statement. This is because arrays in objects behave exactly the same as arrays outside of objects. console.log(myObject.hobbies[0]) Which would print: dancing Setting data is just as straightforward and works with arrays too. Choose a key you want to set the value for and set it equal to a new value. myObject.age = 44; myObject.hobbies[1] = "saxophone";

SM
Answered by Stewart M. Javascript tutor

1292 Views

See similar Javascript Mentoring tutors

Related Javascript Mentoring answers

All answers ▸

Make button that says how many times it has been clicked.


How would you change the background colour of a div with the id "colourme" to purple?


How to sum every number in an array of numbers.


What does the following code do and why? console.log(1+"2")


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2025

Terms & Conditions|Privacy Policy
Cookie Preferences