Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why is Object useful for in JavaScript?

Good day all. I just want to know why objects are important in JavaScript or what are objects use for. I am currently on the loop,array, and object course. I appreicate your feedbacks and thank again. For example this code below why store it as an object?

 <p id ="myobject"> </p>
 var myInfo = {
     firstName: "Abraham",
     lastName: "Swaray",
     favoriteSite:"TreeHouse",

    document.getElementById('myobject').innerHTML =  myInfo.favoriteSite;

}

3 Answers

Some advantages I have in mind:

  1. You can organize in a better way your code, thus, It's more maintainable.
  2. You can modify easily your code, It's more modular.
  3. You 'll often have to deal with litterals objects as you showed in your example when dealing with databases or API. Often, responses from the server are given in JSON format. (which stands for Javascript Object Notation).
  4. You most of time (if not all the time) already play with objects when playing with Javascript, as pretty much everything is object.

From what I can tell the Object is another way to organize. At this point I have used arrays and it is working fairly well but when you start dealing with interacting with other languages and interfaces the Object is easier to work with than array.

I've used objects with PHP but not really with Javascript yet though. There is a nifty "this.objectName" that would let you make changes to the "objectName". Additionally instead of having things in an array you can create "keys" for each object. an example being:

 var myInfo = {
     firstName: "Gandolf",
     lastName: "The Grey",
     age:"290",
    }

That would be an array of firstname, lastname, age where in an object you create each person object with keys.

This is what it would look like as an array:

var array = [['Steve', 'Thompson',34],
                    ['Gandolf','The Grey',290],
                    ['Sweeny','Todd',18]]

So you can pull an object and refer to this.age and have be your output. It is WAY easier than array[2][3] to get Gandolf's age.

Alright, thanks all.