Objects
Intro
- This tutorial covers JavaScript Objects.
- It is recommended that you follow along with each section below. Paste or type the code into your own JavaScript file and view the variable or expression values either with console.logs or using the VS Code Debug sidebar.
- The example code for the entire tutorial series is at github.com/LearnByCheating/javascript-tutorial. There is a separate file or folder for each tutorial, including the To-Do List example project. The Readme file has instructions on how to run the code.
1. Create an object literal
- JavaScript is an object oriented programming language.
- An object is an unordered collection of properties written as name:value pairs.
- Object is one of JavaScript's eight data types and the only one that is not a primitive type.
- The preferred way to create an object outside of a class is by declaring an object literal.
Format:
const objName = { prop1: value, prop2: value, };
- Object literals are surrounded by curly braces.
- Assign it to a const variable unless you plan on assigning the variable to another object or value.
- Properties are listed as name value pairs separated by commas. They are like variables.
- Properties can be of any data type including other objects.
- Trailing commas on the last item are optional but recommended by style guides.
Example:
const author = {
name: 'Joey R',
age: 34,
active: true,
books: ['Learn JavaScript', 'Learn Node.js', 'Learn Express'],
};
- Above is an example of an object literal named author. It has four properties:
- name, which is a string type.
- age which is a number.
- active which is a boolean.
- And books written which is an array of book titles.
- The typeof operator returns the data type of a value:
typeof author; // returns 'object'
2. Create an object with the Object constructor function.
- While you may never need to do this, you can convert a primitive value to an object with the Object constructor function.
- A constructor is a special function that creates and initializes an object instance of a class. In this case of the Object class.
- You call constructor functions with the new operator to instantiate a new object. Just pass in the data as an argument.
const numObj = new Object(7); // converts 7 to a Number object with value 7.
- Calling the Object function without the new keyword will do the same:
const strObj = Object('Hello'); // converts the primitive value to a String object with value "Hello"
- You can can also pass in an object literal to the Object constructor function:
const book = new Object({
title: 'Learn JavaScript',
author: author,
price: 39.99,
});
- Or call it without the new operator and it will work just the same.
const book2 = Object({
title: 'Learn Node.js',
author,
price: 24.95,
});
Property value shorthand:
- If the property and value name are the same you can use property value shorthand and just list the property name.
- In the book2 object declaration above, the author property name is the same as the author variable name. So instead of adding the author property the usual way
author: author,
we used the property value shorthandauthor
.
3. Object properties
- You can get property values by chaining the property name to the object name.
- For example, get the book title property with:
book.title; // returns "Learn JavaScript"
- You can also use bracket notation where the property name is a string. Get the book2 title property with:
book2['title']; // returns "Learn Node.js"
- Use bracket notation if you need to pass in a variable as the property name.
let prop = 'price';
book[prop]; // returns 39.99
- You can set property values using the assignment operator. Change the book price:
book.price = 44.95;
- You can also add a property to the object. If the property doesn't exist on the object it will be added. Below we are adding a category property to the book object.
book.category = 'Software';
- To delete a property use the delete keyword. Below we delete the category property.
delete book.category;
- The book author property value is also an object. To get the book author name just chain author.name. to book.
book.author.name; // returns 'Joey R'
- Optional chaining: If the author property is empty, trying to get author.name will throw an error. ES2020 added optional chaining that won't throw an error if there is no author value. Put a question mark after book.author, but before the .name property. If the property doesn't exist it will return undefined.
book.author?.name; // returns 'Joey R' book.author?.gender; // returns undefined
4&5. Object methods and "This"
- Methods are object properties that are functions.
const author2 = {
name: 'Sheena',
age: 27,
addYear: function() { this.age += 1; },
log: function() { return `${this.name} is ${this.age} years old.` },
}
- The above author2 example has properties for name and age, and two methods.
- The addYear method adds 1 year to the age property.
- The keyword this represents the current object. For a method to access a property in the object you need to chain it to this.
- We get the age property and use the += addition assignment operator to increase age by 1.
- The log method returns information about the object.
Method shorthand syntax:
const author2 = {
name: 'Sheena',
age: 27,
addYear() { this.age += 1; },
log() { return `${this.name} is ${this.age} years old.` },
}
- For methods, you can use a shorthand syntax that drops the colon and function keyword.
- Longhand:
addYear: function() { this.age += 1; },
- Shorthand:
addYear() { this.age += 1; },
- Call the method by chaining it to the object, and append parentheses.
author2.addYear();
author2.age; // returns 28
view = author2.log(); // returns "Sheena is 28 years old."
6. The Spread Operator
- When you assign a variable to an object you are assigning its reference, meaning it's location in heap memory, not the actual object itself.
const bookCopy = book;
let isEqual = (book === bookCopy); // returns true
- The above example assigns the variable bookCopy to the variable book.
- The next statement checks if the two objects are equal. They are because the variables are both assigned to the same heap memory address pointing to the book object.
- If you change a property in one, the change would affect both variables.
- The spread operator lets you make a shallow copy of an object. That means you copy the property name: value pairs to a new object. Unlike the bookCopy variable, this is a new location in memory.
- The spread operator syntax is three dots, followed by the original object name, placed inside object literal curly braces:
{ ...objName }
const shallowCopy = { ...book };
isEqual = (book === shallowCopy); // returns false
- Above we shallow copy the book object properties into a new object and assign it the variable name shallowCopy.
- The two objects are not equal. The property names and values may be identical, but the variables hold different reference values to different memory locations.
book.price; // returns 39.99 bookCopy.price; // returns 39.99 shallowCopy.price; // returns 39.99 bookCopy.price = 42.95; bookCopy.price; // returns 42.95 book.price; // returns 42.95 shallowCopy.price; // returns 39.99
- Above we have three book variables. The book and bookCopy variables are assigned to the same object. ShallowCopy is assigned to a different object. Initially they all have the same price value.
- Then we set a new price value on bookCopy.
- This affects both the bookCopy and the book variables since they both point to the same object in memory.
- But there is no change to shallowCopy since it is not the same object in memory.
- You can use the spread operator to shallow copy an object, then change one or more of its properties in one statement.
const book3 = { ...book, title: 'Learn Express'};
- The above statement creates a new object named book3 that shallow copies the book object's properties, and changes the title property value to "Learn Express".
7. Object built-in global object
- Object is a JavaScript standard built-in object in the global scope.
Object === window.Object; // returns true from the browser Object === global.Object; // returns true from Node.js
- The global object is window in the browser and global in Node.js. Above we confirm that Object is attached to window by seeing if Object and window.object are equal to each other. And they are.
- Object.prototype is the parent prototype of all other built-in global object prototypes. Below is a partial list:
Object.getPrototypeOf(String.prototype) === Object.prototype; // true
Object.getPrototypeOf(Number.prototype) === Object.prototype; // true
Object.getPrototypeOf(Boolean.prototype) === Object.prototype; // true
Object.getPrototypeOf(Date.prototype) === Object.prototype; // true
Object.getPrototypeOf(Array.prototype) === Object.prototype; // true
Object.getPrototypeOf(Function.prototype) === Object.prototype; // true
- All objects ultimately inherit from Object and have access to its properties/methods.
Object.getPrototypeOf({}) === Object.prototype; // returns true
Object static properties and methods
- Object has several static properties and methods.
Object.getOwnPropertyNames(Object); // returns length, name, prototype, assign, getOwnPropertyDescriptor, getOwnPropertyDescriptors, getOwnPropertyNames, getOwnPropertySymbols, is, preventExtensions, seal, create, defineProperties, defineProperty, freeze, getPrototypeOf, setPrototypeOf, isExtensible, isFrozen, isSealed, keys, entries, fromEntries, values, hasOwn
Static properties and methods are called on the Object function itself, not on an object instance.
We are using some of these properties throughout this tutorial series to get the static and instance properties of the standard built-in objects like String, Boolean, Number, etc.
We even just used it above for Object:
Object.getOwnPropertyNames(Object)
You can also use this method on objects created in your code.
const book4 = { title: 'Learn Unix', author: 'Joey R' };Above is an object named book4 with two properties: title and author.
let view = Object.getOwnPropertyNames(book4); // returns ['title', 'author']
view = Object.keys(book4); // returns ['title', 'author']
Object.getOwnPropertyNames(book4)
returns the property names as strings in an array.Object.keys(book4)
also returns the property names in an array.
view = Object.values(book4); // returns ['Learn Unix', 'Joey R']
Object.values(book4)
returns the property values in an array.
view = Object.entries(book4); // returns [ ['title', 'author'], ['Learn Unix', 'Joey R'] ]
Object.entries(book4)
returns an array that contains a key and value array for each property.
8. Prevent changes: freeze and seal
- There are Object static methods that prevent modifications to objects.
Freeze:
- The Object.freeze method freezes an object. This prevents properties from being added or removed, and prevents values from being changed.
- The isFrozen method returns true or false.
book4; // returns { title: 'Learn Unix', author: 'Joey R' };
book4.available = true;
Object.freeze(book4);
view = Object.isFrozen(book4); // returns true
book4.price = 29.99;
book4.available = false;
book4; // returns { title: 'Learn Unix', author: 'Joey R', available: true };
- The above statements add a new property to the book4 object called available and set it to true.
Object.freeze(book4)
freezes the properties so properties cannot be added, modified, or deleted.Object.isFrozen(book4)
confirms that it is frozen.- Then we try to add a new property called price, and modify the available property value.
- Then we check the object, confirming that none of the changes took place.
Seal:
- The Object.seal method seals an object. That prevents properties from being added or removed but still allows the values to change.
const book5 = { title: 'Learn SQL', available: true, author: 'Joey R' };
Object.seal(book5);
view = Object.isSealed(book5); // returns true
book5.price = 29.99;
book5.available = false; book5; // returns { title: 'Learn SQL', available: false, author: 'Joey R' }
- Above we create an object called book5 with three properties: title, available, and author.
Object.seal(book5)
Then sealed it.Object.isSealed(book5)
confirms that book5 is sealed.- Then we try to add a price property, and change the value of the available property to false.
- Looking at the book5 object we see that the price property was not added, but the value of the available property did change to false.
Object instance properties and methods
- Object.prototype contains several properties and methods you can call on any object. Below is the full list of non-deprecated properties.
Object.getOwnPropertyNames(Object.prototype); // Returns: constructor, hasOwnProperty, isPrototypeOf, propertyIsEnumerable, toString, valueOf, toLocaleString
- We will just cover one of these since you aren't likely to use these often, if ever. The constructor property is a reference to the Object() constructor function.
Object.prototype.hasOwnProperty('propName')
Returns true if the object instance contains the property name passed in as the argument.
const book5 = { title: 'Learn Database', price: 49.99 };
view = book5.hasOwnProperty('title'); // returns true
- That concludes this tutorial on JavaScript objects. To see how you can use classes to create objects, review the JavaScript classes tutorial.
Conclusion
The topics in this tutorial correspond with the JavaScript CheatSheet Objects category. Make sure you understand each topic so you can refer back to the CheatSheet when working on your own projects.If you have the CheatSheet desktop app and downloaded the JavaScript CheatSheet, then go through the flashcards for this category to the point where you can answer them all in order and shuffled.