Javascript Array and Object Cloning: Shallow or Deep?

Поділитися
Вставка
  • Опубліковано 17 чер 2024
  • Should you clone objects and arrays shallow or deep? What is the difference and when does it matter? Let's dig into Javascript Array and Object cloning so that we can learn once and for all, why and when to use deep or shallow cloning.
    👉 Upcoming NextJS course: pronextjs.dev
    👉 Don't forget to subscribe to this channel for more updates: bit.ly/2E7drfJ
    👉 Discord server signup: / discord
    👉 VS Code theme and font? Night Wolf [black] and Operator Mono
    👉 Terminal Theme and font? oh-my-posh with powerlevel10k_rainbow and SpaceMono NF
    0:00 Introduction
    0:30 What does Cloning?
    1:41 Primitive Values Copy
    2:23 Array and Objects Clone
    3:43 Shallow Cloning
    4:16 Deep Cloning
    6:31 Speed Comparision
    7:15 Recommendations
    8:00 Outroduction
  • Наука та технологія

КОМЕНТАРІ • 47

  • @FuDiep
    @FuDiep 2 місяці тому +13

    Babe wake up, the absolute GOAT came out with a new video

  • @tanercoder1915
    @tanercoder1915 21 день тому +1

    Your Illustratuons were amazing and to the point for those of us visual types 😊

  • @TomAinsworth94
    @TomAinsworth94 2 місяці тому +1

    This is great Jack, thanks a lot! I was mildly aware of deep vs shallow copies/clones but seeing the different use cases, and performance benchmarks is really helpful

  • @JohannPerezE
    @JohannPerezE 2 місяці тому +2

    Please never stop ❤

  • @kettenbach
    @kettenbach 2 місяці тому +11

    I wonder how many likes get missed. Often at the end of a video while I'm watching on my smart TV, it will show thumbnails of other videos. This is when we get reminded to like the video, but at that point you can't like it because pressing up no longer shows the thumbs, but only navigates to the thumbnail. Basically i had to go on my phone in the history and like the video. I wish UA-cam could do better in this case.

    • @dave6012
      @dave6012 2 місяці тому

      Me too man. Same thing. And if you back up to go like the video you can lose your next video recommendation.

    • @AreyHawUstad
      @AreyHawUstad 2 місяці тому +1

      Like is not a big indicator for a viral video, it's the watch time. So if you're watching the full video you're already helping the creator more than liking it.

  • @JohnFarrellDev
    @JohnFarrellDev 2 місяці тому +2

    I just learnt about structuredClone, thank you very much!
    Nice to remove a dependency.

  • @sawankumardas7384
    @sawankumardas7384 Місяць тому +1

    This type content is very rare in UA-cam. To validate your statement and teaching with real experiment where everything is clear cut like Black and White not gray.
    I love this approach of teaching.❤🧡💛💚💙💜
    Hey @jack, can you attach the link where you have tested the speed of the deepclone with various methods ?

  •  Місяць тому +1

    Great!! Best explanation ever!! If we wonder there's a risk changing the original values of array/object maybe there we need deep copy.

  • @victorlongon
    @victorlongon Місяць тому +1

    great video Jack! I started using structuredClone quite a lot. I feel that is depends on the kind of applications you build to shallow vs deep copy.

  • @nigeryanes1987
    @nigeryanes1987 2 місяці тому +1

    Thanks Jack, great video. 👍

  • @jensadria
    @jensadria 2 місяці тому +3

    At 0:36 I thought I was watching the movie "Honey, I Shrunk the Software Developer"

  • @obohp
    @obohp 2 місяці тому +2

    I just asked chatgpt this a day or two ago, you explained it a lot better. Thank you Jack

  • @billybest5276
    @billybest5276 2 місяці тому +1

    Great video I never actually gave it too much thought in js and was excited to see the test results. I typically just create new objects and use the spread operator syntax but structuredClone looks like it could be useful too.

  • @Cahnisama
    @Cahnisama Місяць тому +1

    I had to solve a bug the other day because I didn't understand I was doing a shallow copy with the spread, and unwittingly i was mutating the original object. This stuff is super important

  • @dog4ik
    @dog4ik 2 місяці тому +6

    the fact that Json stringify Json parse "trick" not considered anti-pattern is so f'd up

    • @adambickford8720
      @adambickford8720 2 місяці тому

      This is the community that uses switch(true){}.

  • @yogeshvanzara5553
    @yogeshvanzara5553 2 місяці тому +2

    Back to back quality content ❤ .
    can you make on vedio on "this" if possible it's confusing with normal fuction and arrow function and lot more with this?.

  • @darwinvilcachaguaayala7647
    @darwinvilcachaguaayala7647 2 місяці тому

    big fan here from Lima - Perú

  • @deatho0ne587
    @deatho0ne587 2 місяці тому +1

    Shallow when you can, deep when you have to. If it is straight from the API you should do a deep with verification/modifications anyways.
    StructuredClone vs JSON.parse/stringfy is not only about performance and Dates. StructuredClone is Chrome 98 and 2022+ browsers roughly. This most likely does not matter for your personal projects, but need to think about it for Enterprise software. Also can target older versions of ES if needed in package.json.

  • @hartesgeld
    @hartesgeld 2 місяці тому +2

    Jack Herrington is a legend. Simple as that.

  • @andrewbrowne8498
    @andrewbrowne8498 2 місяці тому

    I know you kept it to built-in methods, but a video about tools like immer would be really cool

  • @karwanrasul7450
    @karwanrasul7450 Місяць тому +1

    very usefull

  • @sterlo
    @sterlo 2 місяці тому +2

    That's a lot of AI/bot comments 😂- thanks for the video. Really interesting to see that the newly implemented method is slower in this case.

  • @muhammadmuzammil7592
    @muhammadmuzammil7592 29 днів тому

    Great 🎉

  • @pw.70
    @pw.70 2 місяці тому

    Wow! Amazing how the 'optimised' code written by the JS team is way slower than a double conversion!

  • @msahu2595
    @msahu2595 2 місяці тому +1

  • @FrontendNerd-lg3oh
    @FrontendNerd-lg3oh Місяць тому +1

    more Javascript tutorials

  • @Ga2-20
    @Ga2-20 2 місяці тому

    Hey Jack!
    What is your best JS framework and why? Do you even have something like best framework? 😅
    I mean I want to be good at one or two that are enough to build things fast efficiently and flexible on production. I see everywhere people are doing click bait videos why I don't yes this and that, and you shouldn't too 😂
    I really know that you have a lot of knowledge and great content, that's why I am asking 🙂
    God bless you!

    • @jherr
      @jherr  2 місяці тому +1

      Thanks. And no, I don't think there is "one size fits all" best framework. You could have a content heavy application with only small areas of client side functionality (i.e. islands). For that I'd use Astro or HTMX. You could have a very heavy client side app with no requirements for SSR and for that I might look at something like React in a SPA mode on Vite, or Solid.
      If I had to pick two I'd probably go with NextJS and Astro. I think you effectively pick up SPA almost for free with NextJS. All you need to learn is a router like React Router or Tanstack Router.

  • @abhishek_k7
    @abhishek_k7 Місяць тому

    I see that you are a Godzilla/Gojira fan too!

  • @coolmind2476
    @coolmind2476 2 місяці тому

    How about a simple recursive function for deep cloning? Just check if each item of an array is an array, if yes, make a recursive call, if not, Return spreaded ...item.
    Could you do a speed comparison as well?

    • @jherr
      @jherr  2 місяці тому

      I could do that, but I know what the results will be. Any native methods (structuredClone or shallow clone) will blow the freaking doors off of logic running in JS.

    • @jherr
      @jherr  2 місяці тому +2

      Ok, I was wrong, turns out it's faster. jsbenchmark.com/#eyJjYXNlcyI6W3siaWQiOiJDVlA1V1c0bzVDNjlYVktLNVBORHEiLCJjb2RlIjoiSlNPTi5wYXJzZShKU09OLnN0cmluZ2lmeShEQVRBKSk7IiwiZGVwZW5kZW5jaWVzIjpbXSwibmFtZSI6IkpTT04uc3RyaW5naWZ5In0seyJpZCI6IlBoSVVNTW9yLXZNVHhzcGt6Q3ZZbyIsImNvZGUiOiJzdHJ1Y3R1cmVkQ2xvbmUoREFUQSk7IiwibmFtZSI6IlN0cnVjdHVyZWRDbG9uZSIsImRlcGVuZGVuY2llcyI6W119LHsiaWQiOiJMY3hFanVLRzRhWl90LTZ3bjNWU3kiLCJjb2RlIjoiZnVuY3Rpb24gY2xvbmVPYmplY3Qob2JqKSB7XG4gIGlmKEFycmF5LmlzQXJyYXkob2JqKSkge1xuICAgIHJldHVybiBvYmoubWFwKGNsb25lT2JqZWN0KTtcbiAgfSBlbHNlIGlmKHR5cGVvZiBvYmogPT09ICdvYmplY3QnKSB7XG4gICAgcmV0dXJuIE9iamVjdC5lbnRyaWVzKG9iaikucmVkdWNlKChhY2MsIFtrZXksIHZhbHVlXSkgPT4ge1xuICAgICAgYWNjW2tleV0gPSBjbG9uZU9iamVjdCh2YWx1ZSk7XG4gICAgICByZXR1cm4gYWNjO1xuICAgIH0sIHt9KTtcbiAgfSBlbHNlIHtcbiAgICByZXR1cm4gb2JqO1xuICB9XG59XG5jbG9uZU9iamVjdChEQVRBKSIsIm5hbWUiOiJDb3B5IHdpdGggSlMiLCJkZXBlbmRlbmNpZXMiOltdfV0sImNvbmZpZyI6eyJuYW1lIjoiRGVlcCBDbG9uZSB3aXRoIEpTIiwicGFyYWxsZWwiOnRydWUsImdsb2JhbFRlc3RDb25maWciOnsiZGVwZW5kZW5jaWVzIjpbXX0sImRhdGFDb2RlIjoicmV0dXJuIG5ldyBBcnJheSgxMDAwMCkuZmlsbCgwKS5tYXAoKCkgPT4gKFxuICB7IGE6IFt7IHA6IDEgfSx7IHA6IDIgfSx7IHA6IDQgfV0sIGI6IFt7IHA6IFsxLDIsM10gfSw1LDZdLCBjOiBbNyw4LDldIH1cbikpOyJ9fQ

  • @keithjohnson6510
    @keithjohnson6510 2 місяці тому

    Seems odd that structuredClone is slower. I assume because JSON is used so much in JS, it's been optimised to the hilt. So looks like structuredClone could do with some love here.
    I had a need to send JS Objects over a websocket connection, JSON was of course too limited, I needed Dates & Buffers etc. So just created a simple ObjectToBinary, & BinaryToObject, later I thought, actually that's also handy for Cloning & comparing objects too. Would have been much nicer if Javascript had this feature built in, as of course with my code not been Native it's slower, but doesn't seem to be an issue for what I need it for, even running on mobile etc. ps. I did look at NPM for something similar but couldn't find anything at the time, eg. js-binary requires a schema, I just wanted to pass an object and convert to & from binary, with custom types too.

    • @jherr
      @jherr  2 місяці тому

      Structured Clone is slower, yes. But it's also more compatible that JSON.parse(JSON.stringify()) and there is question of how much you are calling it. If you don't call it continuously then most likely in common use cases there won't be a noticable performance impact.

  • @noahwinslow3252
    @noahwinslow3252 2 місяці тому

    Is lodash just bloat at this point? Every time my coworker uses lodash I feel like I could write the method myself with less work, more clarity and more efficient code. And I also flash back to the article "Why you probably don't need lodash"

    • @odra873
      @odra873 2 місяці тому +1

      I still use lodash, why should I implement something that already covers all edge cases, is known in the team and tested?
      you write tests for your own implementation, everyone knows that you added it and not a second person add the same function somewhere else? (We have over 100 devs in our code base)
      And you sure you’re more efficient? Does it even make a difference if you don’t use it at 100k dataset size?
      Bunch of points to consider just to have 3 lines of code nicer which you look at maybe once a year

    • @jherr
      @jherr  2 місяці тому

      I don't think it's either/or. For example I'd rather see someone use `array.filter` in it's native form as opposed to `_.filter`. And a lot of Lodash covers these common cases that are now covered by ES6. And ES6 was released eight years ago. Having a look at the Lodash docs I'd say that roughly 60% of these methods are either directly replaced by ES6, or an ES6 one-liner. But for those 40% I might use Lodash for that.

    • @noahwinslow3252
      @noahwinslow3252 2 місяці тому

      @@jherr this 100% there's certainly good lodash functions but when I see people reaching for _.filter or _.sort I'm like... You know this exists in JS now, right? My page bundle thanks you 😂

    • @borisjoffe
      @borisjoffe 2 місяці тому

      lodash can be really fast

  • @darwinvilcachaguaayala7647
    @darwinvilcachaguaayala7647 2 місяці тому

    subido hace 7 segundos y ya tiene vistas. xd

  • @user-ik7rp8qz5g
    @user-ik7rp8qz5g 2 місяці тому +2

    I will take pineapple pepperoni pizza

  • @voidmind
    @voidmind Місяць тому

    All the functions I write are pure functions, so I have some deep copying happening all over my code, and honestly the performance penalty is not noticeable. You'd have to use pretty huge data structures to notice it.