w3resource

JavaScript: Create a shallow clone of an object

JavaScript fundamental (ES6 Syntax): Exercise-146 with Solution

Shallow Clone Object

Write a JavaScript program to create a shallow clone of an object.

  • Use Object.assign() and an empty object ({}) to create a shallow clone of the original.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2

// Define the shallowClone function
const shallowClone = obj => Object.assign({}, obj);

// Create an object 'a'
const a = { x: true, y: 1 };

// Clone object 'a' into object 'b'
const b = shallowClone(a);

// Log the cloned object 'b'
console.log(b); // Output: { x: true, y: 1 }

Output:

{"x":true,"y":1}

Visual Presentation:

JavaScript Fundamental: Create a shallow clone of an object.

Flowchart:

flowchart: Create a shallow clone of an object

Live Demo:

See the Pen javascript-basic-exercise-146-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that creates a shallow clone of an object using Object.assign.
  • Write a JavaScript function that copies an object’s own properties into a new object without deep cloning nested objects.
  • Write a JavaScript program that demonstrates shallow cloning by modifying the clone and showing the original remains partially linked.

Go to:


PREV : Randomize Array Values.
NEXT : Serialize Cookie Name-Value to Set-Cookie Header.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.