09 - Objects
JavaScript Objects
Introduction to Objects
JavaScript uses a data structure called Object that helps to organize data together. There are a couple of ways of creating an object in JavaScript, one way of doing it would be by using the curly brackets.
var colors = {};
These curly brackets are called Object Initializer. They create an empty object. We hold a reference to the object by using the variable colors.
Now, we can add properties to this colors object by providing the desired property names after a dot. This is called dot notation. We will also assign values to these newly created properties.
var colors = {};colors.black = 0;colors.darkGray = 55;colors.gray = 125;colors.lightGray = 175;colors.white = 255;console.log(colors);
If we are to look at the object at this point by using console.log, we would see it looks something like this.
{"black":0,"darkGray":55,"gray":125,"lightGray":175,"white":255}
We could also have created an object with the same properties from get go, by providing these properties inside curly brackets.
var colors = {black: 0,darkGray: 55,gray: 125,lightGray: 175,white: 255,};console.log(colors);
Objects are basically key-value pairs. Each key stores a value and each key-value pair make up a property on an object.
To be able to access a value on an object, we can again use the dot notation.
console.log(colors.gray);
For some situations, the dot notation doesn’t work. An example is when we use numbers as our key values in an object. In that case, we can use square brackets to access values instead. Like:
colors[1]; // Assuming you were using numbers instead of color names as key values.
What do you think this above expression will return if we were to console.log it? We would get the value undefined as the key 1 doesn’t exist in our current colors object.
We can also define functions as values for keys in an object. In that case, the resulting property would be referred to as a method.
Continuing from our colors object, let’s define a method inside that object called paintItBlack which would make the background color to be black.
var colors = {
black: 0,
darkGray: 55,
gray: 125,
lightGray:
...