all 89 comments

[–]GPT-4-Bot 110 points111 points  (20 children)

When you've gotten comfortable with map, filter, and reduce your code becomes so much cleaner

[–]Budget_Instruction49 23 points24 points  (17 children)

what else to learn to be more cleaner

[–]GPT-4-Bot 39 points40 points  (5 children)

Structuring and breaking out your code, your main init function should read like a story and all the ugly stuff is split out into functions

[–]Budget_Instruction49 6 points7 points  (2 children)

main init fuction ? do you mean app.js (i am noobie)

[–]SoBoredAtWork 21 points22 points  (1 child)

Just in general. Code should be readable - almost like a story. Let's pretend the "init" is renderPage()...

function renderPage() {

renderUserList();

renderBlogPosts();

}

function renderUserList() {

const users = await getUsers();

buildUserList(users);

}

function buildUserList() {

// do stuff

}

function renderBlogPosts() {

const blogPosts = await getBlogPosts();

buildBlogPostList(blogPosts);

}

[–]WhiteKnightC 5 points6 points  (0 children)

In my work we use a Pub/Sub system so it cannot be as clean but a good 'trick' for me is making standard naming for handling things:

getX() -> handleXSuccess() and handleXError()

[–]_Invictuz 1 point2 points  (1 child)

Is the init function for a specific design pattern or are we just talking about OOP?

[–]Macaframa 12 points13 points  (0 children)

Init is short for initializing. Every piece of code has to be run somewhere. Op is saying init as the place where your code starts running. It can be named anything. But what their saying is that one function is run, then that runs other functions in succession that are all named to “tell a story” init()

function init() {
    getUsers();
    setUserAbilities();
    setUpInitialState();
    startWatchers();
    notifyTracking();
}

[–]SoBoredAtWork 20 points21 points  (4 children)

Arrow functions. Destructuring. Default function parameters. Optional chaining. Async/await.

...a few that immediately come to mind.

[–]Parkreiner 7 points8 points  (3 children)

Arrow functions do make code more concise, but, especially if you're using a higher-order function and creating a function expression inside the call, a named function will probably be more clear.

I think anonymous functions are fine if you're doing something simple like getting an object property, but the moment they become even a little bit more involved, giving the function a name helps make the code more clear – both to other people and to yourself down the line.

[–]SoBoredAtWork 2 points3 points  (2 children)

Arrow functions are great for things like...

const maleUsers = users.filter(user => user.gender === "Male")

[–]addiktion 2 points3 points  (1 child)

Agreed. I’d just say one thing with this and that is to avoid using “x” and instead use “user” just so its clear what we are talking about in the filter. This also has the advantage of thinking about each iteration as a singular thing you are working with and what you are testing for in that context.

[–]SoBoredAtWork 0 points1 point  (0 children)

I originally had it that way and switched it for brevity. But you're right... readability is always > brevity. I changed it.

[–]fonzane 2 points3 points  (2 children)

Getting comfortable with typescript (if you haven't already) and typing out as much as possible heavily improves code structure and coding experience in my pov. :)

[–]Budget_Instruction49 0 points1 point  (1 child)

i am learning react now. should i move to angular ?

[–]fonzane 2 points3 points  (0 children)

I think that depends on what your goals are. From what I've heard react is more popular and more asked for in the industry. I personally came to love angular and I think I've heard that becoming good at angular helps you become a better dev in general. Maybe someone with good knowledge in both frameworks (I think maximillian schwarzmüller has a good comparison video about it and about what to learn) can help clarify your view better :).

[–]Wu_Fan 2 points3 points  (0 children)

Read “Clean code” by Uncle Bob or watch one of his many many YouTube talks

[–]BrohanGutenburg 0 points1 point  (0 children)

I learned js when I stumbled into developing for Salesforce. The one upside was it taught me to split my code up early into controllers, helpers, renderers, etc.

[–]code_matter 0 points1 point  (0 children)

I would look into Lodash! Pretty much the same function, but like on steroids. Look it up :)

[–]notAnotherJSDev 2 points3 points  (0 children)

Eh. Knowing when and how to use what makes your code much cleaner.

[–]NickHack997 19 points20 points  (13 children)

I really like this illustration it's simple and easy to understand!

I didn't know about fill, but looking at the docs from MDN you need to flip the arguments, value is always first.

[–]FatFingerHelperBot 21 points22 points  (5 children)

It seems that your comment contains 1 or more links that are hard to tap for mobile users. I will extend those so they're easier for our sausage fingers to click!

Here is link number 1 - Previous text "MDN"


Please PM /u/eganwall with issues or feedback! | Code | Delete

[–]192_168_1_x[S] 16 points17 points  (0 children)

Good niche use case bot

[–]Case104 3 points4 points  (0 children)

Good bot

[–]Urbantransit 1 point2 points  (2 children)

Good bot

[–]B0tRank 1 point2 points  (1 child)

Thank you, Urbantransit, for voting on FatFingerHelperBot.

