JavaScript: Objects

1// Storage
2var person = {
3  "firstName": "John" // String
4  "lastName": "Doe"   // String
5  "age": 35           // Int
6  "weight": 183.5     // Float
7  "isMarried": true   // Boolean
8}
9
10// Access
11console.log(person["firstName"]) // Prints: "John"
12console.log(person["age"])       // Prints: 35
13console.log(person["isMarried"]) // Prints: true

Any time we have multiple variables representing a single entity, like the following two code blocks:

1var firstName1 = "John" // String
2var lastName1 = "Doe"   // String
3var age1 = 35           // Int
4var weight1 = 183.5     // Float
5var isMarried1 = true   // Boolean
6
7var firstName2 = "Jane" // String
8var lastName2 = "Doe"   // String
9var age2 = 33           // Int
10var weight2 = 154.3     // Float
11var isMarried2 = false  // Boolean

It's clear that these 2 groups of variables belong together and also represent a single entity, but Objects are a better way to communicate this:

1var person1 = {
2  "firstName": "John" // String
3  "lastName": "Doe"   // String
4  "age": 35           // Int
5  "weight": 183.5     // Float
6  "isMarried": true   // Boolean
7}
8
9var person2 = {
10  "firstName": "Jane" // String
11  "lastName": "Doe"   // String
12  "age": 33           // Int
13  "weight": 154.3     // Float
14  "isMarried": false  // Boolean
15}

You can think of an Object as a "compound variable", where you can have many different types of variables inside of it