DEV Community

Discussion on: Important Javascript functions you have to know to be a better developer

Collapse
 
_genjudev profile image
Larson • Edited

You should not use JSON.stringify to clone object. It leads to problems because it can't strinigfy functions,symbol etc.

JSON.stringify({ 
    fun: () => console.log('lol'), 
    s: Symbol(), 
    u: undefined, 
    n: NaN, 
    in: Infinity
})
'{"n":null,"in":null}'
Enter fullscreen mode Exit fullscreen mode

Just use lodash. Or write your own deep cloning algo. Or when using the browser you can use structuredClone (there are some limits too).

Collapse
 
peerreynders profile image
peerreynders

Node.js 17.0.0 added structuredClone(value[, options])

Before that use v8.serialize(value) and v8.deserialize(buffer).

Then there is flatted which adds recursive references and RecursiveMap on top of JSON (still no functions, symbols, etc.).

Collapse
 
asapsonter profile image
Sam Sonter

noted. thanks

Collapse
 
asapsonter profile image
Sam Sonter

noted. thanks