Stop Using Javascript Objects

  Рет қаралды 196,886

Theo - t3․gg

Theo - t3․gg

2 жыл бұрын

Seriously, objects are not for everything.
Huge s/o Idez as always!!!
Follow me on...
Twitch: / theo
Twitter: / t3dotgg
Instagram: / fakiebigfoot
Everywhere else: t3.gg/links

Пікірлер: 494
@Bat-Georgi
@Bat-Georgi Жыл бұрын
I will literally NEVER stop using JS objects.
@ethanneff9817
@ethanneff9817 2 жыл бұрын
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 жыл бұрын
good point
@arthurfiorette
@arthurfiorette 2 жыл бұрын
The way he used map() instead of forEach() is hurting me.
@bugs389
@bugs389 2 жыл бұрын
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 жыл бұрын
@@arthurfiorette yeah that convertion into an array threw away his whole argument for me
@v01d_r34l1ty
@v01d_r34l1ty 2 жыл бұрын
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.
@valtism
@valtism 2 жыл бұрын
Don't just say that Map is more performant, show us the benchmarks!
@alexruedi1995
@alexruedi1995 Жыл бұрын
@@GodOfMacro he obviously has very poor understanding of underlying architecture..
@marcioaso
@marcioaso Жыл бұрын
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 Жыл бұрын
​​@@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.
@josefaguilar2955
@josefaguilar2955 11 ай бұрын
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.
@maruseron
@maruseron Жыл бұрын
died inside when you dumped the map into an array to then map it for side effects instead of just using foreach
@alexnezhynsky9707
@alexnezhynsky9707 2 жыл бұрын
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 жыл бұрын
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 жыл бұрын
@@ivanmornar2502 yep same with cloning a Map isn’t much fun either.
@t3dotgg
@t3dotgg 2 жыл бұрын
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 жыл бұрын
He actually did call out what he meant, just saying
@worldbosspf1
@worldbosspf1 2 жыл бұрын
This guy a noob
@AwkworldStudios
@AwkworldStudios 2 жыл бұрын
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 жыл бұрын
Exactly :)
@TrackedHiker
@TrackedHiker Жыл бұрын
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 Жыл бұрын
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 жыл бұрын
I'm guilty of objectifying JavaScript
@SoreBrain
@SoreBrain 2 жыл бұрын
same 😔
@genelorenzsarmiento
@genelorenzsarmiento 2 жыл бұрын
@@SoreBrain (2)
@shrin210
@shrin210 Жыл бұрын
😂😂😂
@mattvicent
@mattvicent 2 жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@socratesutui4466 useDispatch? I think you mean useReducer.
@socratesutui4466
@socratesutui4466 Жыл бұрын
@@MrMudbill indeed!
@lohar5055
@lohar5055 9 ай бұрын
​​​@@kidmoseywe're talking about javascript too. If performance is all we need, why not use wasm?
@v01d_r34l1ty
@v01d_r34l1ty 2 жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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.
@NewenF
@NewenF 3 ай бұрын
Whats the plugin for displaying the values of the console logs after double slash '//' ?
@DubiousNachos
@DubiousNachos 2 жыл бұрын
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 жыл бұрын
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 жыл бұрын
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 Жыл бұрын
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.
@nhoj3457
@nhoj3457 2 жыл бұрын
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!
@CyberAnalyzer
@CyberAnalyzer 2 жыл бұрын
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?
@oggy112
@oggy112 2 жыл бұрын
I love that I grew up coding and learning Java first because all of these concepts are natural to me
@sobanya_228
@sobanya_228 2 жыл бұрын
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 жыл бұрын
Yeah, serialization really hurts any attempt to use Map as the de facto js dictionary
@bugs389
@bugs389 2 жыл бұрын
Yup exactly. Also Redux will warn you about using Maps & Sets in state
@samuelgunter
@samuelgunter Жыл бұрын
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 Жыл бұрын
@@samuelgunter immutable js is kinda outdated now tbh
@kriscpg
@kriscpg 2 жыл бұрын
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 жыл бұрын
Hey I’ll take it
@TayambaMwanza
@TayambaMwanza 2 жыл бұрын
@@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 жыл бұрын
Imho the info (at least in this video) doesn't compensate for the clickbaity title.
@peterpetersen6613
@peterpetersen6613 2 жыл бұрын
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 жыл бұрын
@idez get on it!!
@jasonrooney1368
@jasonrooney1368 Жыл бұрын
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 Жыл бұрын
Very good summary!
@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
@MizManFryingP
@MizManFryingP 9 ай бұрын
Me when I remember that nearly everything in Javascript is an object
@ygaummm
@ygaummm Жыл бұрын
What is that extension that prints ou the console.log on the IDE?
@shinobiwannabe
@shinobiwannabe 2 жыл бұрын
Isn't everything in javascript an object (including functions)
@shineymcshine
@shineymcshine Жыл бұрын
Yes.
@abdulrahmanmohamed8298
@abdulrahmanmohamed8298 Жыл бұрын
what vscode theme is Theo using in the vid?
@absbica31
@absbica31 Жыл бұрын
I've used codewhisperer to get the code predictions/recommendations as I type, but is that what your using or something else?
@andythedishwasher1117
@andythedishwasher1117 Жыл бұрын
Ok this is awesome, but how compatible are these data types with networking protocols? For example, it's incredibly easy to just stringify an object or array and toss it into a request body with an application/json content-type header. Do we have similar protocols for transmitting maps and sets across the network? I'm about to do a lot more research into this because it would massively simplify a lot of the workflows I've been developing for my no-code platform if I could accept these data types in my graphql schema for running CRUD on my Atlas cluster.
@frantry
@frantry Жыл бұрын
Hi What plugin did you use to get the code autocomplete work so beautifully? Can you please share the autocomplete plugin tool?
@proro485
@proro485 Жыл бұрын
GitHub Copilot
@QuadDrums
@QuadDrums Жыл бұрын
Bro this video blew my mind. But I do have a question. Can you provide an example of how you would initialize a Map for the initial state of useState? I also use a onchange handler on my form that uses the name attribute to update an object which represents all the data in my form (rather than having one useState for each input field). Would that be a good useCase for the Map?
@MightyKingKala
@MightyKingKala Жыл бұрын
hello, what's your vs code color theme and icon theme
@Guergeiro
@Guergeiro 2 жыл бұрын
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 жыл бұрын
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 жыл бұрын
@@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 Жыл бұрын
​​​​​​@@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
@jared6117
@jared6117 Жыл бұрын
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...
@staticyawn
@staticyawn Жыл бұрын
Does anyone know what vscode theme this is?
@ericechemane3335
@ericechemane3335 Жыл бұрын
What is your vscode theme?
@SupertigerDev
@SupertigerDev 2 жыл бұрын
Cant use maps in react or solidjs while also making them reactive :/
@robinstevens8712
@robinstevens8712 2 жыл бұрын
Is there an easy way to switch from Objects to Maps when you're communicating with a backend, hence having to convert from/to JSON ?
@rex_melynas
@rex_melynas Жыл бұрын
Yes, use the toJSON() method
@nyteshade
@nyteshade 2 жыл бұрын
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.
@RaducuGabriel
@RaducuGabriel Жыл бұрын
Is Copilot safe to use for non-personal projects?
@kdme
@kdme 2 жыл бұрын
can you now use this in a react component?
@drsensor
@drsensor 2 жыл бұрын
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) 🤔
@4otko999
@4otko999 Жыл бұрын
great video, and copilot looks like a great extension is there a free alternative?
@jaysistar2711
@jaysistar2711 2 жыл бұрын
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.
@Oskar1000
@Oskar1000 2 жыл бұрын
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?
@SenthuranElangovan
@SenthuranElangovan 2 жыл бұрын
How to use this is react's useState ?
@thekwoka4707
@thekwoka4707 Жыл бұрын
Then why does the Record built in type for?
@henriquematias1986
@henriquematias1986 Жыл бұрын
At 3:20 +/- you say hurts performance massively!? How do you measure it? Care to benchmark / give IRL example?
@igoralmeida9136
@igoralmeida9136 2 жыл бұрын
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?
@stercorarius
@stercorarius 2 жыл бұрын
its not faster
@sentinelaenow4576
@sentinelaenow4576 Жыл бұрын
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 9 ай бұрын
So is there a situation where a Map is way better than using an object?
@owenwexler7214
@owenwexler7214 Жыл бұрын
I had no idea Maps were a thing and I've been using objects as dictionaries/maps a lot. There may be some rewrites in my API's future, maybe will try them out in the Drizzle prototype first. Burning question: can JS Maps be serialized and passed from a backend to a frontend? We currently do this with some of our KV object dictionaries.
@HorizonHuntxr
@HorizonHuntxr 2 жыл бұрын
What theme is this ?
@derciojds
@derciojds 2 жыл бұрын
Which VS code theme are you using sir?
@t3dotgg
@t3dotgg 2 жыл бұрын
t3.gg/faq
@PeterBernardin
@PeterBernardin 2 жыл бұрын
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 жыл бұрын
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 жыл бұрын
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....
@thatsinteresting8479
@thatsinteresting8479 2 жыл бұрын
what are the vs code extensions you are using and how is it auto complete so nicely
@simonhylander7489
@simonhylander7489 2 жыл бұрын
Copilot
@thatsinteresting8479
@thatsinteresting8479 2 жыл бұрын
Thanks I'm gonna try that
@noone-gz4pc
@noone-gz4pc Жыл бұрын
does anyone know which vscode theme he's using?
@ghevisartor6005
@ghevisartor6005 Жыл бұрын
Ok im a .net developer so I dont have much experience with javascript. I needed to use it with some js libraries and blazor. The thing is, js objects are awesome, but when i see that i write the same object two times, was wrong of me to put in a js class? I know js classes aren't like c# ones but still. More often then not i found my self factoring out a js object to a class. I didn't have to send them over http requests tho.
@__bogdan
@__bogdan 2 жыл бұрын
I refuse to believe that it's a common pattern to store users in an object
@ShaharHarshuv
@ShaharHarshuv 9 ай бұрын
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.
@kodekorp2064
@kodekorp2064 9 ай бұрын
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.
@EldorJ10
@EldorJ10 2 жыл бұрын
Coming from Python where we always use dictionary, this is eye opener. Thanks!
@AllanSavolainen
@AllanSavolainen Жыл бұрын
Shouldn't all this work happen in the database? So it wouldn't matter at all what you use in JS?
@darck5240
@darck5240 Жыл бұрын
objects are convenient, if the resource consumption is manageable using them isn't that bad
@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
@paulopma
@paulopma Жыл бұрын
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."
@dangtrungkien4999
@dangtrungkien4999 Жыл бұрын
Everything in js is a instance of object, how can we stop using it ?
@DiogoSilva-xx8nz
@DiogoSilva-xx8nz 2 жыл бұрын
and why is it wrong? Object lookups are performant and easy to use.
@kezzu5849
@kezzu5849 2 жыл бұрын
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.
@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?
@andresaguirregonzalez8651
@andresaguirregonzalez8651 2 жыл бұрын
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 8 ай бұрын
As a person reading through these a year later, I hope the job is going well. :)
@jcollins519
@jcollins519 2 жыл бұрын
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
@darkmift
@darkmift 2 жыл бұрын
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
@MarlonEnglemam
@MarlonEnglemam 2 жыл бұрын
I loved your explanation of maps and yeah I'm guilty of never using them so from now on I should be more cautious and give it more attention than I have given, on the other hand I think I'll still stick with literal objects most of the time since the scenarios where I usually use them don't need to deal with so much data so performance won't be much of a downside and I believe it's worth the fact that the object's syntax is much simpler and more readable
@animedreamz2009
@animedreamz2009 2 жыл бұрын
I forgot about maps and sets. I use objects for data for my webgl stuff like uniforms and options. I don’t get the type script thing. It’ll compile to vanilla js anyway.
@PieterWigboldus
@PieterWigboldus 4 ай бұрын
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.
@Khari99
@Khari99 2 жыл бұрын
I’ve been using sets forever but never maps for some reason. Good stuff
@jamesjones2212
@jamesjones2212 2 жыл бұрын
Thanks this addresses a problem i had the other day one of the plights of being a polygot is taking habits from other languages and applying it to whatever you are working on
@nilo_river
@nilo_river 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.
@simboy
@simboy 2 жыл бұрын
If you convert the array to an object it will only use one instance if 17
@alexruedi1995
@alexruedi1995 Жыл бұрын
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.
@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.
@toastrecon
@toastrecon 2 жыл бұрын
So interesting. I hadn’t seen those used before. Thanks!
@lucidmach
@lucidmach Жыл бұрын
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
@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.
@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, ...
@thepanta_82
@thepanta_82 2 жыл бұрын
When mentioning performance, you need to show some actual benchmarks.
@orlvni
@orlvni 2 жыл бұрын
stupid question: why not just use arrays?
@TheYinyangman
@TheYinyangman Жыл бұрын
Object look up with key is faster than map look up with key plenty of videos has benchmarked this
@MaxPicAxe
@MaxPicAxe Жыл бұрын
I didn't know copilot could just predict what the value is at runtime and log it out, that is soooo cool!
@abhiramreddy1598
@abhiramreddy1598 2 жыл бұрын
Wow , I am totally unaware of this information. Thank you.
@nicgeorge6126
@nicgeorge6126 10 ай бұрын
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?
@klemenko345
@klemenko345 2 жыл бұрын
Would you be open to making more of these data structures / patterns videos? This is very informative, thank you!
@archmad
@archmad 11 ай бұрын
what i dont like with Map is you cant really console log it without converting it. tracking your items requires extra work
@ryanmatthews5771
@ryanmatthews5771 2 жыл бұрын
MY GUY I'm currently studying for interviews with google. I thought I was gonna have to learn Java for it and learned about these things in Java, but I was able to come back to JS. I wished I had these. Apparently, I do! Thank you!
@nsttt
@nsttt 2 жыл бұрын
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
@MartinRojas
@MartinRojas Жыл бұрын
The title is such clickbait!!! Everything in JS is an object. That is still good point on the video
@edipedipbulmaz
@edipedipbulmaz 8 ай бұрын
"Don't use {}" how am i supposed to write functions?
@ramielwan48
@ramielwan48 2 жыл бұрын
The reason I dont use maps is because they are not serializable and redux complains
@aram5642
@aram5642 2 жыл бұрын
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' })); 😜
@FunctionGermany
@FunctionGermany Жыл бұрын
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.
@abhinavrobinson2310
@abhinavrobinson2310 2 жыл бұрын
Would love to see more content like this, amazing explainer :D
@jarroddowalter
@jarroddowalter Жыл бұрын
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 Жыл бұрын
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)
@sfulibarri
@sfulibarri Жыл бұрын
Such a contrast between the video being pretty good and the creator being so salty in the comments that his clickbait title backfired lol.
@micycle8778
@micycle8778 Жыл бұрын
I didn't know map was more performant, I just thought it was more ergonomic with TS' type system
@stahlmandesign
@stahlmandesign Жыл бұрын
I was skeptical of this video's title, but you made good points. I knew about Set (and have used it), but not Map. Thanks for sharing insight.
Authentication: It’s Easier Than You Think
21:05
Theo - t3․gg
Рет қаралды 141 М.
Map vs Object in JavaScript
14:33
Leigh Halliday
Рет қаралды 21 М.
I wish I could change THIS fast! 🤣
00:33
America's Got Talent
Рет қаралды 121 МЛН
Дибала против вратаря Легенды
00:33
Mr. Oleynik
Рет қаралды 5 МЛН
ИРИНА КАЙРАТОВНА - АЙДАХАР (БЕКА) [MV]
02:51
ГОСТ ENTERTAINMENT
Рет қаралды 15 МЛН
The Truth About Bun
13:35
Theo - t3․gg
Рет қаралды 196 М.
Reacting to Controversial Opinions of Software Engineers
9:18
Fireship
Рет қаралды 2 МЛН
Your Goals Kinda Suck - LEVEL UP As A Developer
34:40
Theo - t3․gg
Рет қаралды 142 М.
Evolution of Signals in JavaScript
24:17
ThePrimeTime
Рет қаралды 55 М.
Did I Pick The Right Database???
1:07:48
Theo - t3․gg
Рет қаралды 207 М.
You still use Redux?
36:39
Theo - t3․gg
Рет қаралды 252 М.
If this ships, it will change javascript forever
25:54
Theo - t3․gg
Рет қаралды 194 М.
TS vs JSDoc | Prime Reacts
22:11
ThePrimeTime
Рет қаралды 90 М.
Teaching NextJS To Primeagen
1:19:51
Theo - t3․gg
Рет қаралды 233 М.
Dependency Injection | Prime Reacts
28:34
ThePrimeTime
Рет қаралды 304 М.
Easy Art with AR Drawing App - Step by step for Beginners
0:27
Melli Art School
Рет қаралды 8 МЛН
НЕ ПОКУПАЙ СМАРТФОН, ПОКА НЕ УЗНАЕШЬ ЭТО! Не ошибись с выбором…
15:23
Здесь упор в процессор
18:02
Рома, Просто Рома
Рет қаралды 200 М.