I Waited 15 Years For These New Array Methods

  Рет қаралды 220,352

Web Dev Simplified

Web Dev Simplified

Күн бұрын

JavaScript has lots of array methods for doing things like sorting and reversing arrays, but the biggest problem with all these methods is they mutate the array you are working with. This is a huge problem when you are trying to write React code, functional code, or pure functions. This is why I love the new array methods that add immutable versions of all the mutable array methods we are used to.
🌎 Find Me Here:
My Blog: blog.webdevsimplified.com
My Courses: courses.webdevsimplified.com
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/WebDevSimplified
CodePen: codepen.io/WebDevSimplified
⏱️ Timestamps:
00:00 - Introduction
00:36 - Immutability Explanation
02:45 - with Method
03:50 - toSorted Method
05:31 - toReveresed Method
06:00 - toSpliced Method
07:15 - Browser Support
#JSArrayMethods #WDS #Immutability

Пікірлер: 427
@ranvirchoudhary929
@ranvirchoudhary929 10 ай бұрын
Tip: spread syntax creates a shallow copy of the original object. use the structuredClone() function to make a deep copy of an object. structuredClone() has support in all major browsers!
@klirmio21
@klirmio21 10 ай бұрын
I am a beginner, can you please explain what do you imply by a shallow copy and deep copy? Shallow - meaning an object will be cloned but if it has nested children none of them will be cloned? And also, maybe some Usecases? where to use structuredClone()? thanks
@Thikondrius
@Thikondrius 10 ай бұрын
@@klirmio21 Basically if you use the spread operator on an array that contains nested object, the reference to these objects will remain intact, so when you are going to update the nested object in the copy, you are also going to modify the original nested object :s const a = [ "hi" , { hola : "senor" } ] const b = [...a] b[0] = "does not mutate original" b[1].hola = "this will mutate original" console.log(a) // [ "hi" , { hola: "this will mutate original" } ] As you can see the spread operator is not enough to ensure a copy that is completly "detached" from the orignal. But using structuredClone() , the copy won't have any reference to the original anymore. It basically will create the exact same object but a completly new one, with no relation with the original. const a = [ "hi" , { hola : "senor" } ] const b = structuredClone(a) b[0] = "does not mutate original" b[1].hola = "won't mutate the original either" console.log(a) // [ "hi" , { hola: "senor" } ]
@AmodeusR
@AmodeusR 9 ай бұрын
@@klirmio21 Better search in the internet because explaining and understanding such concept from a youtube's comment is a little bit difficult.
@klirmio21
@klirmio21 9 ай бұрын
@@AmodeusR Mister RL above did a flawless job at explaning it though!
@klirmio21
@klirmio21 9 ай бұрын
@@Thikondrius Bravo! Thank you very much my friend, I understood it well now. I will save your response in my knowledge base for future reference tytytytytytyty
@inasuma8180
@inasuma8180 9 ай бұрын
Great methods, I’m very happy about these. Something else to consider is making copies of arrays can also increase memory overhead where the original mutable methods wouldn’t. That said it’s negligible difference at execution time but it is a massive feasibility improvement!
@well.8395
@well.8395 9 ай бұрын
It's not negligible. Imagine doing that with an array of 10k elements, creating unnecessary copies.
@chriss5749
@chriss5749 9 ай бұрын
​@@well.8395 Thats why we have both options available. But most of the time u won't have 10k elements in one single array - and if it's the case, there is a good chance, an array isn't the right choice...
@well.8395
@well.8395 9 ай бұрын
@@chriss5749 Ah the "junior developer" saying. There's hundreds of valid applications that would need to display thousands or hundreds of thousands of elements in an array. For example, a photo editor, rendering pixels, rendering objects, logic of a game's occlusion culling, doing chart graphics, doing "Rich text editing", and the list goes on. You don't simply create copies everytime just because that code looks cleaner.
@stefanamende547
@stefanamende547 10 ай бұрын
Great video. Makes modifying react state arrays so much easier 👍
@LePhenixGD
@LePhenixGD 10 ай бұрын
Finally! It's such a relief to have non-mutating array methods Kudos to you Kyle for sharing this and DX as easy as possible I can't wait to implement these methods in my projects and experience the benefits firsthand. Thanks for sharing this awesome news!
@NathanHedglin
@NathanHedglin 10 ай бұрын
I can see many devs allocating SO much more memory just to mutate something.
@tarabario
@tarabario 10 ай бұрын
Thanks for the announcement and analysis of the new functionality!
@sanjarcode
@sanjarcode 10 ай бұрын
Love the "to" + "past tense", a consistent notation of out-of-place ops.
@christopheanfry2425
@christopheanfry2425 10 ай бұрын
Great content as usual!!! Very good new methods that make things easier and as you mentioned also more performance. 👍👍👍
@expertreviews1112
@expertreviews1112 9 ай бұрын
Gr8 and most comprehensive video on data normalisation
@PieJee1
@PieJee1 10 ай бұрын
I have always uses slice(0) to copy arrays not the spread operator. Even though this is because i have transpiled from ES6 to ES5 for a long time and slice() resulted in smaller code with ES5 code that a browser could optimize better too
@xXx-un3ie
@xXx-un3ie 9 ай бұрын
this is the better way of copying shallowly. don't use spread operator, it is 70+ times slower. also: you can jsut do arr.slice() without the 0. makes the code look nicer!
@AndrewTSq
@AndrewTSq 9 ай бұрын
Thanks for the headsup. Think this will be usable for my next project.
@theisoj
@theisoj 10 ай бұрын
Thanks Kyle as always! 👍
@SuboptimalEng
@SuboptimalEng 10 ай бұрын
Coding Interview Tip: When sorting an array of numbers, you need to do arr.sort((a, b) => a - b). Running arr.sort() will give you an incorrect result.
@aman_s_96
@aman_s_96 10 ай бұрын
Is it really a coding interview tip? Looks more like JavaScript fundamentals to me, which you learn in first few days itself.
@FlorianWendelborn
@FlorianWendelborn 10 ай бұрын
@@aman_s_96 I'm doing JS since over a decade and I've never encountered this. Only saw this fact recently in a random tweet. It's super unexpected behavior Tbf, in practice it's much more common to sort objects, and those need a sorting function anyway
@_Greenflag_
@_Greenflag_ 10 ай бұрын
Elementary, dear Watson !
@aminenadi693
@aminenadi693 10 ай бұрын
True, especially when there are negative numbers in the array.
@aman_s_96
@aman_s_96 10 ай бұрын
@@FlorianWendelborn That's really strange. Always seen it being mentioned in each & every course about JS.
@tejasshekar
@tejasshekar 10 ай бұрын
So are you saying that the with() method is doing some black magic behind the scenes that is not looping through the array and creating a new reference and then modifying it and returning it ? And is it not gonna impact performance? 🤔
@flamme8587
@flamme8587 9 ай бұрын
What about using a class Collection instead ?
@shahfaisal3923
@shahfaisal3923 9 ай бұрын
Thank you so much for sharing with us.
@fenilli
@fenilli 10 ай бұрын
Wouldn't those methods internally HAVE to make a copy of the original array to run those? as they are references to a memory unless a new one is created? so what performance improvements would it make? I can see it being a better DX, but performance wise can't see where it would shine.
@rea1m_
@rea1m_ 10 ай бұрын
you are right, under the hood it's the same thing.
@erichkitzmueller
@erichkitzmueller 9 ай бұрын
Not sure if toSorted() can be faster, but toReversed() and toSpliced() can definitely avoid creating a 1:1 copy first. They can directly create the desired result from the original array.
@PauxloE
@PauxloE 9 ай бұрын
Basically, in the first iteration of sorting, instead of shuffling elements around inside the array, it'll copy them (in a slightly more sorted way) to the new array, then continue on that. Saves a copy operation.
@erichkitzmueller
@erichkitzmueller 9 ай бұрын
@@PauxloE Well yes, I guess that depends on the sorting algorithm. I can see this working as described e.g. for quicksort. Less so e.g. for insertion sort.
@atombanker
@atombanker 10 ай бұрын
Thank you so mcuh share this kind of grateful content! I always appreciate from japan🇯🇵 いつもありがとうございます!
@Naej7
@Naej7 10 ай бұрын
いつも?Not どうも? I’m learning Japanese lol
@lukas.webdev
@lukas.webdev 10 ай бұрын
Very helpful! Thanks for sharing with the community. 😉🔥
@eduardoranierosilva
@eduardoranierosilva 10 ай бұрын
Not only that saves time on development, makes the code a lot more understandable during maintenance
@NathanHedglin
@NathanHedglin 10 ай бұрын
Also potentially uses a lot more memory.
@eduardoranierosilva
@eduardoranierosilva 10 ай бұрын
​@@NathanHedglin on the first or second scenario brought by Kyle you say that?
@HorstKirkPageKian
@HorstKirkPageKian 10 ай бұрын
Regarding the performance benefit of using these native methods: Is there a guarantee for that? For the performance benefit I mean. Who tells me that JS doesn't to two loops under the hood again, it could be just hidden from the developer.
@flywithoutwingss
@flywithoutwingss 10 ай бұрын
Correct... Who knows what is doing internally
@avelinecash
@avelinecash 10 ай бұрын
hey kyle! off topic but can you do a vid about the extensions you're using in VS code? thanks
@ukaszzbrozek6470
@ukaszzbrozek6470 10 ай бұрын
I would be really cautious when talking about performance like that. I don’t know how those new methods are implemented in the run time, but is a good chance that they are doing it exactly the same way we used to do it but on lower level.
@shakapaker
@shakapaker 10 ай бұрын
runtime*, on a lower level*
@twothreeoneoneseventwoonefour5
@twothreeoneoneseventwoonefour5 10 ай бұрын
@@shakapaker also "there is a good chance" instead of "is a good chance"
@stevenlischer
@stevenlischer 10 ай бұрын
Agreed, and microbenchmarks may be misleading because they don't show the disruption GC will cause
@ukaszzbrozek6470
@ukaszzbrozek6470 10 ай бұрын
@@shakapaker sorry 😅 English isn't my first language. I usually don't make so many mistakes.
@capeeshewebdesignanddevelo681
@capeeshewebdesignanddevelo681 10 ай бұрын
@@stevenlischer I wonder also, are those methods just syntatic sugarf that just do what usually is done by extending the prototype with a more declarative approach, thus making it yes more readable / mantainable but not more performant?
@kneekoo
@kneekoo 10 ай бұрын
I was there, Sally. 15 years ago!
@johnconnor9787
@johnconnor9787 10 ай бұрын
2:27 When we get the value of an array by index - the time complexity will be always O(1) no matter what aaray size we have
@mdzaidsiddiqui4262
@mdzaidsiddiqui4262 10 ай бұрын
Exactly! It doesn't matter if we're accessing arr[1] or arr[2588422]. I didn't understand why he said it.
@nurbolatsansyzbay9998
@nurbolatsansyzbay9998 10 ай бұрын
In order to have a new copy with only one change by index, we need to use spread operator(...people), which goes through all items in a list and adds it to a new list. It is O(n) time and it is what he was saying
@johnconnor9787
@johnconnor9787 10 ай бұрын
​@@nurbolatsansyzbay9998 2:17 - "second time". But this second time is actually O(1)
@QwDragon
@QwDragon 9 ай бұрын
@@mdzaidsiddiqui4262 he also sorts array in one looping (4:54).
@nurbolatsansyzbay9998
@nurbolatsansyzbay9998 9 ай бұрын
@@johnconnor9787 gotcha, agree 'second time' is O(1) not O(n)
@ChristianHeilmann
@ChristianHeilmann 9 ай бұрын
Just a hot tip: if you want to speed up your console.log() explanations, simply wrap what you want to log in curly braces. console.log({sorted}) will result in `{sorted: Array(3)}`
@toromanow
@toromanow 10 ай бұрын
How to find out which node version supports those features?
@krtirtho
@krtirtho 10 ай бұрын
It's a fairly simple change. A simple polyfill should cover the cross browser support
@talgy2671
@talgy2671 9 ай бұрын
Do I have to update javascript someway to use it in my electron app?
@srinuvanam4043
@srinuvanam4043 3 ай бұрын
How javascript object works and do properties(key) stores corresponding values and all the properties will be stored in the consecutive memory location?
@ilirbeqiri253
@ilirbeqiri253 10 ай бұрын
Thanks for the explanation. On top as always. What do you think about naming? "with" naming seems to be problematic to express what it actually really does. Same for "toSorted", maybe "immutableSort" would have been more descriptive. What is your opinion?
@fredoverflow
@fredoverflow 10 ай бұрын
"with" is an established convention in other languages, e.g. Kotlin data classes
@ilirbeqiri253
@ilirbeqiri253 10 ай бұрын
@@fredoverflow JS used to have their own conventions that we all liked, and with() is one of the functions that we always have been told to use sparingly and ignore most of the time.
@derfastimmerzustimmer8635
@derfastimmerzustimmer8635 10 ай бұрын
2:17 Why would you need to loop through the array a 2nd time to change a value by index?
@SilviuBurcea1
@SilviuBurcea1 10 ай бұрын
What should I use to have those array methods? ESNext?
@imadev2897
@imadev2897 10 ай бұрын
Amazing, I would like to see a video with your opinion about Map vs Object and Set vs Array usage 😊.
@yamiteru4376
@yamiteru4376 9 ай бұрын
Learn about algorithms and data structures and you'll know.
@Alek-nm6cx
@Alek-nm6cx 10 ай бұрын
Thanks Kyle, your the best
@JesseSlomowitz
@JesseSlomowitz 10 ай бұрын
Jack Herrington has a KZbin Short that shows the value of these immutable options for React with making to-do lists: kzbin.info7xHtGNVQktI
@meinlet5103
@meinlet5103 9 ай бұрын
does reducing code makes code faster in js? I think the implementation will be same as maunal copy & manipulation..
@rishichoubey5060
@rishichoubey5060 9 ай бұрын
Wow so easy to understand !
@aryangupta8756
@aryangupta8756 10 ай бұрын
method 3, what's the difference b/w .slice & .toSpliced?
@talkohavy
@talkohavy 8 ай бұрын
Hey, I have a serious question. How did you get notified about these methods coming out and being released? I also want to be like you, in the sense that i want to be up-to-date with new stuff coming out or getting updated. Is there a JavaScript newsletter that you're subscribed to? How did YOU first learn of these 4 new methods?
@_Greenflag_
@_Greenflag_ 10 ай бұрын
'It save on perfomance'. You don't know :) Did you test it ? Have you seen the signature of those functions ? They are maybe doing the same things you do 'manually'. Plus if you want something just implement it don't wait for it to come :)
@stewart6395
@stewart6395 9 ай бұрын
I had to update Chrome to the latest version to make these methods work. The time hasn't come yet to use these features, because people rarely update their browsers and there's a high risk of breaking your app for them. So it could be a year or so before we can use all this new stuff in production
@user-xm7yq1re2b
@user-xm7yq1re2b 9 ай бұрын
can you do a step by step tutorial building a ptc site with database ,user registration , ad serving page,admin panel and show how to connect everything across ?
@danielm1
@danielm1 10 ай бұрын
5:15 I think you meant to say it saves up on the copying part, but it will loop more than once because it has to keep looping until it's sorted. Although, even in the "less efficient" version, JIT compilation can be quite smart so maybe it's more efficient than we think.
@przemek896
@przemek896 10 ай бұрын
These methods creates deep copy or shallow copy ?
@ArifMatubber-km4nv
@ArifMatubber-km4nv 10 ай бұрын
Thank you so much
@tengun
@tengun 9 ай бұрын
Without any timing evidence, I don't think these new methods are more efficient than the old way. For example, if your loop does two actions, it would be the same as having 2 loops doing 1 action each (in terms of complexity). They are just useful in reducing code and increasing clarity.
@PauxloE
@PauxloE 9 ай бұрын
Don't forget the actions for increasing and comparing the counter.
@tengun
@tengun 9 ай бұрын
@@PauxloE i said "in terms of complexity"
@PauxloE
@PauxloE 9 ай бұрын
@@tengun In terms of complexity (i.e. ignoring constant factors), it's also the same as just having one loop doing just one action, too. But in reality, the factors also matter, especially when you are in the same complexity class.
@tengun
@tengun 9 ай бұрын
@@PauxloE *action here is in broad definition. It can be an expensive cpu computation, like sorting. In that case, the counter is hardly a problem.
@alisoylu4034
@alisoylu4034 10 ай бұрын
Great content. Thanks...
@hasankahya589
@hasankahya589 10 ай бұрын
Thank you 😊
@williamt.roberts4771
@williamt.roberts4771 8 ай бұрын
So, this with() is not recommended and is depreciated?
@SK-vg3mw
@SK-vg3mw 10 ай бұрын
Thank you!
@repeekyraidcero
@repeekyraidcero 10 ай бұрын
SO would love this post. I kinda prefer PHP to JS for Webtasks tho. JS is too easily deterred.
@a.9913
@a.9913 10 ай бұрын
What do you mean deterred?
@BackUp-cz6zn
@BackUp-cz6zn 10 ай бұрын
i like how mutable arrays are declared with "const"
@kneekoo
@kneekoo 10 ай бұрын
Yup, my giggle of the day too.
@chinmayghule8272
@chinmayghule8272 10 ай бұрын
The array elements are mutable, but the reference to the array is a constant.
@bhargavs5180
@bhargavs5180 10 ай бұрын
The reference is still immutable.
@BackUp-cz6zn
@BackUp-cz6zn 10 ай бұрын
@@chinmayghule8272 i know but it's funny to say "a mutable array is declared with "const" ".
@twothreeoneoneseventwoonefour5
@twothreeoneoneseventwoonefour5 10 ай бұрын
In Javascript you need to be VERY equal to be "equal", that's why you use === operator basically 100% of the times. But even then, you are not equal sometimes when you should be. In Javascript you need to be VERY constant to be "constant", that's why you use... Typescript with "as const" assertion operator. (it is "const arr = [1, 2, 3] as const;" if you are not familiar). But even then, you are not constant at runtime. We are doomed.
@aremu_smog
@aremu_smog 9 ай бұрын
These looks super interesting but aren't these syntactic sugar? If yes, I think the major benefits remains clean code and not necessarily performance.
@alexandersedeke
@alexandersedeke 10 ай бұрын
As always, an excellent video, with perfect and easy to understand summary. Thanks
@alexandersedeke
@alexandersedeke 10 ай бұрын
@yt accnt Think you got the wrong comment?
@RaubeR666
@RaubeR666 9 ай бұрын
With "lodash/fp" it was possible like 6 years ago already: `flow([set(2, "Nice"), sortBy(identity), reverse])(array)`.
@ShiloBuff
@ShiloBuff 9 ай бұрын
Cool, now there needs to be a built in method for deep merging objects both mutable and immutable. I couldn't find a "lightweight" library that could merge and mutate an object so I had to create a less than optimal route. There are libraries for deep merging but they seem to be for immutable. And i refuse to use a big library just for 1 method.
@antehll
@antehll 10 ай бұрын
I'm guessing performance is gonna suffer if you do lots of these functions, cloning for each of them, instead of mutating a single copy multiple times
@andsheterliak
@andsheterliak 10 ай бұрын
It seems so. So it's better to just modify the new array after making a copy with these methods. You can try this on your computer: const length = 1000000; const arr = new Array(length).fill('String'); // ------- for loop console.time('for loop'); const forLoopCopy = []; for (let i = 0; i < length; i++) { forLoopCopy.push(arr[i]); } forLoopCopy[length - 1] = 'End'; forLoopCopy[length - 2] = 'Pre End'; console.timeEnd('for loop'); // ------- spread console.time('spread'); const spreadCopy = [...arr]; spreadCopy[length - 1] = 'End'; spreadCopy[length - 2] = 'Pre End'; console.timeEnd('spread'); // ------- with console.time('with'); const withCopy = arr.with(-1, 'End'); withCopy.with(-2, 'Pre End'); console.timeEnd('with');
@uicornerwithJ
@uicornerwithJ 9 ай бұрын
Cool methods. thanks
@jacqueskloster4085
@jacqueskloster4085 9 ай бұрын
My daily observation is that array methods instead of loops are often a source for cascaded full table scans of unexperienced developers... To be honest, I try to avoid then whenever possible. Yet, there are absolutely valid use cases for them. But a concatenated find filter map some isnt one.
@elozinoovedhe
@elozinoovedhe 9 ай бұрын
Isn't toSpliced() the same as slice()?
@bilalarain4632
@bilalarain4632 9 ай бұрын
I think in this erra of unlimited memory and storage availability we should less worry about array mutability. rather a simple [...orignalArray].reverse would do the job and the best part for managing memory on your own is to assign [...originalArray] to a variable and then undefined or despose it later.
@nikilk
@nikilk 10 ай бұрын
This is Epic!
@nothenium
@nothenium 10 ай бұрын
Thank you Kyle, with your advice I have built a Discord clone ❤
@dileepa-mn2to
@dileepa-mn2to 9 ай бұрын
Bro can you make a video about atomica structure of the next project, how the data passing and state handeling throught the atomic componenets, thank you
@AbhishekSharma-fg1ho
@AbhishekSharma-fg1ho 6 ай бұрын
can we copy using slice 2:05
@tontonses7824
@tontonses7824 9 ай бұрын
You can't sort by just looping once. The perf improvement is not 2n vs n, but n(log n + 1) vs n log n. Negligible.
@SIVA-Mycount
@SIVA-Mycount 10 ай бұрын
One doubt. Do all the methods do a deep copy or a shallow copy ?
@savire.ergheiz
@savire.ergheiz 10 ай бұрын
Its basically syntax sugar. Its still do the copies operation it self 😂
@Naej7
@Naej7 10 ай бұрын
@@savire.ergheiz That does not answer the question.
@barneylaurance1865
@barneylaurance1865 10 ай бұрын
Shallow. From MDN: "JavaScript array-copy operations create shallow copies"
@alexm9104
@alexm9104 9 ай бұрын
@@barneylaurance1865 so... structuredClone() hello again. Or JSON.strngf/parse.
@me_rinta
@me_rinta 10 ай бұрын
Do these new methods do shallow or deep copy?
@sanjarcode
@sanjarcode 10 ай бұрын
The spread operator does shallow copy. And this is a notation feature meant to replace that, so I think it's shallow copy too.
@Abdallah_Ismail
@Abdallah_Ismail 10 ай бұрын
0:12 He can actually see the code guys! Sometimes I think he's a robot or some sort of an AI especially in his old videos like from 4 years ago O.O
@SebastianSastre
@SebastianSastre 9 ай бұрын
And Smalltalk had these and more since 70's
@HuynhLuong227
@HuynhLuong227 10 ай бұрын
Thank you🎉🎉🎉
@njox1635
@njox1635 10 ай бұрын
Insightful,but I have tried on Firefox but looks like some features aren't yet!
@wfl-junior
@wfl-junior 10 ай бұрын
These are awesome for the react ecosystem
@harshavardhans4374
@harshavardhans4374 9 ай бұрын
Instead of spread operator we can use structuredClone for a deep copy
@arshadsiddiqui9071
@arshadsiddiqui9071 10 ай бұрын
You look 23. Been waiting since you were 8 is pretty crazy.
@shantanusharma4901
@shantanusharma4901 10 ай бұрын
Perfect sir
@uthoshantm
@uthoshantm 10 ай бұрын
Well, toSorted() is not going to gain much in performance taking into account that copying is O(n) while sorting is O(n log n))
@atxorsatti
@atxorsatti 10 ай бұрын
Mathematically yes, practically we loop one time less. Idk it seems to be more of a convinance at the end.
@madsfrost9464
@madsfrost9464 10 ай бұрын
But what is the current support for this in browsers?
@barneylaurance1865
@barneylaurance1865 10 ай бұрын
Not sure, but I guess it should be possible to transpile it to something supported in whatever browsers you want to support.
@AbnerG787
@AbnerG787 10 ай бұрын
this works the same as structuredClone() but for arrays, right?
@mohammadbinfaisalal-khalif710
@mohammadbinfaisalal-khalif710 10 ай бұрын
Consider the following: const user1 = { name: "user1" }; const arr = [user1]; console.log(arr[0] === user1); // true const arrClone = structuredClone(arr); console.log(arrClone[0] === user1); false
@Naej7
@Naej7 10 ай бұрын
Yes
@2ndintelligentWorld
@2ndintelligentWorld 9 ай бұрын
amazing!
@TrungNguyenVan-ln7bp
@TrungNguyenVan-ln7bp 9 ай бұрын
that great bro
@Ultrajuiced
@Ultrajuiced 9 ай бұрын
I find your lack of semicolons disturbing. 😝 Interesting video, thanks for explaining! Learnt something. 👍
@willyhorizont8672
@willyhorizont8672 10 ай бұрын
good news!🎉
@user-ey5xw2nx9s
@user-ey5xw2nx9s 9 ай бұрын
OMG! So cool!
@upyrov
@upyrov 10 ай бұрын
what's the difference between slice and toSpliced methods?
@MichaelCampbell01
@MichaelCampbell01 10 ай бұрын
.slice only returns a section of the array, .splice (and .toSpliced) does 2 things, it removes elements from the array, and optionally adds others in their place.
@skipper3204
@skipper3204 10 ай бұрын
Thumbnail: what is the point of reversing an array if you sort it right after? 🧐
@TeKadGdn
@TeKadGdn 9 ай бұрын
good material. these new methods are syntatic sugar only and expand a number of methods without good reason
@riskitall7421
@riskitall7421 10 ай бұрын
Exercise caution when considering the opinions of influencers regarding performance matters; it is prudent to personally put their claims to the test. Many of these individuals create videos merely after perusing documentation, lacking the genuine hands-on experience requisite for their expansive discussions
@bpospanov
@bpospanov 9 ай бұрын
Why toReversed() didn't work?
@waynekmdigital
@waynekmdigital 10 ай бұрын
🎉Awesome
@kukulis100
@kukulis100 10 ай бұрын
The center idea is 'immutable' ?
@mohamed-zhioua
@mohamed-zhioua 10 ай бұрын
very helpfull
@MaverickDriver95
@MaverickDriver95 10 ай бұрын
Can someone make some js benchmarks on this? It feels very superficial
@andsheterliak
@andsheterliak 10 ай бұрын
I believe these new methods are more for convenience than performance. You can try this simple test for the "with" method on your computer: const length = 1000000; const arr = new Array(length).fill('String'); // ------- for loop console.time('for loop'); const forLoopCopy = []; for (let i = 0; i < length; i++) { forLoopCopy.push(arr[i]); } forLoopCopy[length - 1] = 'End'; console.timeEnd('for loop'); // ------- spread console.time('spread'); const spreadCopy = [...arr]; spreadCopy[length - 1] = 'End'; console.timeEnd('spread'); // ------- with console.time('with'); arr.with(-1, 'End'); console.timeEnd('with');
@twothreeoneoneseventwoonefour5
@twothreeoneoneseventwoonefour5 10 ай бұрын
​@@andsheterliak (on my pc, Ryzen 5 5625u, 16gb ram) it seems like under load spread is the slowest one (if you do multiple passes of the same test after one another), with 140ms. If it is only a single run though, spread and with have the same performance, 30-35ms. For is the fastest with 18-20ms.
@zkksch
@zkksch 10 ай бұрын
Names of those methods are a bit confusing. They at least should be consinstent and use with in all methods name (withSorted withReversed etc.) but even better explicitly say what they do: copyWith, copySorted etc. Also is there an optimization to not create new array for each method if they were used in chain? Iterators approach (like in python) allows you to do it: you're creating chain of iterators, and finalize resulting iterator only when you actually need a copy, so only one copy will be created (if there is no "helping copies" inside those iterators) no matter how many modifications you've used.
@invisi1407
@invisi1407 9 ай бұрын
withSorted() sounds weird - toSorted() or toArray() or toString() or similar is usually the right naming for these methods - they return something new in a different way. They don't do it _with_ anything.
@johnstone7092
@johnstone7092 10 ай бұрын
How do i use theese methods : ( im noob and vsc dosent recognise them
@harag9
@harag9 10 ай бұрын
Best to learn the basics first and play around with normal arrays doing the way everyone else does it rather than waiting for browsers to update.
@johnstone7092
@johnstone7092 10 ай бұрын
@@harag9 I already know how to do that, not that noob : ) Im just wondering how to use the latest.
@gopallohar5534
@gopallohar5534 10 ай бұрын
After watching so many of your videos, the only question comes to my mind Who is Sally?😂
@njox1635
@njox1635 10 ай бұрын
LoL 😂
@belvederepapi7495
@belvederepapi7495 8 ай бұрын
very nice
@cherubin7th
@cherubin7th 6 ай бұрын
Great, even more you need to remember if you want to be able to read JavaScript. Just so that 5 people can type one line less per project.
@stevenlischer
@stevenlischer 10 ай бұрын
Be careful using these. Make sure your problem must be immutable. Memory allocation and garbage collection in JavaScript is not free and using these methods with large arrays or using them within a loop will kill performance compared to a mutable solution
@capeeshewebdesignanddevelo681
@capeeshewebdesignanddevelo681 10 ай бұрын
Exactly, I was going to say not always we want immutable version of arrays for the sake of having pure testable functions, sometimes, unforutunately a mutable version, when operating on the 100k+ order is preffered
@dimitritarasenko9960
@dimitritarasenko9960 10 ай бұрын
Who are you performance and memory management guys? Are you students or something like professor without any real experience? I see this sort of ppl only in comments. All real life projects I have ever seen before give a f* about this kind of performance issues. What are you doing frontend side with 100k length arrays? Are you these guys who have a Fibonacci calc on each project? Wtf?
@stevenlischer
@stevenlischer 10 ай бұрын
@@dimitritarasenko9960 Many front end devs might not need to be concerned about this. They'll never implement a dynamic search for a large directory of data, or work on a shop with thousands of purchasable items, or make a chat system, or work on a demanding web game, etc etc. Most backend devs do care about these things though because it is much more common to run into performance/memory problems from iterating large data structures there.
@codesymphony
@codesymphony 10 ай бұрын
But why would they use these versions if they're fine with mutating the original array
@stevenlischer
@stevenlischer 10 ай бұрын
@@codesymphony a cornerstone of functional programming is "pure" functions that don't mutate arrays/objects but instead return completely new objects and arrays. Sometimes pure functions are handy and keep code easier to reason about and debug, but too often pure functions are presented as being the best or preferred way and there is no critical analysis of the consequences. So new devs seeing this video may wonder which functions they should use and no context has been provided to help them decide which makes the most sense for their application.
@moonyyy9093
@moonyyy9093 9 ай бұрын
Great new methods, but the problem for now is the browsers support.
20+ Must Know Array Methods That Almost Nobody Knows
11:47
Web Dev Simplified
Рет қаралды 85 М.
State Managers Are Making Your Code Worse In React
13:33
Web Dev Simplified
Рет қаралды 95 М.
Что будет с моей рукой?😨
01:00
Аришнев
Рет қаралды 2,8 МЛН
All useEffect Mistakes Every Junior React Developer Makes
22:23
javascript - What is the difference between "let" and "var"?
1:44
NEW React 19 Changes Are Amazing!
8:42
Web Dev Simplified
Рет қаралды 145 М.
5 Must Know JavaScript Features That Almost Nobody Knows
18:06
Web Dev Simplified
Рет қаралды 470 М.
Speed Up Your React Apps With Code Splitting
16:50
Web Dev Simplified
Рет қаралды 353 М.
8 Must Know JavaScript Array Methods
10:05
Web Dev Simplified
Рет қаралды 1 МЛН
CSS Anchor Is The Best New CSS Feature Since Flexbox
15:39
Web Dev Simplified
Рет қаралды 343 М.