ความคิดเห็น •

  • @ethanneff9817
    @ethanneff9817 2 ปีที่แล้ว +1031

    This video is wrongly misguiding developers.
    If you are building an app that doesn’t make a network call or save data, sure Map() and Set() are good alternatives. However, most real-world apps use objects {} because transforming data to Map() or Set() and then back to {} to be serialized is a waste of developer and cpu resources.

    • @alkolaqi83
      @alkolaqi83 2 ปีที่แล้ว +18

      good point

    • @arthurfiorette
      @arthurfiorette 2 ปีที่แล้ว +138

      The way he used map() instead of forEach() is hurting me.

    • @bugs389
      @bugs389 2 ปีที่แล้ว +12

      Agreed. I would also add that if the keys are predicable, and not something user generated, it's no big deal to use an object. Whereas you'd want a map in case one of the keys is no no word like "constructor".

    • @blazefirer
      @blazefirer 2 ปีที่แล้ว +38

      @@arthurfiorette yeah that convertion into an array threw away his whole argument for me

    • @v01d_r34l1ty
      @v01d_r34l1ty 2 ปีที่แล้ว +10

      Ideally, objects should be used to abstract types of data into a single form of encapsulation. It should operate similar to a struct in C.
      Maps should be used where a key needs be matched to a value.
      Arrays should be used to hold multiple instances of the same type of data.
      Classes are just a higher form of abstraction in comparison to objects and should be minimized unless practical.
      If you're not using JavaScript (or TypeScript) this way, as you SHOULD, then you might find yourself in a fucky wucky debugging situation that nobody wants to deal with.
      Edit: If you want to use objects as Maps instead of the actual Map object, that's fine imho, you should just clearly label it as behaving as a map.

  • @Bat-Georgi
    @Bat-Georgi 2 ปีที่แล้ว +62

    I will literally NEVER stop using JS objects.

  • @valtism
    @valtism 2 ปีที่แล้ว +326

    Don't just say that Map is more performant, show us the benchmarks!

    • @alexruedi1995
      @alexruedi1995 ปีที่แล้ว +36

      @@GodOfMacro he obviously has very poor understanding of underlying architecture..

    • @marcioaso
      @marcioaso ปีที่แล้ว +4

      In theory it might depend on the context that they run. Remember that JS is an interpreted language, by who? C++.
      I know where he comes from, it might even be more performatic indeed... but not in all cases... and it might even be the exception.
      The best way to ensure the best performance to your functions is to actually isolate them in a module, and console.time the load tests.
      In an isolated environment, you won´t have a problem running 2, 10mm times your function, and be SURE about what method is faster.

    • @LusidDreaming
      @LusidDreaming ปีที่แล้ว +8

      ​​@@marcioaso interesting fact: std::map in C++ is not a hash map, its a tree. You have to use std::unordered_map to get the traditional hash map (std::map uses a tree structure so that the keys themselves are sorted). Not sure if this has any relevance to JS interpreters, but it blew my mind when I first found that out.

    • @marcioaso
      @marcioaso ปีที่แล้ว

      @@LusidDreaming thanks lusid, makes sense.
      Using a flat object {} as hashmap, you will notice that putting properties there, you end up with an object organized alphabetically.
      At least from what I know from the source at V8, the earliest ancestor any object has is a wasmobject (Assembly maybe, bytecode definitely), which is transformed and enhanced with map and jsobject methods after.
      The Map and Set apis are made from the Object API... in fact, every single other method, function, event... even number or strings.... are made from the same primitive: JSObject.
      That's why (if you have the curiosity to dig into it), the switch inside the object is VERY big.
      If you look into ANY object's ___proto___ property you digging through the chain you will end up at the Object.
      The exception? {}.___proto___ because the object won´t have the property ___proto___ to be read.
      That's why is very unlikely that Map would be faster than simply everyone's ancestor. But (a BIG but in here) depending of the methods you use to extend your object and make it suitable for your needs, maybe is better to use Map, since the heavy work would run at the C++ context.

    • @Bluesourboy
      @Bluesourboy ปีที่แล้ว +2

      Define speed, is speed the time at which the code runs or is it the time for which abstractions can be written and pushed to prod?
      In this case it seems to be the latter which is not bad given we should not prematurely optimize.

  • @alexnezhynsky9707
    @alexnezhynsky9707 2 ปีที่แล้ว +464

    Historically, objects have been used as both dynamic key/value collections and hash tables. Map is a newer feature c. 2014 and tends to have a bigger memory footprint than an object. In fact, objects are more optimal as lookup tables (i.e. read-heavy). As far as dynamic/extensible objects, I still use object literals because their API is simpler, they too maintain the insertion order as of ES2015/ES2020, and as a bonus they're more easily serializable to JSON.

    • @ivanmornar2502
      @ivanmornar2502 2 ปีที่แล้ว +101

      Yeah, this video is just "beginner into to JS map" and nothing more than that, but that title wouldn't get much clicks. Ofc he doesn't speak of limitation's such as "serializable to JSON" issue, his video would suddenly stop being much fun

    • @tuttsj
      @tuttsj 2 ปีที่แล้ว +11

      @@ivanmornar2502 yep same with cloning a Map isn’t much fun either.

    • @t3dotgg
      @t3dotgg 2 ปีที่แล้ว +108

      If data is being serialized, the data has a shape. I explicitly call out that you should stop using Objects for UNSHAPED DATA or DATA THAT HAS KEYS ARBITRARILY CHANGING
      If y'all want to take the worst faith approach to my TITLE, ignore the video, and get pissy about it in the comments, go nuts. Just know I'll make fun of you for it :)

    • @fr5229
      @fr5229 2 ปีที่แล้ว +3

      He actually did call out what he meant, just saying

    • @worldbosspf1
      @worldbosspf1 2 ปีที่แล้ว

      This guy a noob

  • @maruseron
    @maruseron 2 ปีที่แล้ว +9

    died inside when you dumped the map into an array to then map it for side effects instead of just using foreach

  • @AwkworldStudios
    @AwkworldStudios 2 ปีที่แล้ว +150

    I'm not saying he's wrong but as a general rule I am dubious of any performance related claims in JS. Largely this comes down to the fact that we have no idea what kind of performance optimizations the JIT is going to apply.
    There are definitely some good reasons to use Map and Set but I'm going to reserve judgement on performance until I see some bench marks covering a wide range of real world tasks where both the time and memory used is presented.

    • @paales2
      @paales2 2 ปีที่แล้ว +2

      Exactly :)

    • @TrackedHiker
      @TrackedHiker 2 ปีที่แล้ว +3

      Except the spec requires Map and Set to have sublinear performance: better than O(n). So you at least have that guarantee.

    • @JoaoVitor-qy3ze
      @JoaoVitor-qy3ze 2 ปีที่แล้ว +11

      Access of properties with Map.prototype.get are greatly superior when compared to directly accessing an object through object[key] and really makes a difference when iterating over an object vs a map with very large data structures, but is irrelevant for most developers in 99.9% of the world use cases.
      It's a shame that this video argues about it while using something as bad as [...usersMap].map and providing no benchmark as proof of his claims, relying on "just trust me, bro". Seems like a video target at beginners made by someone who's slightly above beginner level

  • @TomDoesTech
    @TomDoesTech 2 ปีที่แล้ว +28

    I'm guilty of objectifying JavaScript

  • @mattvicent
    @mattvicent 2 ปีที่แล้ว +130

    If you're on react land, just stick to using objects for dynamic data, like inside a useState. Your life is going to be so much harder trying to use a map for that, and it's very likely going to be slower.

    • @socratesutui4466
      @socratesutui4466 2 ปีที่แล้ว +2

      useState is ment to use with simple object structures. If your structure is complicated there is useDispatch for that or even better a state library

    • @MrMudbill
      @MrMudbill ปีที่แล้ว +8

      @@socratesutui4466 useDispatch? I think you mean useReducer.

    • @socratesutui4466
      @socratesutui4466 ปีที่แล้ว

      @@MrMudbill indeed!

    • @lohar5055
      @lohar5055 ปีที่แล้ว +2

      ​​​@@kidmoseywe're talking about javascript too. If performance is all we need, why not use wasm?

  • @oggy112
    @oggy112 2 ปีที่แล้ว +9

    I love that I grew up coding and learning Java first because all of these concepts are natural to me

  • @jasonrooney1368
    @jasonrooney1368 2 ปีที่แล้ว +7

    While I probably wouldn't reach for Map here and would likely just use an array of Users (with username, id, and status being part of the User object), I think the key takeaway here is that your object shapes should always be known at compile time if possible. Index keys should be avoided whenever possible, as it leads to unpredictable runtime objects. Of course, they are sometimes useful for highly dynamic patterns, but 99% of the time that's not the case.

    • @t3dotgg
      @t3dotgg 2 ปีที่แล้ว

      Very good summary!

  • @MizManFryingP
    @MizManFryingP ปีที่แล้ว +1

    Me when I remember that nearly everything in Javascript is an object

  • @v01d_r34l1ty
    @v01d_r34l1ty 2 ปีที่แล้ว +108

    I think you're sorely misled by the intentions of these new/common JavaScript features. JavaScript is meant to be an easy, flexible and dynamic language. The purpose of TypeScript is to tone this back because developers oftentimes make minor mistakes that JavaScript won't complain about that lead to unexpected bugs and just waste development time. Features like the Map class aren't necessarily going to be faster. It's just going to make it more obvious what you're doing with your code, and possibly make development easier. Same goes for the .forEach prototype function. It might not be faster than a simple for loop, however it makes it much easier to develop with. JavaScript isn't about speed, and either way, optimizations depend on the engine being used, not [necessarily] the code being run. This is even the same case for lower level and stricter languages like C/C++/Rust.

    • @jared6117
      @jared6117 2 ปีที่แล้ว +1

      good point about engines, see chrome performance calling object read

    • @danieleproia
      @danieleproia ปีที่แล้ว

      they're also kinda annoying in the presence of async stuff

    • @MrMudbill
      @MrMudbill ปีที่แล้ว +1

      Not to mention the speed is in almost all cases still fast enough to not be noticed by anyone. Only in heavy loops or other specific situations may you find yourself needing to forego the more readable code in favor of the more performant code. Generally I tend to just write what is simplest to read and understand, and if I run into performance issues, I look at optimizing for that.

    • @cyrus01337
      @cyrus01337 ปีที่แล้ว

      Optimisations depend on the engine sure, but they also need to take shape where performance is due and this can be because of code you've written, and so refactored code that may include this (as an example, I'd expect stronger and more justified overhauls than objects -> maps) still carries importance.
      I guess the point I'm trying to make here is that it's not always the engine at fault, you could simply underengineer a problem, write a solution then run into performance issues due to unintentional corner cutting - that wouldn't be the engine's fault.
      For the record, everything else I agree with, never been a fan of forEach but man is it convenient when I read other's code that uses it!

    • @v01d_r34l1ty
      @v01d_r34l1ty ปีที่แล้ว +1

      @@cyrus01337 tbf under engineering is a rather insignificant problem because it means you didn’t spend a whole lot of time on it outside of just getting it to work, so you really shouldn’t have a problem spending more time to get it working optimally. It’s not like over engineering where you’re just wasting time for a minimal outcome.

  • @sobanya_228
    @sobanya_228 2 ปีที่แล้ว +12

    In immutable React world maps are kinda awkward to use.
    Sets are nice, when it's possible to use them, but still have the same problem, that identity of your immutable objects changes and the Set can't track it.

    • @DanKaschel
      @DanKaschel 2 ปีที่แล้ว +4

      Yeah, serialization really hurts any attempt to use Map as the de facto js dictionary

    • @bugs389
      @bugs389 2 ปีที่แล้ว +1

      Yup exactly. Also Redux will warn you about using Maps & Sets in state

    • @samuelgunter
      @samuelgunter 2 ปีที่แล้ว

      there are libraries for this such as Immutable JS that implement Map/Set and more with big optimizations so that you don't have to copy data itself if you CRUD a key/value

    • @HonestCode
      @HonestCode 2 ปีที่แล้ว +1

      @@samuelgunter immutable js is kinda outdated now tbh

  • @Guergeiro
    @Guergeiro 2 ปีที่แล้ว +89

    Honestly, basically anytime you have an "id" of some sorts, something that identifies an object, it's probably better to convert to Map/Set instead of keeping it on an Array. The overhead of iterating over an Array and adding it to a Map/Set is probably worth it. If it's not worth it, that probably means that you may not require an array to begin with.

    • @valtism
      @valtism 2 ปีที่แล้ว +5

      There are probably times when you don't want to do that. Redux's normalised data patterns come to mind, because they need to be serialised and Map/Set are not serialisable.

    • @Guergeiro
      @Guergeiro 2 ปีที่แล้ว +3

      @@valtism well, yeah. Even a REST response can't be a Map/Set because of that. But you can easily (de)serialise a Map/Set from/to an Array. If you are always doing searches you can instantly add/search/remove an item and in case the id is not the thing you're looking by, just iterate through the Map/Set like you would in an Array. But then again, I never said you must do that, there are probably cases where you shouldn't, but from those cases, I bet a bunch of them one is simply using an Array or other Data Structure where you shouldn't and the other cases are edge cases.

    • @diogooliveira5320
      @diogooliveira5320 2 ปีที่แล้ว

      Ok Breno, nice.

    • @YaohanChen
      @YaohanChen 2 ปีที่แล้ว

      Set is not usually useful for keeping track of objects since it would compare them by identity. Even if your objects had "id", two items with the same id can still be added to the same Set.

    • @owenizedd2830
      @owenizedd2830 2 ปีที่แล้ว +7

      ​​​​​​@@YaohanChen Correct. To be frank, my life is already easy without the use of Map, why add extra noise to the code because something is underutilized.
      I can see the use case of Set with primitive data type not object, in fact recently I've been working on it. but Map I still haven't, rare case maybe, and I think forcing something to be utilized without good use case gonna make your life harder
      Remember KISS principles guys

  • @kriscpg
    @kriscpg 2 ปีที่แล้ว +70

    Honestly, Theo kind of pisses me off with the whole Twitter entrepreneur vibe and the extremely clickbaity titles/takes, but the js info he gives out is so fucking useful I'm willing to put up with the rest. Thanks for this gem

    • @t3dotgg
      @t3dotgg 2 ปีที่แล้ว +32

      Hey I’ll take it

    • @TayambaMwanza
      @TayambaMwanza 2 ปีที่แล้ว +9

      @@t3dotgg I also read this like, don't know whether to feel offended or complimented

    • @appuser
      @appuser 2 ปีที่แล้ว

      He out there :)

    • @semyaza555
      @semyaza555 2 ปีที่แล้ว

      @@TayambaMwanza Backhanded compliments are the best because even the bystanders are confused.

    • @danielschmitt5750
      @danielschmitt5750 2 ปีที่แล้ว +2

      Imho the info (at least in this video) doesn't compensate for the clickbaity title.

  • @drsensor
    @drsensor 2 ปีที่แล้ว +1

    benchmark?
    I though IC (inline cache) in JSObject will optimize the read/write 🤔
    Also I have been wondering if V8 will store Set as SparseSet since Array stored as packed_smi (packed small integers) 🤔

  • @peterpetersen6613
    @peterpetersen6613 2 ปีที่แล้ว +4

    BTW @Theo your end card "only half my viewers aren't subscribed yet" is always super low in volume compared to the main part.

    • @t3dotgg
      @t3dotgg 2 ปีที่แล้ว +1

      @idez get on it!!

  • @shinobiwannabe
    @shinobiwannabe 2 ปีที่แล้ว +4

    Isn't everything in javascript an object (including functions)

  • @DubiousNachos
    @DubiousNachos 2 ปีที่แล้ว +38

    Hey, Theo. Love your channel, but this is actually an area where I disagree with you. Yeah, Maps are under-used, but their existence doesn't invalidate the use of objects as dictionaries.
    Unless someone strictly needs Maps for their ability to remember insertion order, or their ability to store non-string/non-symbol keys, I don't think they should concern themselves with the difference all that much. Unless, of course, you can speak more to how the pattern breaks optimizations for V8 and the like. I'm definitely not an expert on that, and am approaching things from the perspective of the "letter of the law" from the more abstract/theoretical ECMAscript specification. But in my mind, you're already avoiding de-optimizations to a significant degree by using Typescript - you're structuring your code in a way that prevents variables from holding any arbitrary value, which would help the C++ engine. My gut feeling is that this feels like a weird micro-optimization, or a case of you getting hung up on the fact that you absolutely wouldn't do this in other languages. JS/TS, for better or worse, aren't like other languages, though.
    The biggest sticking point for me, though, is the fact that Maps are not serializable with JSON. So we already have plenty of examples of real-life servers sending dictionary-formatted objects, and things aren't breaking. If you wanted to send plain JSON over the wire, you'd have to convert the map to an anonymous object anyway, which should be a sign that it's not just a matter of objects "not being meant to be used this way". Not many people are using SuperJSON yet.

    • @DanKaschel
      @DanKaschel 2 ปีที่แล้ว +1

      This seems to be the general consensus here.
      But also, I think Theo uses hot takes to stimulate discussion. He's successfully raising awareness of the feature and leaning on the community to moderate the intentional generalization.
      Maybe. I don't know him. I like Theo and choose to believe he is using lack of nuance as an intentional tool and not just being myopic.

    • @StephaneBjrn
      @StephaneBjrn 2 ปีที่แล้ว +6

      I would have loved to hear more about why Maps are better than objects, in what way they are more "optimized"?
      People very often forget how irrelevant it is if there's a difference by a constant factor in the performance between two implementations. Unless you have very specific cases - and 99% of the people don't - it makes no difference whatsoever.

    • @magne6049
      @magne6049 2 ปีที่แล้ว

      @@StephaneBjrn 1 million would be a constant factor, so it’s not that no constant factors matter at any time.

    • @TrackedHiker
      @TrackedHiker 2 ปีที่แล้ว

      Maps are easily serialized using .entries(), unless you have non-string keys, in which case you can’t use an object anyway, so the criticism wouldn’t apply.

  • @jared6117
    @jared6117 2 ปีที่แล้ว +2

    Between objects and maps is object keys are always strings whereas maps can key to any data type. However you can also use classes instead. In frontend it can take the form of state management such as Pinia, Redux...

  • @FunctionGermany
    @FunctionGermany 2 ปีที่แล้ว +2

    i respectfully disagree. you base the initial argument on typescript types, but typescript has the Record type specifically for these kinds of objects. Map needs more resources and is first and foremost for using any data type as an index and not just strings like with objects.
    i'd use Map specifically when i want to store auxiliary data for objects, and otherwise i use records for performance.

  • @Oskar1000
    @Oskar1000 2 ปีที่แล้ว +9

    5:41 If you do Array.from instead of [map...] syntax you can send a second argument to Array.from which is a map function. A bit neater since you avoid creating an entire array just to map yo another Array.
    Haven't checked the speed but I'd presumably Array.from to be faster. It is more ergonomic eitherway.

    • @DanKaschel
      @DanKaschel 2 ปีที่แล้ว

      Don't make untested performance claims. Take a second and test them. CS is full of performance wive's tails.

    • @Oskar1000
      @Oskar1000 2 ปีที่แล้ว

      @@DanKaschel Yeah. That's why I made it clear that I hasn't tested and just told you my assumptions instead. Was that not clear enough?

  • @Stasakusok
    @Stasakusok ปีที่แล้ว +2

    Stop using JavaScript.

  • @PeterBernardin
    @PeterBernardin 2 ปีที่แล้ว +5

    Maps are new in ES6 so if backwards compatibility is a concern, don't use them. They only really work in evergreen browsers. People had to store key of type : some value data since before maps came about a few years ago. Objects were suitable to use. Now maps are better, true.

    • @dhkatz_
      @dhkatz_ 2 ปีที่แล้ว +3

      You say new in ES6 as if ES6 is new. It's been around for 7 years. It's literally standard in every browser with active use. Use Maps and Sets. There is no excuse.

    • @PeterBernardin
      @PeterBernardin 2 ปีที่แล้ว

      @@dhkatz_ If you're making apps and you're not concerned with all your customers being able to use it, that's true. For example you're developing for a bank or something, you're going to want backwards compatibility. I am a fan of maps and I use them as much as I can, but I am aware that by using them I am limiting many older browsers. In most cases I don't care, in some cases I do. It's worth noting.
      The thing is that he is acting as though objects were never made to be used with dynamic keys, which isn't true at all. People have been doing it for literally more than a decade before ES6

    • @appuser
      @appuser 2 ปีที่แล้ว +1

      Backward compatibility just shouldn't be an issue since you can transpile to regular old JavaScript. For a minimal personal project that's not utilizing a package manager, webpack and/or babel I guess you're right though.

    • @PeterBernardin
      @PeterBernardin 2 ปีที่แล้ว

      @@appuser I was actually kind of assuming TS and Babel didn't work with ES6 map but I am probably mistaken

    • @appuser
      @appuser 2 ปีที่แล้ว

      @@PeterBernardin Now I'm curious....

  • @sentinelaenow4576
    @sentinelaenow4576 2 ปีที่แล้ว +3

    There's nothing wrong with Objects, they can be used as dictionaries just fine, they're efficient, expressive and flexible enough to serve all purposes. Anyone could certainly memorize tons of redundant documentation to do the same things, but worse. Most "STOP DOING X" development content are usually awfully wrong.

    • @melonenlord2723
      @melonenlord2723 ปีที่แล้ว

      So is there a situation where a Map is way better than using an object?

  • @jaysistar2711
    @jaysistar2711 2 ปีที่แล้ว +4

    Maps are new in Javascript. Technically, you should have an array of things (let's say users, since that's what you used), and it should include all key/values (the key of your outer object shouldn't be the only time you have the user name), and a map (or object in older Javascript) should be created with keys of 1 of the values in the inner objects, with values that point back to spicific objects in the array, or just index numbers. That object is an "index" (not the number, the map), but you only do that for the keys that you'll need to lookup often. That way, you only iterate through the list when you are creating the index maps, and not when you actually need the list entries; use the index to get the entry at that time. That's also what databases do internally.

  • @__bogdan
    @__bogdan 2 ปีที่แล้ว +1

    I refuse to believe that it's a common pattern to store users in an object

  • @nilo_river
    @nilo_river 2 ปีที่แล้ว +2

    People who work as a tradicional employee will like this.
    People who do code in a creative way will strongly disagree.
    In my case Arrays of Objects is like multiple Swiss Knives.

  • @PieterWigboldus
    @PieterWigboldus 7 หลายเดือนก่อน

    Something many people have to learn is the different why to use object and array.
    For repeating items, like users, use always array. The user itself is an object.
    You can also use map, but if you look like it as json, how you send the data, you will have to use arrays.
    So object has unique fields, array if you have multiple items with the same field. (Array of objects)
    Map and set are also useful, but are more specific, useful to work with lists, to have e.g. unique items in the list.

  • @aram5642
    @aram5642 2 ปีที่แล้ว +1

    Sets and maps are not serializable, so they are not always interchangeable with literals.

    • @mpcref
      @mpcref 2 ปีที่แล้ว

      sure they are!
      JSON.stringify(Object.assign(new Map(), { foo: 'bar' }));
      😜

  • @DiogoSilva-xx8nz
    @DiogoSilva-xx8nz 2 ปีที่แล้ว +4

    and why is it wrong? Object lookups are performant and easy to use.

    • @kezzu5849
      @kezzu5849 2 ปีที่แล้ว +3

      Just feels like another one of his "hot takes". No explanation whatsoever why it's more "optimal" to use a Map instead of an object.
      Honestly you're better off reviewing the design patterns and algorithms in your application than trying to implement micro-optimisations like this; especially without benchmarks.
      Not a hater, I subscribe to his content; but I don't agree with him on this one.

  • @kodekorp2064
    @kodekorp2064 ปีที่แล้ว

    Even working at a small company, I never had code written like this. Objects are mostly use to represent data, not contain multitudes of the same templated data.

  • @darkmift
    @darkmift 2 ปีที่แล้ว +3

    Performance wise iterating over a spread may not be too great.
    You can always use for.

    • @jocke8277
      @jocke8277 2 ปีที่แล้ว

      ya this makes it so you need to iterate over the array twice no

  • @TheYinyangman
    @TheYinyangman ปีที่แล้ว +1

    Object look up with key is faster than map look up with key plenty of videos has benchmarked this

  • @ShaharHarshuv
    @ShaharHarshuv ปีที่แล้ว

    The way objects works under the hood is one of the most misunderstood concepts in JavaScript. I still don't fully understand it. Like property accessing is really quick (quicker than map) but somehow if you change the shape too much you have some performance penalty.

  • @nyteshade
    @nyteshade 2 ปีที่แล้ว +6

    Have to agree with most that indicate ubiquity of Objects for historical and ease of use issues.
    Also you didn’t talk about some of the fundamental differences between map and using an object as a map.
    The keys undefined and null would be different. The fact that you can use true numbers as keys and many other subtleties.

  • @henriquematias1986
    @henriquematias1986 ปีที่แล้ว +1

    At 3:20 +/- you say hurts performance massively!? How do you measure it? Care to benchmark / give IRL example?

  • @NewenF
    @NewenF 6 หลายเดือนก่อน

    Whats the plugin for displaying the values of the console logs after double slash '//' ?

  • @alexruedi1995
    @alexruedi1995 ปีที่แล้ว +2

    i guess you learned JS in the last 2-3 years. Earlier on there were two structures: arrays for repeating objects and objects for key-value pairs.
    If you use map/set, you're either working on a very special project or doing stuff wrong. There is no need to play around with data. The server should expose good API's that are easy to display. If the server says it exists twice, why bother? The backend needs to be fixed then, not the frontend.

  • @nhoj3457
    @nhoj3457 2 ปีที่แล้ว +3

    Thanks! This literally solves, simplifies a problem I was working on!
    I was trying puzzle out a way to iterate over records for politicians where it only shows contirbutions they made or voted etc, but not absent. I was going to make different arrays and iterate until all the records were checked to see if they were there and remove them from the absent array and add them to a yes vote array. Doing this with sets looks like it would be so much easier!

  • @ramielwan48
    @ramielwan48 2 ปีที่แล้ว +1

    The reason I dont use maps is because they are not serializable and redux complains

  • @archmad
    @archmad ปีที่แล้ว

    what i dont like with Map is you cant really console log it without converting it. tracking your items requires extra work

  • @andresaguirregonzalez8651
    @andresaguirregonzalez8651 2 ปีที่แล้ว +17

    Hey Theo! I started watchings your vods around 5 months ago, I've implemented a bunch of your suggested code approaches to ts and js in several projects and seen nothing but good results. Today I landed a great job thanks to most of the good quality content that you show in your channel, this channel is awesome, keep doing what you do, immensely grateful!

    • @sora4222
      @sora4222 11 หลายเดือนก่อน

      As a person reading through these a year later, I hope the job is going well. :)

  • @jcollins519
    @jcollins519 2 ปีที่แล้ว +4

    Maybe "users" isn't the best example. Most of the time I'd imagine that's an object[ ], unless you've reduced it to another data structure for some reason. Then yeah, definitely consider some different data structures beside object. I think in many ways a map is more similar to an array than an object, or perhaps halfway in between the two.

    • @dabbopabblo
      @dabbopabblo 2 ปีที่แล้ว

      That is just completely entirely incorrect in every way shape and form. Just cause it "looks" some way surface level to you doesn't mean that's how it behaves, to make a remark like that you must be new to programing. Maps if you do any research use a hash table look up, and in various benchmarks perform 2 - 10X faster when doing consistent random access and, iteration. And you may not of realized this, but whats stored as values mapped to the keys in a map, can literally be, OBJECTS, making it literally just a more performant alternative to using objects to store for example "users" what you called a bad example, pff

  • @EldorJ10
    @EldorJ10 2 ปีที่แล้ว +3

    Coming from Python where we always use dictionary, this is eye opener. Thanks!

  • @absbica31
    @absbica31 ปีที่แล้ว

    I've used codewhisperer to get the code predictions/recommendations as I type, but is that what your using or something else?

  • @nbear2289
    @nbear2289 ปีที่แล้ว

    Imagine you have a chat application with 1000 channels.
    Should I load all of the chat history each time I call the backend?
    No.
    Should I cache the chat channels?
    Yes
    How will you cache each chat channel state and type checking the incoming 30 parameter so that other developers don't send bad data to the chat channel presentation layer?
    I have worked at very old, large companies that use procedural development cycles and their regression testing misses side-effects on a regular basis. Resulting in tens of thousands of debug hours per year.
    SRP and Open/closed are the most important things to follow. -And then...
    Think of regression testing, reliability, and evolvability when deciding how you are going to architect a system.

  • @darck5240
    @darck5240 ปีที่แล้ว +1

    objects are convenient, if the resource consumption is manageable using them isn't that bad

  • @paulopma
    @paulopma ปีที่แล้ว +1

    Chatgpt tells me objects are faster to iterate.
    "In terms of performance, there are differences between iterating over a plain object literal and a Map, but they can vary depending on the size of the data and the specific context of use.
    Iterating over a plain object literal using methods like Object.keys(), Object.values(), or Object.entries() is generally faster than iterating over a Map. This is because plain object literals are optimized in JavaScript for fast iteration using sequential integer keys.
    On the other hand, Map provides additional features compared to plain object literals, such as the ability to use any value type as a key, maintain insertion order of elements, and offer specific methods for manipulating key-value pairs. These additional features come with a performance cost compared to plain object literals.
    However, in many cases, the performance difference between plain object literals and Map can be negligible, especially for collections of moderate size. The choice between them is often based on the specific needs and desired semantics of the data structure.
    It's important to note that performance optimizations can vary between JavaScript execution engines in different environments (browsers, Node.js, etc.), so it's always recommended to perform specific performance tests for your particular use case to determine which approach provides the best performance in your specific situation."

  • @JulianColeman03
    @JulianColeman03 2 ปีที่แล้ว +1

    I agree and disagree. I agree in that objects of course should not be used as a store of data in this way. It's difficult to read, and you can accidentally overwrite a key, which can cause crude behavior in your application down the road. The caveat to this rule is that it's often how many schemaless "databases" store data (enter Firebase). This is because database objects should retain order, but you cannot declare a Map in JSON, and array order is not guaranteed.
    I disagree with the use of Map and Set here. I haven't watched the vod yet, but I hope you pointed to MDN and covered the technical definitions of each and what their purposes are. The example you gave is a Set of numbers. But this is far from real-world use-case. It's entirely possible you want to dedupe an array of objects returned from an API, but this wasn't covered here. So, my main point of contention is that the first point of the video covered some "big" data, but the end of the video ultimately boiled down to a unique Set of numbers. This is a comparison of apples and oranges.
    HOWEVER, I do appreciate your use of these newer APIs in JS. Please, keep talking about them. As someone who has been a JS dev for over a decade, I'm reluctant to use these APIs as they don't 1:1 replace objects and arrays (which are just objects anyway), but I am keen to find a good use-case in some of my production apps

  • @CyberAnalyzer
    @CyberAnalyzer 2 ปีที่แล้ว +1

    I decided not to use Map and Set, because it would have been more difficult to parse and stringify such data types. Can zod deal with those?

  • @simboy
    @simboy 2 ปีที่แล้ว

    If you convert the array to an object it will only use one instance if 17

  • @tonybaloney212
    @tonybaloney212 ปีที่แล้ว

    type User = Record is perfectly reasonable. I would probably keep lists in an array tho, when will you need to get a specific user by key?

  • @spyroninja
    @spyroninja 2 ปีที่แล้ว +2

    Maps and sets are a real pain point if you're using redux.

  • @jarroddowalter
    @jarroddowalter 2 ปีที่แล้ว

    This is a weird pattern to me... why not have an array of user objects with name, id, and status keys? Then you can just use .find() and .filter() to pull user objects out by key values. Am I missing something?

    • @proro485
      @proro485 2 ปีที่แล้ว

      Because those methods are doing the same thing that is iterating over the whole array. But in case of set every item is unique and you get O(1) lookup whereas in case of array it is O(n)

  • @recursiv
    @recursiv 2 ปีที่แล้ว +2

    Title is clickbait. Objects are not for everything. But they are for some things. It's telling that your users are still objects. So maybe "sometimes don't use objects", but that's not as spicy.

  • @appuser
    @appuser 2 ปีที่แล้ว +8

    I'm embarrassed to say that I do this. Coming from a python background it makes sense I'd get this mixed up. Good explanation. You wouldn't go around creating class definitions for instances of data... that's ridiculous but that's what people do in JavaScript kinda. Will use your alternative.

    • @RudraSingh-pb5ls
      @RudraSingh-pb5ls 2 ปีที่แล้ว +2

      Pardon me but i kinda didn't understand why using onjects is wrong here ? Can u explain ?
      I undestrood the sets part pefectly but failed to differentiate when should be use maps instead of objects ?

    • @hundvd_7
      @hundvd_7 2 ปีที่แล้ว +2

      @@RudraSingh-pb5ls Performance, as I understand. And arguably less verbose type-safety.
      So, if you would have an unknown number of keys in an object, use a Map.
      If you know exactly how many keys the object will have - and it will never change - then use an object.

    • @appuser
      @appuser 2 ปีที่แล้ว

      @@RudraSingh-pb5ls Additionally, I'm also a bit confused when you should specifically use map vs object. What type of data is the best fit for objects?

    • @appuser
      @appuser 2 ปีที่แล้ว +1

      ​ @Rudra Singh I'm not sure if my comparison to classes makes any sense (probably not). However, there are simply disadvantages to using objects for record-like data (e.g. users, contacts etc). The differences and benefits are summarized on the map page in the MDM docs.
      I think the crucial one is performance, while being an iterable, ordered and without keys that you could collide with are just nice-to-have additional benefits of using maps. Using objects in this way will not be a significant issue in most cases but you can flex a little and use the superior option :)

    • @DanKaschel
      @DanKaschel 2 ปีที่แล้ว +2

      @@appuser Literals are a great use for objects as dictionaries. Especially using "as const" at the end, they provide a type-safe way to create a key/value map where the values don't necessarily have the same type.

  • @ChrisosIDK
    @ChrisosIDK ปีที่แล้ว

    Dude, just because you say you shouldn't dynamically change the structure of an object doesn't mean you shouldn't.

  • @nicgeorge6126
    @nicgeorge6126 ปีที่แล้ว

    There is no way this video just told me not to use objects because setting keys is expensive while telling me to pass my maps into an array using the spread operator and running .map() on it performing double memory allocation on the entire map, right?

  • @bernardstachman3507
    @bernardstachman3507 ปีที่แล้ว +1

    stop using ts and use objects everywhere. less garbage in your code is less garbage in your head

  • @dangtrungkien4999
    @dangtrungkien4999 ปีที่แล้ว

    Everything in js is a instance of object, how can we stop using it ?

  • @frantry
    @frantry 2 ปีที่แล้ว

    Hi
    What plugin did you use to get the code autocomplete work so beautifully? Can you please share the autocomplete plugin tool?

    • @proro485
      @proro485 2 ปีที่แล้ว

      GitHub Copilot

  • @nsttt
    @nsttt 2 ปีที่แล้ว +4

    I've tried a few times to use Maps instead of objects, but I mostly end up with type-safety errors. Might need to look into a pattern to use it efficiently

  • @orlvni
    @orlvni 2 ปีที่แล้ว

    stupid question: why not just use arrays?

  • @bestieboots
    @bestieboots ปีที่แล้ว

    I stopped using maps and sets because I started to notice I was the only one using them and I figured they were not a preferred solution

  • @mbaroukh
    @mbaroukh 2 ปีที่แล้ว

    Imho, the problem with set/map is that you can't easily stringify then parse and get a map/set back ... For example when you have data coming from rest API. Or from a persisted store, ...

  • @lucidmach
    @lucidmach 2 ปีที่แล้ว +1

    TL;DR
    maps are not objects, you can delete from an map super easily
    sets are not arrays, you can't have duplicates in sets

  • @marcioaso
    @marcioaso ปีที่แล้ว +1

    No.
    I will continue using object and maps based on the feature specific needs, their module benchmarks, and the knowledge management I've agreed with my plain and junior developers throughout our dojo's.
    That's what a real senior would do, not just spit rules out of his a based on "I need views".
    I will stop recommending you.

  • @herkulessi
    @herkulessi ปีที่แล้ว

    I'm not sure that moving everything to a Map and then COPYING the Map Elements when you want to iterate over it is better...

  • @coolemur976
    @coolemur976 ปีที่แล้ว +1

    Stop misleading people.
    JSON objects can have their own purpose. For example, if you need a fast search by key in a huge list, JSON object outperforms maps.

  • @aditya.khapre
    @aditya.khapre ปีที่แล้ว +1

    Use JS objects, stay based.

  • @4otko999
    @4otko999 ปีที่แล้ว

    great video, and copilot looks like a great extension is there a free alternative?

  • @MartinRojas
    @MartinRojas ปีที่แล้ว +1

    The title is such clickbait!!! Everything in JS is an object. That is still good point on the video

  • @sfulibarri
    @sfulibarri 2 ปีที่แล้ว +1

    Such a contrast between the video being pretty good and the creator being so salty in the comments that his clickbait title backfired lol.

  • @DevinBidwell
    @DevinBidwell 2 ปีที่แล้ว +1

    Stop telling me what I should or shouldn't be using.

  • @13odman
    @13odman 2 ปีที่แล้ว +1

    The main issue with sets and maps is serialization.

  • @Krzysiekoy
    @Krzysiekoy 2 ปีที่แล้ว +3

    Do people actually store users like he showed in the first example? I have never seen that. Usually you would have an array of objects where each object represents a user, and not just have one giant object.

    • @everyhandletaken
      @everyhandletaken 2 ปีที่แล้ว +1

      don't underestimate the power of stupidity 🙂

  • @GoodVolition
    @GoodVolition 2 ปีที่แล้ว +5

    Unfortunately Map was introduced in ES2015 (I think) and because developers have traditionally found ways to use objects for unshaped data and as collections getting started with it can be a sharp edge. I wonder how many devs don't know Map and Set are available.

    • @johndavidson8096
      @johndavidson8096 2 ปีที่แล้ว +1

      This is so funny to me. I always convert my arrays to sets, then back to arrays, in order to remove duplicates. For some reason it has never occurred to me to just use sets to begin with 😂

    • @fujisan0388
      @fujisan0388 ปีที่แล้ว

      Guilty of not knowing Map

  • @insoft_uk
    @insoft_uk 2 ปีที่แล้ว +1

    Interesting title since everything one dose in JavaScript is an object.

  • @MightyKingKala
    @MightyKingKala 2 ปีที่แล้ว

    hello, what's your vs code color theme and icon theme

  • @KendaBeatMaker
    @KendaBeatMaker ปีที่แล้ว

    as a rookie dev that don't know much, I don't really rock with this idea.

  • @MaxPicAxe
    @MaxPicAxe 2 ปีที่แล้ว

    I didn't know copilot could just predict what the value is at runtime and log it out, that is soooo cool!

  • @hayesmaker64
    @hayesmaker64 ปีที่แล้ว

    Everything in Javascript is an object except primitives.

  • @thepanta_82
    @thepanta_82 2 ปีที่แล้ว +4

    When mentioning performance, you need to show some actual benchmarks.

  • @igoralmeida9136
    @igoralmeida9136 2 ปีที่แล้ว +1

    i use object literals everywhere, i know that for lookups it's a lot faster than a array, can you provide some benchmarks showing that Map is faster than object literals?

  • @micycle8778
    @micycle8778 ปีที่แล้ว

    I didn't know map was more performant, I just thought it was more ergonomic with TS' type system

  • @mm_subhan
    @mm_subhan 2 ปีที่แล้ว

    I'm confused between maps and array now. When do I use which. I use arrays but seems like they provide very similar functionality

  • @kennethmiller7109
    @kennethmiller7109 2 ปีที่แล้ว +4

    All of the other errors in this video aside. It is remarkable how both the Set and Map alternatives given in this video perform 20% slower than their traditional counterparts. I'm not seeing a compelling reason to do this aside from safety benefits. You are going to have serialize that data back to standard collections if you are building anything more than a toy.

  • @Ratstail91
    @Ratstail91 2 ปีที่แล้ว

    Hmm... i don't know if I'll suddenly start using maps and sets.

  • @DiThi
    @DiThi ปีที่แล้ว

    I have a function dict() that returns an empty object after doing "delete object.x" which automatically marks the object as a hash table in the JIT. I learned that trick from reading some compiled dart code. I have been doing that before we had official hash maps in the language.

  • @DanielNistrean
    @DanielNistrean 2 ปีที่แล้ว +1

    However you look at this, the title is a Clickbait. I'd say benefits of using maps are significant only in edge cases or search queries. Code readability IMO is way more important în most cases.

  • @abdulrahmanmohamed8298
    @abdulrahmanmohamed8298 ปีที่แล้ว

    what vscode theme is Theo using in the vid?

  • @votienhoang1813
    @votienhoang1813 2 ปีที่แล้ว

    Title should've been "Stop using objects to store key-value data"

  • @abhiramreddy1598
    @abhiramreddy1598 2 ปีที่แล้ว +2

    Wow , I am totally unaware of this information. Thank you.

  • @PauloSantosk
    @PauloSantosk ปีที่แล้ว +1

    Sorry, too much boilerplate code, i will still use javascrpt objects.

  • @ForgottenGames
    @ForgottenGames 2 ปีที่แล้ว

    I use objects all the time when I make HTML/PHP/JS websites.
    Every HTML/PHP page has an object belonging to that page, containing all the functions for the api calls etc.
    e.g.
    const UserPage = {
    getUsers() {
    ///api.get("user")
    },
    putUsers() {
    ///api.put("user");
    }
    }
    etc...
    To say: use maps because they have predefined functions (and then continue to write much more complicated ( 5:40 ) code to get all users for example from a map, is like putting all focus on the predefined functions, and completely negate the much broader capabilities of objects in general.
    I think especially the title is misleading and is like comparing a cat with a beetle.

  • @grimfunk8145
    @grimfunk8145 ปีที่แล้ว +1

    I have no idea why everyone is being so toxic in the comments. He made it clear that if the data is changing a lot use a map. If you know the structure of the data and it doesn't change, use an object. Why is everyone getting hissy about using maps haha.

  • @jhonyortiz5
    @jhonyortiz5 2 ปีที่แล้ว +1

    This feels like a "blah blah blah with this simple trick" kind of video.

  • @semyaza555
    @semyaza555 2 ปีที่แล้ว

    kinda seems like the example started as an array of objects, until someone decided to normalize the data. Why not normalize/denormalize as necessary?

  • @alext5497
    @alext5497 2 ปีที่แล้ว

    Sets in js are just a class which is an obj. I don't get it.