DEV Community


Discussion on: How to Deep Clone an Array in JavaScript

alfredosalzillo profile image
Alfredo Salzillo 🐺 • Edited

nice post, but i'd like you to note that there are some difference between deepClone and JSON.stringify/parse.

  • JSON.stringify/parse only work with Number and String and Object litteral without function or Symbol properties.
  • deepClone work with all types, function and Symbol are copied by reference.

Here an example:

const lodashClonedeep = require("lodash.clonedeep");

const arrOfFunction = [() => 2, {
    test: () => 3,
}, Symbol('4')];

// deepClone copy by refence function and Symbol
// JSON replace function with null and function in object with undefined

// function and symbol are copied by reference in deepClone
console.log(lodashClonedeep(arrOfFunction)[0] === lodashClonedeep(arrOfFunction)[0]);
console.log(lodashClonedeep(arrOfFunction)[2] === lodashClonedeep(arrOfFunction)[2]);
samanthaming profile image
Samantha Ming Author

Exactly! Thanks for sharing this! Let me add it to my code notes 👍