Objects
1.How would you clone an object?
In JavaScript, there are a few ways to clone an object:
- Using the spread operator:
const originalObj = { a: 1, b: 2, c: 3 };
const clonedObj = { ...originalObj };- Using
Object.assign():
const originalObj = { a: 1, b: 2, c: 3 };
const clonedObj = Object.assign({}, originalObj);- Using
JSON.parse()andJSON.stringify():
const originalObj = { a: 1, b: 2, c: 3 };
const clonedObj = JSON.parse(JSON.stringify(originalObj));It's important to note that the first two methods will only create a shallow clone of the object, meaning that any nested objects or arrays will still be references to the original object. The third method will create a deep clone, but it won't work if the object contains functions, symbols or undefined values.