Objects

Codecademy Team
Use this article as a reference sheet for JavaScript objects.

Use this article as a reference sheet for JavaScript Objects.

  • Objects are like arrays, but values are accessed by named properties, not just numbers. An object’s property can also be set to a function. Because they are associated with an object, these functions are called methods.

Let’s consider the role of an object before you learn how to create and use one. Objects, like arrays, numbers, strings, and booleans are used to model the world around us. The difference is that objects can model both the data and the functions that manipulate the data.

Objects are especially useful for storing information (and functions that use that information) in the same place.

You can think of objects as a collection of property-value pairs. Values, however, don’t have to be numbers like 0, 1, or 2, they can be any other data type and even variables.

var scoreboard = {
teamA: 'Code',
teamB: 'Cademy',
scoreA: 0,
scoreB: 0,
incrementScoreA: function () {
scoreboard.scoreA++;
},
incrementScoreB: function(){
scoreboard.scoreB++;
}
}

In the example above, the variable scoreboard stores an object with six property-value pairs. The keys teamA and teamB store string values. The keys scoreA and scoreB store number values, and the last two keys, incrementScoreA and incrementScoreB store functions. The value of a property can be accessed, logged, used, and/or overwritten. New property-value pairs can be created as well.

scoreboard.teamA = 'Blue Team';
scoreboard.teamC = 'Yellow Team';

On line 1 of this example, the teamA property is overwritten to the string 'Blue Team'. On line 2 a new property is created with the value ‘Yellow Team’.

scoreboard['teamB'] = 'Red Team';

In this example, the teamB property is overwritten to 'Red Team' using bracket notation. Bracket notation is often used when the key (another word for property) value is saved in a variable.

var whatScore = 'scoreA';
console.log(scoreboard[whatScore]);

In this example, the property saved to scoreA is logged to the console. The key scoreA is saved to the variable whatScore as a string. This is the benefit of bracket notation. You can use variables that store strings to access the values of an object.

scoreboard.incrementScoreA();

In this example, the incrementScoreA function is called. This function increases the scoreA value in scoreboard by one.