JavaScript Objects
# JavaScript Objects
In the real world, an object is a tangible thing—like a car. A car has properties (like weight and color) and methods (like start and stop).
In JavaScript, objects work exactly the same way. They are the most important data type in the language. If you understand objects, you understand JavaScript.
1. Introduction
While arrays are great for lists, Objects are used to store structured data that represents a single entity. Instead of accessing data via numerical indexes ([0], [1]), objects store data in Key-Value pairs. You ask the object for a specific "key", and it gives you the "value".
2. Learning Objectives
By the end of this chapter, you will be able to:
-
Create objects using the Object Literal syntax
{}.
- Access and modify object properties using dot notation and bracket notation.
- Add methods (functions) to objects.
-
Understand the
thiskeyword inside an object.
- Iterate over an object's properties.
- Build a working Product Catalog mini-project.
3. Creating an Object
The easiest way to create an object is using curly braces {}. Inside, you define properties as key: value pairs, separated by commas.
*Note: Just like arrays, objects are usually declared with const.*
4. Accessing Object Properties
There are two ways to access data inside an object:
-
1.
Dot Notation:
objectName.propertyName(Most common)
-
2.
Bracket Notation:
objectName["propertyName"](Used when the key name has spaces, or when using variables as keys)
5. Object Methods
Objects can also contain functions. When a function is attached to an object, it is called a Method.
---
6. Real-world Examples & Code Snippets
Example 1: Creating a User Profile
Example 2: Modifying an Object
You can easily change the value of an existing property, or add a brand new one dynamically.
Example 3: Deleting a Property
You can completely remove a property from an object using the delete keyword.
Example 4: The this Keyword
Inside an object method, this refers to the object itself. It allows the method to access sibling properties within the same object.
Example 5: Arrays of Objects
This is the most common data structure in all of web development (especially when fetching data from an API or Database).
Example 6: Iterating over an Object (for...in loop)
You cannot use a standard for loop with i++ on an object because objects don't have numbered indexes or a .length property. Instead, you use for...in.
Output Explanation: It loops through every key. Notice we *must* use bracket notation stats[key] inside the loop, because stats.key would literally look for a property named "key", which doesn't exist.
Example 7: Nested Objects
An object can contain other objects.
Example 8: Optional Chaining (?.)
If you try to access a property deep inside an object that doesn't exist, your app will crash. Optional chaining safely checks if the property exists before proceeding.
Example 9: Object.keys() and Object.values()
These built-in JavaScript methods extract just the keys or just the values into an Array.
Example 10: Using Variables as Keys
If you want to use a variable as a key name, you *must* use bracket notation.
---
7. Common Mistakes for Beginners
-
1.
Using
=instead of:inside an object:const obj = { name = "John" }is a syntax error.
-
2.
Forgetting commas between properties:
const obj = { name: "John" age: 25 }is a syntax error.
-
3.
Using
thisinside an Arrow Function: We will cover arrow functions later, but note thatthisbreaks if used inside an arrow function attached to an object. Always use the standardfunction()syntax for object methods.
8. Best Practices
-
Always declare objects with
const.
- Keep object properties logically related. Don't put user data and database configuration strings into the same object.
-
Use Dot Notation
obj.namefor readability, and only use Bracket Notationobj["name"]when absolutely necessary (like dynamic keys).
9. Mini Project: Product Catalog
Let's use an Array of Objects to dynamically render a shopping catalog to the screen.
HTML:
store.js:
*(Note: We used backticks ` ` to create multi-line strings. We will officially cover this in Chapter 12: Strings).*
10. Exercises
-
1.
Create an object called book
with properties:title,author, andpages.
-
2.
Add a new property to the book
object calledisReadand set it totrue.
-
3.
Add a method to the book
object calledgetSummarythat returns the string: "(Title) was written by (Author)".
11. MCQs (Multiple Choice Questions)
Q1: How do you access the age property of a person object?
A) person[age]
B) person.age
C) person->age
D) Both A and B are correct if A has quotes person["age"]
*Answer: D*
Q2: What is a function called when it is attached to an object? A) A Procedure B) A Property C) A Method D) A Class *Answer: C*
Q3: What keyword refers to the current object inside an object's method? A) it B) self C) current D) this *Answer: D*
12. Interview Questions
Q: Explain the difference between Dot Notation and Bracket Notation.
*A: Dot notation (obj.key) is cleaner and easier to read, but the key must be a valid JavaScript identifier (no spaces, doesn't start with a number). Bracket notation (obj["key"]) accepts any string, and is strictly required when evaluating dynamic variables (e.g., obj[dynamicVar]).*
Q: What does Object.keys() return?
*A: It returns an Array containing all the enumerable property names (keys) of an object as strings.*
13. FAQs
Q: What is the difference between JSON and a JavaScript Object? *A: They look identical, but JSON is strictly a text string format used for transmitting data over the network. A JS Object is a live entity in memory. JSON keys MUST be wrapped in double quotes. (We will cover JSON deeply in Chapter 23).*
14. Summary
- Objects store data in Key-Value pairs.
-
Access data using .
or[].
- Functions inside objects are called Methods.
-
Use this
to access sibling properties inside methods.
- Arrays of Objects are the standard way to represent lists of complex data.