DEV Community

Randy Rivera
Randy Rivera

Posted on

JavaScript Objects

Build JavaScript Objects

You may have seen the term object before.
Objects are similar to arrays, except that instead of using indexes to access and modify their data, you access the data in objects through what are called properties.

  • Example:
var myDog = {
  name: "Anakin",
  legs: 4,
  tails: 1,
  friends: ["Obi-woof", "Ahso-bark"]
};
Enter fullscreen mode Exit fullscreen mode

In this example, we made an object that represents a dog called myDog which contains the properties name (a string), legs, tails and friends.
You can set these object properties to whatever values you want, for this challenge as long as name is a string, legs and tails are numbers, and friends is an array.

Accessing Object Properties with Dot Notation

There are two ways to access the properties of an object: dot notation (.) and bracket notation ([]), similar to an array.

  • Here is an example of using dot notation (.) to read an object's property:
var testObj = {
  console: "PS5",
  game: "God Of War",
  friends: ["Alan", "Diego"]
};

var consoleValue = testObj.console;
var gameValue = testObj.games; 
console.log(consoleValue); // will display PS5
console.log(gameValue); // will display God Of War
Enter fullscreen mode Exit fullscreen mode

Here we set the variable consoleValue equal to the object's property console and set the variable gameValue equal to the object's property game using dot notation.

Accessing Object Properties with Bracket Notation

The second way to access the properties of an object is bracket notation ([]). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.

However, you can still use bracket notation on object properties without spaces.

Here is an example of using bracket notation to read an object's property:

var testObj = {
  "my entree": "hamburger",
  "my side": "fries",
  "my drink": "water"
};
Enter fullscreen mode Exit fullscreen mode
var entreeValue = testObj["my entree"];
var drinkValue = testObj["my drink"]; 

console.log(entreeValue); // will display hamburger
console.log(drinkValue); // will display water
Enter fullscreen mode Exit fullscreen mode

testObj["my entree"] would be the string hamburger, testObj["my drink"] would be the string water. We assigned them to entreeValue and drinkValue.

  • Also Note that property names with spaces in them must be in quotes (single or double).

Accessing Object Properties with Variables

Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.

  • Example:
var testObj = {
  12: "Namath",
  16: "Montana",
  19: "Unitas"
};
Enter fullscreen mode Exit fullscreen mode
var playerNumber = 16;     
var player = (testObj[playerNumber]);   

console.log(player); will display Montana
Enter fullscreen mode Exit fullscreen mode

Here we set the playerNumber variable to 16. Then, use the variable to look up the player's name and assign it to player.

Updating Object Properties

After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.

  • Example:
var myDog = {
  name: "Anakin",
  legs: 4,
  tails: 1,
  friends: ["Obi-woof", "Ahso-bark"]
};

myDog.name = "Anakin Skywalker";
console.log(myDog.name); // will display Anakin Skywalker
Enter fullscreen mode Exit fullscreen mode

Here we can change his name to the string Anakin Skywalker. Here's how we update his object's name property:

myDog.name = "Anakin Skywalker";
Enter fullscreen mode Exit fullscreen mode

or

myDog["name"] = "Anakin Skywalker";
Enter fullscreen mode Exit fullscreen mode

Now when we evaluate myDog.name, instead of getting Anakin, we'll get his new name, Anakin Skywalker.

Add New Properties to a JavaScript Object

You can add new properties to existing JavaScript objects the same way you would modify them.

  • Here's how we would add a bark property to myDog:
var myDog = {
  name: "Anakin",
  legs: 4,
  tails: 1,
  friends: ["Obi-woof", "Ahso-bark"]
};

myDog.bark = "woof";
console.log(myDog.bark); will display woof
Enter fullscreen mode Exit fullscreen mode

Delete Properties from a JavaScript Object

  • We can also delete properties from objects like this:
delete myDog.tails;
Enter fullscreen mode Exit fullscreen mode
var myDog = {
  name: "Anakin",
  legs: 4,
  tails: 1,
  friends: ["Obi-woof", "Ahso-bark"]
};

delete myDog.tails;
Enter fullscreen mode Exit fullscreen mode

After the code runs it will look like this.

{
  name: "Anakin",
  legs: 4,
  friends: ["Obi-woof", "Ahso-bark"]
}
Enter fullscreen mode Exit fullscreen mode

Using Objects for Lookups

Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to lookup values rather than a switch statement or an if/else chain.

  • Here we'll convert the switch statement into an object called lookup. then we use it to look up val and assign the associated string to the result variable.
function phoneticLookup(val) {
  var result = "";

  // Only change code below this line
  switch(val) {
    case "alpha":
      result = "Adams";
      break;
    case "bravo":
      result = "Boston";
      break;
    case "charlie":
      result = "Chicago";
      break;
    case "delta":
      result = "Denver";
      break;
    case "echo":
      result = "Easy";
      break;
    case "foxtrot":
      result = "Frank";
  }

  // Only change code above this line
  return result;
}

phoneticLookup("charlie");
Enter fullscreen mode Exit fullscreen mode
  • Then after converting it into an Object called lookup.
function phoneticLookup(val) {
  var result = "";

  // Only change code below this line
  var lookup = {
    "alpha": "Adams",
    "bravo": "Boston",
    "charlie": "Chicago",
    "delta": "Denver",
    "echo": "Easy",
    "foxtrot": "Frank"
  };

  // Only change code above this line
  result = lookup[val];
  return result;
}

console.log(phoneticLookup("charlie")); // will display Chicago
Enter fullscreen mode Exit fullscreen mode

Testing Objects for PropertiesPassed

Sometimes it is useful to check if the property of a given object exists or not. We can use the

.hasOwnProperty(propname)
Enter fullscreen mode Exit fullscreen mode

method of objects to determine if that object has the given property name. .hasOwnProperty() returns true or false if the property is found or not.

  • Let's Modify the function checkObj to test if an object passed to the function (obj) contains a specific property (checkProp). If the property is found, let's return that property's value. If not, return "Not Found".
function checkObj(obj, checkProp) {

  if (obj.hasOwnProperty(checkProp)) {
    return obj[checkProp];
  } else {
    return "Not Found";
  }
}
Enter fullscreen mode Exit fullscreen mode
checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet") should return the string kitten.
checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house") should return the string Not Found.
Enter fullscreen mode Exit fullscreen mode

Accessing Nested Objects

The sub-properties of objects can be accessed by chaining together the dot or bracket notation.

  • Here is a nested object:
var myStorage = {
  "car": {
    "inside": {
      "glove box": "maps",
      "passenger seat": "crumbs"
     },
    "outside": {
      "trunk": "jack"
    }
  }
};

var gloveBoxContents = myStorage.car.inside["glove box"];
console.log(gloveBoxContents); // will display maps
Enter fullscreen mode Exit fullscreen mode

Here we accessed the myStorage object and assign the contents of the glove box property to the gloveBoxContents variable using dot notation for all properties where possible, otherwise use bracket notation.

Top comments (0)