Objects JavaScript
Objects JavaScript
Buy EPUB/PDF
Objects
As we know from the chapter Data types, there are eight data types in JavaScript. Seven of them are called “primitive”,
because their values contain only a single thing (be it a string or a number or whatever).
In contrast, objects are used to store keyed collections of various data and more complex entities. In JavaScript, objects
penetrate almost every aspect of the language. So we must understand them first before going in-depth anywhere else.
An object can be created with figure brackets {…} with an optional list of properties. A property is a “key: value” pair,
where key is a string (also called a “property name”), and value can be anything.
We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key. It’s easy to find
a file by its name or add/remove a file.
key1
key2
key3
An empty object (“empty cabinet”) can be created using one of two syntaxes:
empty
user
Usually, the figure brackets {...} are used. That declaration is called an object literal.
A property has a key (also known as “name” or “identifier”) before the colon ":" and a value to the right of it.
1. The first property has the name "name" and the value "John" .
2. The second one has the name "age" and the value 30 .
The resulting user object can be imagined as a cabinet with two signed files labeled “name” and “age”.
name
age
user
1 user.isAdmin = true;
isAdmin
name
age
user
1 delete user.age;
isAdmin
name
user
We can also use multiword property names, but then they must be quoted:
1 let user = {
2 name: "John",
3 age: 30,
4 "likes birds": true // multiword property name must be quoted
5 };
likes birds
name
age
user
1 let user = {
2 name: "John",
3 age: 30,
4 }
That is called a “trailing” or “hanging” comma. Makes it easier to add/remove/move around properties, because all lines
become alike.
Square brackets
For multiword properties, the dot access doesn’t work:
1 // this would give a syntax error
2 user.likes birds = true
JavaScript doesn’t understand that. It thinks that we address user.likes , and then gives a syntax error when comes
across unexpected birds .
The dot requires the key to be a valid variable identifier. That implies: contains no spaces, doesn’t start with a digit and
doesn’t include special characters ( $ and _ are allowed).
There’s an alternative “square bracket notation” that works with any string:
1 let user = {};
2
3 // set
4 user["likes birds"] = true;
5
6 // get
7 alert(user["likes birds"]); // true
8
9 // delete
10 delete user["likes birds"];
Now everything is fine. Please note that the string inside the brackets is properly quoted (any type of quotes will do).
Square brackets also provide a way to obtain the property name as the result of any expression – as opposed to a literal
string – like from a variable as follows:
Here, the variable key may be calculated at run-time or depend on the user input. And then we use it to access the
property. That gives us a great deal of flexibility.
For instance:
1 let user = {
2 name: "John",
3 age: 30
4 };
5
6 let key = prompt("What do you want to know about the user?", "name");
7
8 // access by variable
9 alert( user[key] ); // John (if enter "name")
1 let user = {
2 name: "John",
3 age: 30
4 };
5
6 let key = "name";
7 alert( user.key ) // undefined
Computed properties
We can use square brackets in an object literal, when creating an object. That’s called computed properties.
For instance:
1 let fruit = prompt("Which fruit to buy?", "apple");
2
3 let bag = {
4 [fruit]: 5, // the name of the property is taken from the variable fruit
5 };
6
7 alert( bag.apple ); // 5 if fruit="apple"
The meaning of a computed property is simple: [fruit] means that the property name should be taken from fruit .
1 let fruit = prompt("Which fruit to buy?", "apple");
2 let bag = {};
3
4 // take property name from the fruit variable
5 bag[fruit] = 5;
Square brackets are much more powerful than dot notation. They allow any property names and variables. But they are
also more cumbersome to write.
So most of the time, when property names are known and simple, the dot is used. And if we need something more
complex, then we switch to square brackets.
For instance:
1 function makeUser(name, age) {
2 return {
3 name: name,
4 age: age,
5 // ...other properties
6 };
7 }
8
9 let user = makeUser("John", 30);
10 alert(user.name); // John
In the example above, properties have the same names as variables. The use-case of making a property from a variable
is so common, that there’s a special property value shorthand to make it shorter.
We can use both normal properties and shorthands in the same object:
1 let user = {
2 name, // same as name:name
3 age: 30
4 };
1 // these properties are all right
2 let obj = {
3 for: 1,
4 let: 2,
5 return: 3
6 };
7
8 alert( obj.for + obj.let + obj.return ); // 6
In short, there are no limitations on property names. They can be any strings or symbols (a special type for identifiers, to
be covered later).
For instance, a number 0 becomes a string "0" when used as a property key:
1 let obj = {
2 0: "test" // same as "0": "test"
3 };
4
5 // both alerts access the same property (the number 0 is converted to string "0")
6 alert( obj["0"] ); // test
7 alert( obj[0] ); // test (same property)
There’s a minor gotcha with a special property named __proto__ . We can’t set it to a non-object value:
1 let obj = {};
2 obj.__proto__ = 5; // assign a number
3 alert(obj.__proto__); // [object Object] - the value is an object, didn't work as
We’ll cover the special nature of __proto__ in subsequent chapters, and suggest the ways to fix such behavior.
Reading a non-existing property just returns undefined . So we can easily test whether the property exists:
1 let user = {};
2
3 alert( user.noSuchProperty === undefined ); // true means "no such property"
1 "key" in object
For instance:
1 let user = { name: "John", age: 30 };
2
3 alert( "age" in user ); // true, user.age exists
4 alert( "blabla" in user ); // false, user.blabla doesn't exist
Please note that on the left side of in there must be a property name. That’s usually a quoted string.
If we omit quotes, that means a variable should contain the actual name to be tested. For instance:
1 let user = { age: 30 };
2
3 let key = "age";
4 alert( key in user ); // true, property "age" exists
Why does the in operator exist? Isn’t it enough to compare against undefined ?
Well, most of the time the comparison with undefined works fine. But there’s a special case when it fails, but "in"
works correctly.
1 let obj = {
2 test: undefined
3 };
4
5 alert( obj.test ); // it's undefined, so - no such property?
6
7 alert( "test" in obj ); // true, the property does exist!
In the code above, the property obj.test technically exists. So the in operator works right.
Situations like this happen very rarely, because undefined should not be explicitly assigned. We mostly use null for
“unknown” or “empty” values. So the in operator is an exotic guest in the code.
The syntax:
1 let user = {
2 name: "John",
3 age: 30,
4 isAdmin: true
5 };
6
7 for (let key in user) {
8 // keys
9 alert( key ); // name, age, isAdmin
10 // values for the keys
11 alert( user[key] ); // John, 30, true
12 }
Note that all “for” constructs allow us to declare the looping variable inside the loop, like let key here.
Also, we could use another variable name here instead of key . For instance, "for (let prop in obj)" is also
widely used.
Are objects ordered? In other words, if we loop over an object, do we get all properties in the same order they were
added? Can we rely on this?
The short answer is: “ordered in a special fashion”: integer properties are sorted, others appear in creation order. The
details follow.
1 let codes = {
2 "49": "Germany",
3 "41": "Switzerland",
4 "44": "Great Britain",
5 // ..,
6 "1": "USA"
7 };
8
9 for (let code in codes) {
10 alert(code); // 1, 41, 44, 49
11 }
The object may be used to suggest a list of options to the user. If we’re making a site mainly for a German audience then
we probably want 49 to be the first.
The phone codes go in the ascending sorted order, because they are integers. So we see 1, 41, 44, 49 .
So, "49" is an integer property name, because when it’s transformed to an integer number and back, it’s still the
same. But "+49" and "1.2" are not:
1 // Number(...) explicitly converts to a number
2 // Math.trunc is a built-in function that removes the decimal part
3 alert( String(Math.trunc(Number("49"))) ); // "49", same, integer property
4 alert( String(Math.trunc(Number("+49"))) ); // "49", not same "+49" ⇒ not intege
5 alert( String(Math.trunc(Number("1.2"))) ); // "1", not same "1.2" ⇒ not integer
…On the other hand, if the keys are non-integer, then they are listed in the creation order, for instance:
1 let user = {
2 name: "John",
3 surname: "Smith"
4 };
5 user.age = 25; // add one more
6
7 // non-integer properties are listed in the creation order
8 for (let prop in user) {
9 alert( prop ); // name, surname, age
10 }
So, to fix the issue with the phone codes, we can “cheat” by making the codes non-integer. Adding a plus "+" sign
before each code is enough.
Like this:
1 let codes = {
2 "+49": "Germany",
3 "+41": "Switzerland",
4 "+44": "Great Britain",
5 // ..,
6 "+1": "USA"
7 };
8
9 for (let code in codes) {
10 alert( +code ); // 49, 41, 44, 1
11 }
Summary
Objects are associative arrays with several special features.
Additional operators:
What we’ve studied in this chapter is called a “plain object”, or just Object .
They have their special features that we’ll study later. Sometimes people say something like “Array type” or “Date type”,
but formally they are not types of their own, but belong to a single “object” data type. And they extend it in various ways.
Objects in JavaScript are very powerful. Here we’ve just scratched the surface of a topic that is really huge. We’ll be
closely working with objects and learning more about them in further parts of the tutorial.
Tasks
Hello, object
importance: 5
solution
importance: 5
Write the function isEmpty(obj) which returns true if the object has no properties, false otherwise.
solution
importance: 5
1 let salaries = {
2 John: 100,
3 Ann: 160,
4 Pete: 130
5 }
Write the code to sum all salaries and store in the variable sum . Should be 390 in the example above.
solution
importance: 3
Create a function multiplyNumeric(obj) that multiplies all numeric property values of obj by 2 .
For instance:
Please note that multiplyNumeric does not need to return anything. It should modify the object in-place.
solution
Comments
● If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of
commenting.
● If you can't understand something in the article – please elaborate.
● To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than
10 lines – use a sandbox (plnkr, jsbin, codepen…)
privacy policy
terms of usage
contact us