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";

Related Javascript Mentoring answers

All answers ▸

How to check if value exists in an object in JavaScript?


Find the sum of all multiples of 2 less than 10000


How to sum every number in an array of numbers.


How do you create objects in javascript?


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–2024

Terms & Conditions|Privacy Policy