In JavaScript, objects are used to store multiple values in a single variable.
Think of an object like a real-world item, such as a "person." A person has properties like name
, age
, and maybe a method like getFullName()
that tells you the full name.
Unlike primitive types (like numbers or strings), objects are non-primitive and can hold many values using key-value pairs.
How to Create Objects
1. Using Object Literal (Easiest Way)
This is the short and simple way to create an object.
2. Using Object Constructor
This is the longer way using new Object()
.
Accessing Properties and Methods
You can access object values in two ways:
If you call a method without parentheses (like person.getFullName
), it will just return the function code, not the result.
Missing Properties Return undefined
To check if a property exists, use:
Each Object Is Separate
Each object is independent. If you change one, the other doesn’t change — unless they point to the same memory.
Loop Through Object Properties
Use a for...in
loop to go through each property in the object.
Pass by Reference
Objects in JavaScript are passed by reference, not by value.
Nested Objects
You can have objects inside other objects.
Common Mistakes
-
Don’t declare a property without a value:
Summary Table
Topic | Example |
---|---|
Object Literal | var obj = { key: value }; |
Object Constructor | var obj = new Object(); |
Add Property | obj.name = "John"; |
Add Method | obj.sayHi = function() { ... }; |
Access Property | obj.name or obj["name"] |
Access Method | obj.sayHi() |
Check Property Exists | obj.hasOwnProperty("name") |
Loop Through Properties | for (var key in obj) |
Nested Object | obj.address.city |
Pass by Reference | Changes in function affect original object |