loading...

Intro to Objects Part 1

scdan0624 profile image SCDan0624 ・2 min read

Intro
Normally in Javascript Arrays are a great way to store ordered data. But what if we wanted to store data that doesn't need to be ordered such a person's personal information. This is where using storing the data as an object is very useful.

Object Syntax
To create an object we use the following syntax:

const myObject = {
key:value
}
Enter fullscreen mode Exit fullscreen mode

So lets take the personal information of a person named John and store it into an object:

const myProfile = {
  name:"John",
  age: 32,
  hair: "brown",
  weight: 175
}

Enter fullscreen mode Exit fullscreen mode

Quick Note About Keys
If you create an object with a key that it is number it will convert it to a string. Example:

const myObj = {
32:'Magic Johnson'
// the key 32 will be converted to '32'.
}
Enter fullscreen mode Exit fullscreen mode

Accessing Data in Objects
Rather than accessing data using an index like we do with arrays we use custom keys.

There are two different ways to access a property in an object.

objectName.propertyName
Enter fullscreen mode Exit fullscreen mode

or

objectName["propertyName"]
Enter fullscreen mode Exit fullscreen mode

Lets look back at our profile example and access John's age using both techniques:

const myProfile = {
  name:"John",
  age: 32,
  hair: "brown",
  weight: 175
}

myProfile.age // output 32
myProfile["age"] //  output 32
Enter fullscreen mode Exit fullscreen mode

Adding and Updating Properties

What if we wanted to add an eye color to John's profile? We simply do that using the following syntax:

const myProfile = {
  name:"John",
  age: 32,
  hair: "brown",
  weight: 175
}

myProfile.eye = "blue"

console.log(myProfile)

/* output
{
  name:"John",
  age: 32,
  hair: "brown",
  weight: 175,
  eye:"blue"

}
*/
Enter fullscreen mode Exit fullscreen mode

Oh no we made a mistake John actually has green eyes. Lets's update that:

const myProfile = {
  name:"John",
  age: 32,
  hair: "brown",
  weight: 175,
  eye:"blue",
}

myProfile.eye = "green"

// myProfile["eye" = "green" would also work


console.log(myProfile)

/* output
{
  name:"John",
  age: 32,
  hair: "brown",
  weight: 175,
  eye:"green"

}
*/
Enter fullscreen mode Exit fullscreen mode

As you can see with one line of code our profile now has John's eye color listed as green.

Conclusion

Now you know who to both create and manipulate javascript objects. In part 2 we will dive into more advanced syntax such as using methods in Javascript and how to use the this keyword.

Discussion

pic
Editor guide