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

1266 Views

See similar Javascript Mentoring tutors

Related Javascript Mentoring answers

All answers ▸

How are objects created in arrays


Suppose that you have a <p> element with an id of 'id1'. Use javascript to set the inner html of this element to 'hello!'


What does the document.onload() function do and why is it useful?


What is the importance of javascript in the web?


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