r/learnjavascript • u/elediardo • Sep 01 '22
Three ways to append an item to an array (Mutative)
10
u/senocular Sep 01 '22
In this case, we're adding "Cow" at the end of the array by using
myArray.lengthas our index (which is 2)...
myArray.length here is 1 ;)
let myArray = new Array();
myArray.push("Cat");
console.log(myArray.length); // 18
u/monkiebars Sep 02 '22
What possible reason would you have for not just using Push?
-1
u/TranquilDev Sep 02 '22
I'm not familiar with the time complexity of the various solutions but that would be the case in which you wouldn't use push - if possible. If there's a more efficient solution and your working with a large amount of data that requires it.
4
Sep 02 '22
They all have the same time complexity. Also, JavaScript arrays are dynamic, so pushing into the array has an amortized time complexity of O(1), aka as cheap as it can realistically be.
12
u/b4ux1t3 Sep 01 '22
The last is a bad practice, because of reasons. (async, e.g.)
The middle one is more for splicing multiple arrays together.
Really, the only "correct" way is the first one.
Still, good explanation of the tools available!
2
u/Makemeacyborg Sep 01 '22
Are you saying that assignment into a index is async?
4
u/b4ux1t3 Sep 01 '22
No, I'm saying that you could be using an array in an asynchronous operation, and something else could change it.
Mind you, I don't think that's how it ends up working out in JavaScript.
However, I don't know for sure. What I do know is that, in other languages, you have to be very careful with sharing data in async code, because you might be dealing with stale or invalid data.
Hence, if I'm going to add something to a list (which JavaScript arrays are), I'm going to make sure I use the method that, at least on the face of it, will put my element at the end of the array, regardless of the size.
1
u/TwiNighty Sep 02 '22
No, I'm saying that you could be using an array in an asynchronous operation, and something else could change it.
Mind you, I don't think that's how it ends up working out in JavaScript.
No I think you are absolutely correct. It suffers from the same problem as
counter += await promise1
Sep 02 '22
[removed] — view removed comment
-2
u/b4ux1t3 Sep 02 '22 edited Sep 02 '22
My bad, I assumed for a second that people, eventually, step foot outside of JavaScript land.
I forgot that there are people who only ever spend their time working in one specific environment and, as such, can completely ignore the best practices and anti-patterns of other languages, simply because their environment doesn't succumb to them.
I'm sorry you couldn't piece together what I was trying to say, let me break it down for you:
A list is a data structure which can store an arbitrary and mutable number of elements.
JavaScript arrays demonstrate this behavior, and very well at that.
pushwill, regardless of the length of an array, stick an element at the end of an array.If you, for example, store the length of an array ("caching" that value for later use) , run a method which mutates that array by adding one or more elements to it, and then try to use the stored length to index said array, you're going to overwrite data.
"Caching" properties is a very common practice to cull a few cycles here and there from code execution. It's not hard to see where this practice could lead to problems when coupled with the third method listed in the OP.
Snide comments aside, it's still best practice to use
pushfor this use case, whether or not you agree with my (polyglot) reasoning.Demonstrate otherwise, and I'll change my tune.
Or, you know, just stop being a pernicious douche on a subreddit about learning a programming language.
2
u/StoneCypher Sep 02 '22
My bad, I assumed for a second that people, eventually, step foot outside of JavaScript land.
Giving Javascript advice in
learnjavascriptthat's wrong for Javascript, and then saying "oh well it's right in other languages," is hilarious, and allYou'll find that you're not able to find a single specific language in which this advice was correct, though. There are only about a dozen languages with this keyword, and they all use it for serial awaiting.
These keywords are not used for parallelism in any language, and parallelism is the thing you are trying to discuss (in hilariously junior ways.)
But since you said "I assumed for a second that people, eventually, step foot outside of JavaScript land," I'll cede the possibility that I might be missing something.
In which specific language do you imagine spreading and unspreading an array will cause a parallelism problem in non-threaded code, please?
There aren't many languages that have spread in the first place, so I'm sure you'll be able to explain which language you were talking about neatly and easily.
I'm sorry you couldn't piece together what I was trying to say
I could; it was just incorrect.
"Caching" properties is a very common practice
This is completely unrelated to the discussion at hand.
Demonstrate otherwise, and I'll change my tune.
I rather doubt it.
Snide comments aside, it's still best practice to use push for this use case
I never said otherwise. What I said was wrong was your attempt to spread a container and reassemble it, and it was for a lot of reasons, such as:
Many values won't be copied correctly
You're completing two entire unnecessary iterations at the whole length of the array
You're losing pre-size copy
You're spending the entire memory of the array a second time unnecessarily
You've invoked a copy for every single value in the array, unnecessarily
The fact that you made something up about parallelism in a language that doesn't have parallelism in order to attempt to salvage your appearance of expertise, then a second time tried diving into other languages without even naming one? Just icing.
I also didn't say anything snide. My mockery was direct.
I did also explain why the phrase
best practicedoesn't belong here. That doesn't mean "the right way to do it." You seem to have decided to continue, however.
Or, you know, just stop being a pernicious douche
Pernicious means "causing slow and subtle harm over a long time period." You know, like a poison, or a broken bone, or a bad law.
I'm not sure how you would imagine that would ever map to a Reddit comment, or a Redditor.
2
u/highangler Sep 22 '22
I learned more in these two comments than I did the entire time learning Js. Don’t be a shitty know it all because, there’s people out there(don’t know if you’re senior or what you title yourself) that are so much better at what they do than you. If you were my boss I’d probably be too ashamed to return to work.
1
u/StoneCypher Sep 22 '22
If you were my boss I’d probably be too ashamed to return to work.
Honestly, if I was this person's boss, they would have been sitting in a culture where programmers talk to each other, ask questions, say "my opinion is," offer suggestions, take criticism with thanks, and so on
This person is doing this because they've never been in a supportive team. They learned from the internet, which is a combat arena, where you "win" by "defeating" someone else with jokes or anger or evidence.
If I was their boss, they'd have seen a healthy group behaving differently, and I don't think they'd have said it at all, in the first place.
But also, if they did, I'd try to make a safe landing space for them to come in, say "I'm sorry and I learned something," and receive a second chance.
Everyone makes mistakes. Some people, including me, make mistakes a lot.
Letting people try again is how they adjust towards better.
I appreciate your kind words towards me.
1
u/toastertop Sep 02 '22
push will, regardless of the length of an array, stick an element at the end of an array.
Not true, Array's support up to an unsigned 32-bit integer of 4.29 billion records. Memory would be off the charts by then anyways but just saying.
1
u/highangler Sep 22 '22
Couldn’t you just use .join() in that case if you wanted to combine two arrays?
2
u/b4ux1t3 Sep 22 '22 edited Sep 22 '22
If that's all you need to do, yeah. But say I want to include only those elements that I filter out, or the result of any other non-trivial operation.
Sure I could run a filter on the array, and then join the result, but that's allocating a whole new array for the purposes of sticking it at the end of another. I'd generally favor adding the correct elements directly, minimizing the memory overhead.
But then, I'm an old hand and I'm coming from languages where that sort of thing generally matters. It doesn't matter quite so much in most contexts in JavaScript.
1
u/StoneCypher Sep 02 '22
The last is a bad practice, because of reasons. (async, e.g.)
😂 What is this even supposed to mean?
3
u/OutOfTheForLoop Sep 02 '22
What’s the difference between:
let myArray = new Array()
and
let myArray = []
4
u/-FAnonyMOUS Sep 02 '22
it's like initializing a string variable with
let myVar: string = ''; vs let myVar: String = new String('');both might seem the same but the former uses the primitive string type while the other creates an object of String construct.
1
u/OutOfTheForLoop Sep 03 '22
Ok, great! Now, what’s the difference between declaring a primitive string type and an object of Strong construct?
Edit: someone earlier informed me that by creating an array construct I was afforded a parameter that allowed me to declare the initial size of the array, but that doesn’t seem very important with JS. (Before you criticize my lack of deep understanding, please take my username into consideration, hahahaa)
2
5
2
2
Sep 02 '22
Don't mind me. I'm gonna take ... Yeah. I gonna just take a nice little copy of this. Umm, for a friend of mine. Who might need this later. Maybe.
1
1
u/Rguttersohn Sep 02 '22
The third one is pretty clever. Took me a second to figure out how that would work.
1
u/Cahnis Sep 01 '22
is there a situation where it is desirable to mutate?
From what I gathered so far I avoid it like the plague
8
37
u/dee_jay_mon Sep 01 '22
myArray = [...myArray, 'Pig'] :)