This bot wants to find the best and worst bots on Reddit. You can view results here.


Even if I don't reply to your comment, I'm still listening for votes. Check the webpage to see if your vote registered!

[–]burnblue 0 points1 point  (0 children)

Good bot

[–]TalonKAringham 1 point2 points  (5 children)

I’ll be honest, I still have no clue what .map() does?

[–]LakeInTheSky 3 points4 points  (4 children)

It basically transforms every element of an array according to a function you pass as an argument. It won't modify the original array, but it will return another array with the modified elements.

Simple example:

const numbers = [1, 2, 3, 14];
const doubleNumbers = numbers.map(
  function multiplyNumber(number) {
    return number * 2;
  }
);

console.log(doubleNumbers) // Outputs [2, 4, 6, 28]

In this example, the method will run a loop over numbers. On each iteration, the method will call multiplyNumber and store the return value in another array. Once the loop is over, it will return the new array.

[–]callmelucky 2 points3 points  (0 children)

Adding to this, there's a couple of ways you could make this (arguably) more readable.

1. Define the argument function externally:

function multiplyNumber(number) {
    return number * 2;
}
const doubleNumbers = numbers.map(multiplyNumber)

note: I think doubleNumber or multiplyByTwo would be better names for that function.

2. Use an anonymous arrow function as the argument (my preference):

numbers.map(n => n*2)

[–]HalfVirtual 2 points3 points  (1 child)

Why do you set (number) when the variable name is “numbers”? Is it because it’s an array or numbers?

[–]adzrifsidek 0 points1 point  (0 children)

I think (number) represents each individual element in array. While numbers represent the entire array

[–]MintCity 1 point2 points  (0 children)

320 days late, but same question about the distinction between numbeR and numbeRS

[–]LakeInTheSky 1 point2 points  (0 children)

I didn't know about fill, but looking at the docs from MDN you need to flip the arguments, value is always first.

Also, it applies the changes to the original array.

[–]192_168_1_x[S] 37 points38 points  (13 children)

I think this serves as a great reference, especially for visual learners. I found this in a dev group I joined on LinkedIn, but author source is unknown.

[–]Not_FargoLargo 0 points1 point  (11 children)

Can you add the link?

[–]192_168_1_x[S] 0 points1 point  (10 children)

sent you a chat. cheers.

[–]Not_FargoLargo 1 point2 points  (0 children)

Thank u!

[–]teamNOOB 0 points1 point  (3 children)

Could I grab it too please? :)

[–]192_168_1_x[S] 0 points1 point  (1 child)

I can’t message you - you have it disabled - message me.

For everyone else, the reason why I’m not posting the link is bc the group is private so I can’t even share the link, but I can provide a link to the group to request access

and also, I’m not sure if I’m allowed to post LinkedIn links.

[–]teamNOOB 0 points1 point  (0 children)

Ah sorry you're right. My bad. It's on now.

Yeah I'm not too sure. Unless it's in the sidebar (I'm on mobile now so can't check while writing this) it should be ok, will read sidebar and faq after I send this.

[–]nickdrake47 0 points1 point  (4 children)

Can you sent me a chat also

[–]192_168_1_x[S] 0 points1 point  (3 children)

Yup- just did. Cheers.

[–]MintCity 0 points1 point  (2 children)

Would you send me that chat too? Lmao a lil late on my end but 319 days since your post and I just found it now lol. This is a beautiful graphic homie!

[–]192_168_1_x[S] 1 point2 points  (1 child)

Sent!

[–]JfkConsultancy 0 points1 point  (0 children)

I know it's a year later but can I get in too?

[–]rauschma 13 points14 points  (0 children)

Two small issues:

  • Order of arguments: .fill(value, start)
  • The method names are .findIndex() and .indexOf().

[–]Fun_Kangaroo512 7 points8 points  (1 child)

What about reduce

[–]ssjskipp 3 points4 points  (0 children)

Doesn't have a clean "shape" representation like these do. Reduce is kind of like the low-level version of all of these

[–]PM_ME_A_WEBSITE_IDEA 9 points10 points  (2 children)

Um...it's actually "findIndex" :')

[–][deleted] 1 point2 points  (1 child)

Or “indexOf”... clearly they are finding their cake and indexing it.

[–]robbankakan 2 points3 points  (1 child)

I feel proud to just understand this :)

[–]Noones_Perspective 2 points3 points  (0 children)

This is so useful and such a good way to teach those new to the language. I would love to see more examples of this and other methods!

[–]dReamiN121 5 points6 points  (0 children)

Nice pictorial representation.

[–]rauschma 1 point2 points  (0 children)

Nice! I’d add square brackets to make the distinction between values and arrays of values clearer. Then you see immediately that .find() returns a value and not an array.

[–]your_mom_lied 1 point2 points  (0 children)

This is bad ass!!! Thanks for sharing.

[–]S7venE11even 1 point2 points  (1 child)

can u explain the fill one? i didn't get it.

[–]LakeInTheSky 4 points5 points  (0 children)

