Getting Started with JavaScript Object
Publikováno: 2.7.2018
An object is a type of data in JavaScript. It's the only value you can pass around as variables besides primitives. For this reason, objects are really important in JavaScript.
What are obj...
An object is a type of data in JavaScript. It's the only value you can pass around as variables besides primitives. For this reason, objects are really important in JavaScript.
What are objects
An object in JavaScript is a type of data that contains key-value pairs.
You can create objects by writing these key-value pairs within curly braces. If you intend to create multiple key-value pairs, you need to separate each pair with commas, like this:
const anObject = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
// ...
}
Each key gives you a reference to a value. If you imagine an English dictionary, the keys are the words while the values are the definition of each word.
const dictionary = {
dream: "a series of thoughts, images, and sensations occurring in a person's mind during sleep",
happy: "feeling or showing pleasure or contentment",
// ...
}
Since object stores key-value pairs, another analogy you can use is to compare objects in JavaScript with objects in real life.
For example, you can observe the device you're using to read this lesson. What device is this? What's its size? What's its operating system?
If you put these information together into a JavaScript object, it'd look like this:
const macbook = {
operatingSystem: 'macOS Sierra',
screenResolution: '2880x1800',
screenSize: '15.4 inch',
usbPorts: 2,
hdmiPort: 1,
storage: '512gb'
// ... Other specs
}
Object values
Objects can contain any value that's valid in JavaScript. This means you can store primitives (like Strings and Numbers) and other objects.
const anObject = {
string: 'Yay',
number: 1,
boolean: true,
nullPrimitive: null,
undefinedPrimitive: undefined,
anotherObject: {},
afunction: function () {} // more on functions later
anArray: [] // more on array in the next lesson
}
Getting the value of a property
Keys are also called properties. You can use two methods to get the value of a property
The first method is through the dot notation, where you write the name of the object, followed by .
, followed by the property name:
const prop = object.property
So, if you'd like to get the storage
of the macbook we declared above, you can write macbook.storage
const macbookStorage = macbook.storage
console.log(macbookStorage) // 512gb
The second method is through the bracket notation. Here, you write the name of the object, followed by a string of the property in square brackets ([]
).
const macbookStorage = macbook['storage']
console.log(macbookStorage) // 512gb
Both methods work.
Normally, you'll use the dot notation. You'll only use the bracket notation in special occasions where the dot notation doesn't work. These special occasions include:
- When your property name is an invalid identifier
- When you need get the value of a property through a variable
Invalid identifiers
When you declare variables in JavaScript, you need to adhere to four rules:
- The variable must be written as a single word
- The variable must consist only of letters, numbers or underscores (0-9, a-z, A-Z,
_
). - The variable cannot begin with a number.
- The variable cannot be any of these reserved keywords
If your variable follows these four rules, it's a valid identifier; if your variable doesn't follow any of these rules, it's an invalide identifier.
Objects can have invalid identifiers as properties. Here's one example:
const ObjWithInvalidIdentifer = {
'First Name': 'Zell'
}
When you have an invalid identifier, you can't use the dot notation. You need to use the bracket notation:
const firstName = ObjWithInvalidIdentifer.First Name // Syntax Error: Unexpected identifier
const firstName2 = ObjWithInvalidIdentifer['First Name'] // Zell
Of course, when you create objects, try to make properties with valid identifiers so you can use the dot notation. Don't make life hard for yourself!
Getting the value of a property through a variable.
When you write more advanced code, you may need to get the value of a property through a variable. In this case, you can only use the bracket notation.
For example, let's say you store the property to search in a variable called propertyToGet
.
const propertyToGet = 'storage'
There's no property called propertyToGet
in the object, so you can't use the dot notation. If you try doing it, you'll get undefined
.
const storageWithDotNotation = macbook.propertyToGet
console.log(storageWithDotNotation) // undefined
You can only use the bracket notation, like this:
const macbookStorage = macbook[propertyToGet]
console.log(macbookStorage) // 512gb
That's all you need to know about getting property values. Let's move on and learn to set property values.
Setting the value of a property
You can set the value of a property either with the dot notation or the bracket notation. Likewise, the dot notation is always preferred.
// Dot notation
macbook.storage = '256gb'
// Bracket notation
macbook['usbPorts'] = 2
console.log(macbook)
// {
// storage: '256gb',
// usbPorts: 2
// }
Deleting properties
You can delete key-value pairs from objects with the delete
keyword. To do so, you write delete
, followed by the property either in dot or bracket notation.
delete object.property
Here's an example where we delete the storage
property from the macbook Object.
delete macbook.storage
console.log(macbook)
// The storage property is already deleted, hence you don't see it anymore when you console.log it
// {
// usbPorts: 2
// }
Functions are Objects in JavaScript
Functions are a special kind of Object in JavaScript. It can have properties too (even though you'd most likely won't declare any).
// You can add properties to functions
function sayName () {}
sayName.property = 'Hallelujah'
console.log(sayName.property)
// Hallelujah
Since functions are objects, you can write functions as values in objects. The properties that contain functions as their values are called methods.
const anObject = {
aMethod: function() {
// Do something in function
}
}
In the following example, we say playMusic
is a method of macbook
.
const macbook = {
playMusic: function () {
/* some code to play music */
}
}
Since methods are functions, they behave exactly like functions.
To call a method, you write parenthesis ()
after getting the method through the dot or bracket notation
// Calling a method with the dot notation
macbook.playMusic()
// Calling a method with the bracket notation
macbook['playMusic']()
You can also add arguments to methods, just like normal functions:
const greeter = {
sayHello: function (name) {
console.log('Hello ' + name + '!')
}
}
greeter.sayHello('Zell')
// Hello Zell!
You may hear phrases like "higher order functions" and "functions are first class objects" when you browse outside tutorials. Ignore these phrases. They both mean functions are objects, which means you can pass functions around as a variable. People like to introduce important-sounding jargons to make functions sound more amazing (and confusing) than they really are.
Exercises to help you get better with objects
You'll use a lot of objects in JavaScript. Make sure you know them inside-out. Here are some exercises to use can for practice:
- Make an empty object
- Make a property for your object with the dot notation. Give it a value
- Make a property for your object with the bracket notation. Give it a value
- Get the value of a property with the dot notation
- Get the value of a property with the square bracket notation
- Set the value of a property with the dot notation
- Set the value of a property with the square bracket notation
- Make a method. Call this method
- Make a method that takes in an argument. Call this method