In my previous post I mentioned Iād been practicing problem-solving by handwriting answers. It's taking much longer than on an IDE or cargo-program...
For further actions, you may consider blocking this person and/or reporting abuse
Good points! You could iterate through a string directly though with a for loop, accessing the character at each index!
As a rule I see
charAt
/charCodeAt
/length
for strings as useful optimisations in well-curated performance code and anti-patterns in typical code.They are great if you know what's in the string (i.e. you made it or "sanitised" it to take all the interesting bits out), but can get you in trouble for arbitrary user input where at some stage some fool is going to try out some fancier unicode.
charAt
works nicely in the usual case:But get's funky when multi-char graphemes exist:
(see speakingjs.com/es5/ch24.html for a bit of background)
This is a really good point! Multi-character glyphs do mess with string iteration whether you split, spread, or loop. Trying to remember my solution to this the last time I encountered it in practice. I may have used a library to convert the strings to multi character arrays...
Omg I have not thought of this either. Multi-char graphemes really mess with my head
Wow yesss! I didn't think to!
const newArr = arr.slice()
Is my favourite way to clone an array
woah woah woah! Does it clone past 1 level deep?
jsperf.com/cloning-arrays/38
forEach
doesn't mutate an array. Mutation happens only if you explicitly mutate array items in iteration function.I guess if you're using forEach like map you could say it mutates
Well, actually if we execute your examples, we can notice that
forEach
doesn't mutate the original array.Thanks for pointing that out. This seems like a gray area. I don't know how I got under the impression that
forEach
mutates the original array items, maybe it was this post I looked up as I was writing the post. It's not entirely clear to me whatforEach
actually returns if I ran it on an array its own.I have around the web read general opinions that
forEach
iterates straight through arrays without breaking, and skips empty values, so that if one wanted to include a condition it would be easier to go with a for-loop. I don't have enough experience withforEach
to tell, tbhTo address your point "what forEach actually returns", the answer is "nothing".
forEach
does not return a value, it is a void function.Thank you! That makes a lot of sense.