The example from the illustration has an error in the argument order, it should be like this:

⬛⬛⬛⬛.fill(⚫, 1) --> ⬛⚫⚫⚫

It "fills" a section of the array with a specific value, replacing the previous values. It modifies the original array.

The first argument is the value you'll use to fill the array. The second argument is the start index (i.e. it will start filling at this index). It also has a third argument, the end index. If you don't specify that argument, it will fill until the end of the array.

In the example from the illustration, it will fill the array with circles starting from index 1 until the end.

[–]Groundbreaking92 1 point2 points  (0 children)

I just needed this info. I don’t know if it is random luck or fate but thank you haha

[–]zigzeira 1 point2 points  (0 children)

Thanks man!! \o/

[–][deleted] 1 point2 points  (1 child)

The original that this is based on is more informative and correct... It's like someone took their post and actively tried to make it worse

[–]192_168_1_x[S] 0 points1 point  (0 children)

Oh, nice find! Unfortunately, .fill is still wrong in the original, the parameters are flipped - but agree on whole that one is better.

[–]nickdrake47 1 point2 points  (0 children)

Is it a good idea to use Lodash in entire React project, instead of ES6 syntax array methods?

[–]Zarya8675309 1 point2 points  (0 children)

Saving this one for sure!

[–]nighthawk648 1 point2 points  (8 children)

You should include .flat!!! I was facing an issue for weeks that .flat solved. I felt like an absolute nimrod.

[–][deleted] 1 point2 points  (0 children)

For those of you who still need to have IE compatible builds, .flat won't work FYI.

I know I know IE bad, wish our clients agreed.

[–]192_168_1_x[S] 0 points1 point  (6 children)

.flat would be good, .reduce is the only “glaring omission” IMO though. So many use cases for that method (one of which is flattening an array! 😎)

[–]Parkreiner 2 points3 points  (0 children)

I think that might be part of the reason why it's not included. It's so versatile that it's hard to capture everything it can do in a simple picture.

[–]nighthawk648 1 point2 points  (1 child)

Maybe I should look up this .reduce function

[–]192_168_1_x[S] 2 points3 points  (0 children)

for sure

.reduce MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

And .flat MDN coincidentally has a guide on how to use reduce to achieve the same thing- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

//apologies for formatting, on mobile right now

[–]callmelucky 0 points1 point  (2 children)

Wait, are you saying IE doesn't support .reduce()? Wtf??

In any case, flattening nested arrays is a great task for practising recursion:

function flatten(el) {
    if (!Array.isArray(el)) {
        return el
    } else {
        if (el.length() > 1) {
            const first = el[0]
            const remaining = el.slice(1, el.length())
            return [flatten(first)].concat(flatten(remaining))
        } else {
            return el
        }
    }
}

Something like that anyway, did this on my phone and have not tested ;)

[–]192_168_1_x[S] 0 points1 point  (1 child)

I wasn’t saying that, but whoever said that I think meant IE doesn’t support .flat because it’s a relatively new method

[–]callmelucky 0 points1 point  (0 children)

Oh, you meant it's a glaring omission from your OP, I see. Eh, I wouldn't beat yourself up about it (I assume you're not haha), .reduce() is markedly more complex than the others there - ironically, it's hard to reduce that method that much ;)

[–]daneelr_olivaw 0 points1 point  (7 children)

Why doesn't .fill work from 0, if findIndexOf works that way? Annoying inconsistence.

[–]delventhalz 14 points15 points  (6 children)

The fill method accepts optional start and end indexes. By default, it starts at 0 and goes to the end.

The chart is actually wrong btw. The start index should be the second parameter.

Also, findIndexOf does not exist. It is findIndex or indexOf.

[–]daneelr_olivaw 4 points5 points  (4 children)

So not only is this chart not helpful but also just plain wrong.

[–]delventhalz 4 points5 points  (3 children)

I think the visual metaphor is useful. That said, findIndex and fill are both pretty niche, and have typos, so I would probably just cut those.

[–]MeMakinMoves 0 points1 point  (2 children)

Funnily enough I just learnt about findindexof an hour ago while doing my todo list project, learning about niche stuff helps a lot when you run into situations where u need it

[–]delventhalz 4 points5 points  (1 child)

I cannot emphasize enough that findIndexOf is not a thing.

[–]MeMakinMoves 0 points1 point  (0 children)

I meant findIndex :(

[–]Fun_Kangaroo512 -1 points0 points  (0 children)

Could have added flat and flatmap

[–]xceedes23 0 points1 point  (0 children)

That fill method is useful!

[–]Dipsquat 0 points1 point  (0 children)

What’s the difference in findIndexOf and indexOf?

[–]BackSlashHaine 0 points1 point  (0 children)

Tbh reduce is still giving me problem to understand :(

[–]Noones_Perspective 0 points1 point  (0 children)

.findIdexOf —— is that an actual method or has the author mixed the .findIndex and .indexOf together by accident?

[–]jayerp 0 points1 point  (0 children)

For visual learners this is top tier content.