Wednesday, February 19, 2025

JavaScript, How can we create a copy of Object Literal?

How can we create a copy of Object Literal?


In JavaScript, there are multiple ways to create a copy of an object literal. A copy can be either shallow or deep.

Shallow Copy: Duplicates only the top-level properties. If the object contains nested objects, the inner objects are still referenced (not duplicated).
Deep Copy: Duplicates the object and all nested objects, making an independent copy that doesn’t share references with the original.
Let's explore different methods for each type:

1. Shallow Copy Methods
Method 1: Using Object.assign()
Object.assign() is a method for creating a shallow copy of an object.



const original = { name: "Alice", age: 30 };
const copy = Object.assign({}, original);

copy.name = "Bob";
console.log(original.name); // "Alice" - original is not affected
console.log(copy.name); // "Bob"
Method 2: Using the Spread Operator {...}
The spread operator (...) creates a shallow copy of an object and is often simpler than Object.assign().



const original = { name: "Alice", age: 30 };
const copy = { ...original };

copy.age = 25;
console.log(original.age); // 30 - original is not affected
console.log(copy.age); // 25
2. Deep Copy Methods
For deep copies, we need methods that copy nested objects as well.

Method 1: Using JSON.parse(JSON.stringify())
A common way to create a deep copy is to convert the object to a JSON string and then parse it back into an object. However, this method has limitations (e.g., it won’t handle functions, undefined, Date, or special values like Infinity).



const original = { name: "Alice", age: 30, address: { city: "New York" } };
const deepCopy = JSON.parse(JSON.stringify(original));

deepCopy.address.city = "San Francisco";
console.log(original.address.city); // "New York" - original is not affected
console.log(deepCopy.address.city); // "San Francisco"
Method 2: Using a Recursive Function
For complex objects with nested properties, a recursive function can be used to create a true deep copy.



function deepClone(obj) {
    if (obj === null || typeof obj !== "object") return obj;

    const copy = Array.isArray(obj) ? [] : {};

    for (const key in obj) {
        copy[key] = deepClone(obj[key]);
    }

    return copy;
}

const original = { name: "Alice", age: 30, address: { city: "New York" } };
const deepCopy = deepClone(original);

deepCopy.address.city = "San Francisco";
console.log(original.address.city); // "New York" - original is not affected
console.log(deepCopy.address.city); // "San Francisco"
Summary
Use Object.assign() or spread operator {...} for shallow copies.
Use JSON.parse(JSON.stringify()) for simple deep copies.
Use a recursive function for a more robust deep copy, especially with nested structures.

JavaScript, What is object literal in JavaScript?

What is object literal in JavaScript?
In JavaScript, an object literal is a way to define an object directly using a set of key-value pairs inside curly braces {}. It's one of the most common and straightforward ways to create objects in JavaScript.

Syntax of an Object Literal
Here's a simple example of an object literal:



const person = {
    name: "Alice",
    age: 30,
    job: "Developer",
    greet: function() {
        console.log("Hello, " + this.name);
    }
};
Breakdown of the Syntax
Curly braces {}: Define the boundaries of the object literal.
Key-value pairs: Each entry in the object has a key (also called a property name) and an associated value.
Property values: These can be of any data type, such as strings, numbers, booleans, arrays, functions, and even other objects.
Features of Object Literals
Concise and Readable: Object literals provide a concise way to create objects with properties and methods in one place.

Shorthand for Functions (ES6): You can define methods in an object literal more concisely:



const person = {
    name: "Alice",
    age: 30,
    greet() {
        console.log("Hello, " + this.name);
    }
};
Property Shorthand (ES6): If you have variables with the same name as the property, you can use shorthand notation.



const name = "Alice";
const age = 30;
const person = { name, age }; // equivalent to { name: name, age: age }
Computed Property Names (ES6): You can use expressions as property names by enclosing them in square brackets.



const propName = "age";
const person = {
    name: "Alice",
    [propName]: 30  // equivalent to age: 30
};
Example Usage


const car = {
    brand: "Toyota",
    model: "Corolla",
    year: 2021,
    start() {
        console.log(`${this.brand} ${this.model} is starting...`);
    }
};

console.log(car.brand); // "Toyota"
car.start(); // "Toyota Corolla is starting..."
Benefits of Using Object Literals
Simplicity: No need for new keyword or a constructor function.
Flexibility: You can easily add or remove properties and methods after creating the object.
Readability: It’s easy to understand the structure of an object at a glance.
Object literals are widely used in JavaScript for creating objects with specific properties and methods quickly and are a foundational feature in JavaScript programming.






Hot Topics