An object is one of the eight fundamental data types in JavaScript. Unlike the other seven primitive data types (e.g., numbers, strings, booleans), which represent a single value, an object can store multiple values. These values are organized as properties
, consisting of key-value
pairs. The key is always a type string or symbol and the value can be of any type.
Initialization:
const myObj = new Object();
const myObj = {}; // more commonly used
Accessing Object Properties
There are two primary ways to access an object's properties: dot notation and square bracket notation.
Dot Notation
Dot notation is used for literal property names and searches for the property as it is written. Dot notation is more commonly used than square bracket notation because it is simple and concise. However, it only works with valid JavaScript identifiers (e.g., no spaces or special characters).
let user = { name: "John", age: 30 };
console.log(user.name); //John
Square Bracket Notation
Square brackets allow dynamic property access in the following cases:
- When a key consists of multiple words with whitespace:
e.g.
myObj[my computer]
- When a variable or an expression is used to access the value:
let user = { name: "John", age: 30 };
let key = prompt("What do you want to know about the user?", "name");
// access by variable
alert( user[key] ); // John (if enter "name")
The Modern JavaScript Tutorial
With Computed Properties
Square brackets can also be used to create properties dynamically:
let fruit = prompt("Which fruit to buy?", "apple");
let bag = {
[fruit]: 5, // the name of the property is taken from the variable fruit
};
alert( bag.apple ); // 5 if fruit="apple"
This is equivalent to:
let fruit = prompt("Which fruit to buy?", "apple");
let bag = {};
// take property name from the fruit variable
bag[fruit] = 5;
The Modern JavaScript Tutorial
Primitive vs Object
One of the key differences between primitives and objects is how they are stored and copied.
Primitives
- Primitives are stored by value.
- When assigned to a variable or passed as an argument, the value is copied.
let message = "Hello";
let greeting = message;
message = message + " World!";
console.log(message); // Hello World!
console.log(greeting); // Hello
Objects
- Objects are stored by reference.
- When copied, the reference to the object is copied rather than duplicating the object itself. Both variables point to the same object in memory.
let user = { name: 'John' };
let admin = user;
admin.name = 'Pete'; // changed by the "admin" reference alert(user.name); // 'Pete', changes are seen from the "user" reference
The Modern JavaScript Tutorial
Cloning Objects
To duplicate an object with the same structure, you can use a for-of loop to copy the properties one by one. However, there's a more efficient method: Object.assign
Object.assign(dest, ...sources)
dest
: The destination object, to which we want to copy the properties
sources
: The objects whose properties we want to copy
let user = { name: "John", age: 30 };
let clone = Object.assign({}, user);
alert(clone.name); // John
alert(clone.age); // 30
The Modern JavaScript Tutorial
Nested Cloning
When an object contains another object, which is stored in a separate memory space, we explicitly clone it as well. This process is called "deep cloning" or "structured cloning". JavaScript provides a method for this: structuredClone(object)
let user = {
name: "John",
sizes: {
height: 182,
width: 50
}
};
let clone = structuredClone(user);
alert( user.sizes === clone.sizes ); // false, different objects
// user and clone are totally unrelated now
user.sizes.width = 60; // change a property from one place alert(clone.sizes.width); // 50, not related
The Modern JavaScript Tutorial
Checking Property Existence Using the Binary in Operator
To check whether a property exists in an object, use the in operator. It returns true if the property exists and false otherwise.
"key" in object
let user = { name: "John", age: 30 };
alert( "age" in user ); // true, user.age exists
alert( "blabla" in user ); // false, user.blabla doesn't exist
The Modern JavaScript Tutorial
Objects have more aspects to explore, such as properties and classes. It's helpful to learn the fundamentals step by step, and I've already noticed some improvement and growth in my coding as a result.
Top comments (0)