r/javascript • • Dec 27 '18

help What differences do you see in novice javascript code vs professional javascript code?

I can code things using Javascript, but the more I learn about the language, the more I feel I'm not using it properly. This was especially made apparent after I watched Douglas Crockford's lecture "Javascript: The good parts." I want to take my abilities to the next level, but I'm not really sure where to start, so I was hoping people could list things they constantly see programmers improperly do in JS and what they should be doing instead.. or things that they always see people get wrong in interviews. Most of the info I've learned came from w3schools, which gives a decent intro to the language, but doesn't really get into the details about the various traps the language has. If you have any good book recommendations, that would be appreciated as well.

320 Upvotes

305 comments sorted by

262

u/ForScale Dec 27 '18

Bad naming.

Not keeping things DRY.

Massive functions that do many things.

Not caching static values but instead querying them over and over again.

133

u/cynicaloctopus Dec 27 '18

I agree with everything except the last point. It can be tempting to pre-optimize, but caches tend to be bug farms. Instead focus on getting performance data, then act on that if you need to.

50

u/robotmayo Dec 27 '18

They might mean doing object.value or function(sameValue) 10x instead of just storing it into a variable. Is it optimization? Yes. But its easy and free so why not.

55

u/brtt3000 Dec 27 '18

You see this a lot in bad jQuery or DOM querySelector code, where instead of assigning the result of the query to a variable and reuse that for different operations they keep querying the same thing over and over.

18

u/ForScale Dec 28 '18

Precisely what I was referring to.

20

u/tr14l Dec 27 '18

Bad jQuery? There's good jQuery? :P

12

u/brtt3000 Dec 28 '18

Sure, it is a just a tool to manipulate DOM.

2

u/CrimsonXFrost Dec 28 '18

I try not to write jQuery, but when I do, I make a mess of it. I’ve been doing this 15 years, and jQuery is still tough to get right the first time.

→ More replies (1)

1

u/MonkeyNin Dec 28 '18

In jQuery itself, or in code of people using jQuery?

1

u/[deleted] Dec 28 '18

People using it.

Its just that a lot of people will do $('.my-class') every time they need to do something to the .my-class element and then jQuery does a new lookup every time when they should have just set a variable with the element like let $myClass = $('.my-class') and used that over and over. (I use the $ prefix just as a convention so I remember its a jQuery variable).

→ More replies (1)

9

u/cm_yoder Dec 27 '18

DRY??

52

u/mindonshuffle Dec 27 '18

Not sure if sarcasm, but "Don't Repeat Yourself." Basically, if there's code you're repeating more than couple times in different places, you should probably refactor that into a named variable or function you can call.

24

u/djhalon Dec 27 '18

I like what I call "the rule of three". On the third time writing the same (or very similar) code, time to DRY it up. It's just a recommended rule of thumb that helps define that line for myself and the team to prevent early optimization and also help make sure you really understand what the code is doing and how it is being used before trying to abstract it.

There are definitely times where I know I will be reusing code on the first draft, so I just write it that way. The flip side is the dreaded "it almost looks the same" and when you try to DRY it up and it either becomes a configuration nightmare passing in all kinds of options or the code is branching/switch hell. Sometimes duplicated code really isn't that bad.

5

u/Rumicon Dec 28 '18

W.E.T -> write everything (only) twice.

2

u/[deleted] Dec 28 '18

I do the same thing and it helps a lot. Also I nice “rule of ten” a friend of mine told me awhile back is if you have a process that takes ten lines or more, wrap it in a function. If you have a function that takes ten lines or more, think about breaking into more than one function. It just makes more readable code.

→ More replies (2)

0

u/[deleted] Dec 27 '18

[deleted]

3

u/AndrewGreenh Dec 28 '18

Just a small addition: you can accomplish the same by using interfaces. I think what one must get in Javascript or node is the usage of implicit (or explicit when using typescript) interfaces, but not only for objects but also for functions. Instead of having 3 different database implementations, why not have one generic one, that you can pass functions for saving/reading or something like that (strategy pattern).

→ More replies (3)

2

u/TheStonerStrategist Dec 28 '18

Sorry for the aside, but if you don't mind my asking, where/how did you learn the theory behind this sort of thought process? I don't mean this specific thing you're talking about, I just mean that it seems like you have a solid grasp of high-level programming concepts that are still pretty beyond me, and I'm wondering if this is just the type of understanding that only comes through many years of experience, or if I should be doing more reading/studying/video watching, etc. Like, I know what inheritance is, in the sense that I could provide a coherent answer if it was a question on an exam, but I don't think I could really enunciate its advantages/disadvantages or identify its ideal use cases like you just did. I think this sort of ability to reason about programming tactics and strategies is an area where I'm probably lacking.

5

u/oorza Dec 28 '18 edited Dec 28 '18

Mostly I've been doing this well over a decade now. When I was 18 or 19, someone told me a proverb that I have stuck to religiously and the older I get, the more I become a zealot for it: "Good developers read 10 lines of code for every 1 that they write." Reading, in this context, means reading and understanding, of course. I read almost all of the code of almost all of the dependencies that I use. I would read all the code that's consumed anywhere in my apps, but there's only so many hours in the day.

That said, it doesn't help to read code if you can't figure out why the right decisions were made or that the decisions made were sub-optimal. I didn't learn most of this shit in college because my family's finances collapsed in the 2000s and I didn't finish, so I read a ton of books. A lot of it is being able to read code, figure out what you can't understand, and figure out how to get help learning, so get in IRC or discord/slack/glitter and talk to the people that write the software you use the most and figure out why they do things the way that they do things.

Here's some books that I think are worth recommending. A lot of them are written against Java because there is almost nothing to the language itself, it's a very bare set of syntactical features, which makes it well suited for teaching concepts and abstractions.

  1. The Gang of Four is arguably the most important book in software architecture. Many of the patterns in the book are very common and will be very familiar to you, even if you've never seen them formalized before, because the book has had such an impact on the way people design software.

  2. Head First Design Patterns, despite the cringiest cover, is more or less the same information as the gang of four except that it's written to be read. If I had to do it all over again, I'd probably read this one really thoroughly to get an understanding of the concepts, and then hit the gang of four.

  3. Thinking In Java is ostensibly a book about learning how to write Java, which it is, but it's also the book best suited for teaching OOP thinking. OOP isn't just a set of tools, it's a set of tools that's best applied under certain assumptions about the way that data is structured and signals are communicated across an application. TIJ does a better job teaching the OOP way of modeling software than any other book I've come across. Java itself has changed quite a bit, and is largely superceded by Kotlin these days, but even still I'd recommend reading through the book if not working through the book.

  4. Java Concurrency in Practice is probably the least relevant think I'm gonna recommend, because again it's for java, but it starts with the assumption that you have a decent knowledge of Java and absolutely no knowledge of concurrency. It starts with primitives like mutexes and moves through them and into concurrent data structures, locking strategies, etc. Concurrency is a feature that's often omitted from high level languages (it's completely absent in JS, for instance) because it's difficult for developers to learn and understand because it's the most difficult thing in writing software. Learning at least the basics of how concurrent programming can work is helpful in architecting and designing every piece of software, because it makes you start thinking about stuff like the difference between calling setInterval and setTimeout to loop code on a timer, properly gating http requests so their responses get resolved in the order they were requested, etc.

  5. Clean Code and Clean Architecture assume that you're already a fairly competent programmer, which is why I listed them last, but they're also the most directly applicable to your question. "How do I know what bad code looks like versus good code? How do I refactor bad code to good code?" are the types of questions these books answer fairly thoroughly.

  6. Martin Fowler's Refactoring needs no blurb. Buy it, read it, grok it.

Honestly though, if you want to write good software, get the hell out of Javascript as fast as you can. There are no senior engineers anywhere in the Node community.

→ More replies (2)

2

u/[deleted] Dec 28 '18

Sure do oop if you feel like it, but js still not beeing the classical javalike oop language classes shoehorn a shitty program like no other. Ive seen this over and over, trying to mold java into js it turns to shit every time. Js as a fp langauge is just that much simpler.

14

u/cm_yoder Dec 27 '18

No sarcasm just curiosity. DRY makes sense.

9

u/mindonshuffle Dec 27 '18

It's an important concept because repetition becomes a liability for maintenance. If you have something written five times in five different places, if you ever need to change it it's way too easy to miss an occurrence or even just introduce a bug when changing (especially if they aren't EXACTLY identical).

13

u/Mettalicron Dec 27 '18

Do not Repeat Yourself

14

u/robotomatic Dec 27 '18

Do not repeat yourself

13

u/musicnothing Dec 27 '18

Do not repeat yourself

0

u/[deleted] Dec 27 '18

[deleted]

0

u/[deleted] Dec 27 '18

[deleted]

→ More replies (1)

8

u/Ashanmaril Dec 27 '18

Do not repeat yourself

1

u/unflores Dec 27 '18

DRY can be a bit of pre-optimisation itself.

15

u/chazmuzz Dec 27 '18

Dogmatically following the DRY principle can cause early abstractions that become troublesome down the road when they don't quite fit some new set of requirements. However not writing abstractions is also bad because the codebase becomes unmanageable and time consuming to update.

The skill of when to abstract is difficult but comes with experience

4

u/[deleted] Dec 27 '18

Dogma is almost always a bad thing. From my experience and from other comments I've seen on this, when you're writing the same thing for the third time then it is time to consider abstraction.

1

u/chazmuzz Dec 28 '18

Also, is it really the same thing or does it just feel similar?

1

u/littlebluebrown Dec 27 '18

Dogmatically following anything will lead to disaster in the long run. No matter what field of expertise. One should understand why the key principles are what they are.

3

u/Mattonicide Dec 28 '18

I feel like redux butts heads with DRY quite often. Especially when it comes to selectors. So many redux reducers/selectors are very similar but need to access or modify data in a sliiiightly different way that makes it very difficult to abstract without lots of customization.

1

u/unflores Dec 29 '18

Yeah. There is a bit of scaffolding. I much prefer using a standard pathway that has a little more writing involved though.

25

u/Pstrnil Dec 27 '18

Most jquery code I see suffers from the last point. Thankfully it's easy to fix.

Overall good points

21

u/qudat Dec 27 '18 edited Dec 28 '18

Not keeping things DRY.

It's funny because I would consider prematurely DRYing every piece of code a sign of an engineer who is following "standard practices" without weighing the pros/cons.

I saw DRY on the RoR site therefore everything must be DRY

I think "always DRY" is a sign of someone who isn't thinking for themselves. For me, DRY should only happen after ~3 instances of duplication and certainly never before that.

Write code that is easy to delete, not easy to extend.

I think this quote rings quite true for me. As engineers we always see the abstractions and I fear we seek it out when it isn't necessary.

11

u/mypetocean Dec 27 '18 edited Dec 28 '18

This is a rarer problem among junior devs in my experience than the lack of concern for such best practice rules of thumb.

And of the two, I'd rather have a developer who has habitualized thinking about best practices and architectural generalization opportunities (who therefore often over-engineers) than a developer who lacks that metacognitive discipline.

The former is learning where to stop generalizing. The latter hasn't begun to learn to generalize.

1

u/dungone Dec 28 '18 edited Dec 28 '18

Metacognitive what? These are simple concepts.

1

u/mypetocean Dec 28 '18

Simplicity has nothing or little to do with the question of metacognition.

Metacognition enters into the question of DRY in reflecting on similarities between thoughts and between intentions. You might implement DRY after only noting a visual similarity between parts of code, but by the time you're actually over-engineering due to DRY, it's a side-effect of the more advanced metacognitive reflection.

2

u/dungone Dec 28 '18 edited Dec 28 '18

Don't you have that backwards? If you are aware of and understand your own thought processes, then this shouldn't result in over-engineering at all. Understanding why you want to keep things DRY doesn't lead you to abuse it. At least in my opinion.

Also, I don't think DRY can ever lead to over-engineering. Over-engineering is when you make something that's actually more robust and better than it has to be. Ill-conceived attempts at keeping code DRY actually lead to it being under-engineered.

While it's an important principle, it's not the only one nor the most important. For example, I could do without all of the DRY code if only programmers would understand separation of concerns and some functional programming. If you know those two, then DRYness will be a side effect. If you don't know those two, then your DRY code will actually be a bunch of spaghetti code.

14

u/jonny_eh Dec 27 '18

This guy is actually senior. Knowing when to ignore "best practices" is the sign of an expert.

17

u/littlebluebrown Dec 27 '18

The beginner does not know about best practices. The intermediate will follow them too mechanically. Only the master knows when to break the rules.

3

u/ForScale Dec 28 '18

What are the pros of writing the same code over and over again?

I dont know who you're quoting with he "always dry ror" thing, it's not me.

It's cleaner to cache and more performant in certain situations. Store the value of querySelectorAll, don't query the dom and rebuild an identical array like html collection every time.

5

u/qudat Dec 28 '18

What are the pros of writing the same code over and over again?

Abstracting a piece of code has maintenance burden. If that code is never used more than once or twice, it's more maintainable to copy/paste.

https://programmingisterrible.com/post/139222674273/write-code-that-is-easy-to-delete-not-easy-to

Building reusable code is something that’s easier to do in hindsight with a couple of examples of use in the code base, than foresight of ones you might want later. On the plus side, you’re probably re-using a lot of code already by just using the file-system, why worry that much? A little redundancy is healthy.

It’s good to copy-paste code a couple of times, rather than making a library function, just to get a handle on how it will be used. Once you make something a shared API, you make it harder to change.

The code that calls your function will rely on both the intentional and the unintentional behaviours of the implementation behind it. The programmers using your function will not rely on what you document, but what they observe.

2

u/ForScale Dec 28 '18

Yeah, repeating code once or twice is fine.. but dear lord I'd hate to write the same 5 lines of code over and over beyond that. And I used to do that when I was starting out.. just didn't occur to me to put those five lines in a function and use that function instead of writing those 5 lines. Makes life a hell of a lot easier for me.

2

u/ScientificBeastMode strongly typed comments Dec 28 '18

It’s good to copy-paste code a couple of times, rather than making a library function, just to get a handle on how it will be used. Once you make something a shared API, you make it harder to change.

Yeah, you have to careful. I find it’s better to just keep a “utils” folder and add a few small abstractions as I work. Then as broader patterns emerge, it becomes more obvious which abstractions ought to be included in a library and shared.

1

u/[deleted] Dec 28 '18

In early stages you can't be sure what code will remain there once the first version is ready, unless you have perfect information beforehand about the application scope. You don't want ugly code, and you don't want to waste time in code that will be thrown away. Also you may want to use that time to work in features, so you get in debt ignoring code maintainability. However that is debt has compound interest, so the sooner you pay your debt the better.

1

u/ForScale Dec 28 '18

I'm not sure you answered the question of what are the pros of writing the same code over and over again. I don't see the pros of repeating the same lines of code, I dont see many cons of putting reusable lines of code in to a function or module.

1

u/[deleted] Dec 28 '18

Copy-paste is cheap.
Copy-paste is ugly.
Ugly needs fixing.
Fixing is debt.
Debt is bad.

→ More replies (1)

3

u/jasofalcon Dec 28 '18

These points are good but I would just note that those are overall good principles of software design, not only JS

2

u/sh0rtwave Dec 27 '18

I really can't argue with any of that.

2

u/FlyingQuokka Dec 28 '18

Phew, glad I passed all of these. I would also add documentation to this list. As a beginner, I NEVER used to do it. Finally, after being frustrated with my own code and such little documentation, I made it a point to properly (though painstakingly) document all future code.

3

u/[deleted] Dec 28 '18

All this goes for programming in general.

4

u/[deleted] Dec 27 '18

yeah careful with caching. lots of unnecessary things in memory can eventually become more detrimental to performance than a redundant query.

1

u/DerNalia Dec 28 '18

That last one would apply to nearly all react usage

1

u/ForScale Dec 28 '18

How do you mean?

1

u/DerNalia Dec 29 '18

During render, any derived values are recomputed each render. Most of the time it isn't an issue, cause it's usually for simplifying property access, but if there is calculation, that calculation is can every render.

→ More replies (16)

72

u/[deleted] Dec 27 '18

God functions. One function to do all the things is a tell tale sign of a jr / inexperienced Dev.

Code splitting, code reuse and organization to me are now staples of an experienced developer.

13

u/BasicDesignAdvice Dec 27 '18

See also: Code Complete 2: Chapter in Function Coupling (or some such name).

Code is meant to be read by humans. When working with a junior dev this is the only point I hammer over and over again.

2

u/FlyingQuokka Dec 28 '18

Agreed. Sometimes in my Node.js code I'll take stuff like database operations and put them in functions in a separate file so that the server.js file isn't clogged with stuff that isn't about request handling.

3

u/Tyreal Dec 28 '18

That's not always true. JavaScript gives people the unique ability of easily parsing parameters in order to perform multiple tasks. If you can make your code readable, sometimes "God Functions" are useful. Being an experienced developer is knowing when a large function is worth writing.

13

u/[deleted] Dec 28 '18

I would say this is incredibly rare case and is to be avoided when possible, especially if unit testing is part of your workflow.

1

u/isowolf Dec 28 '18

While I agree that code splitting is usually a good thing, sometimes it just doesn't make sense. If someone writes a function that was used only in one other function and nowhere else, I don't see the point of code splitting. And some devs are doing just this, because they were thought that code-splitting is good.

When I am reading code from other devs I prefer when they dont split the code just for the sake of splitting, because whenever I read a function that contains other functions I always need to refer to the functions instead of reading it all together, which obviously is easier, especially when you are trying to understand someone elses code. One simple comment line above the block of logic can totally replace the function need and make my day easier.

1

u/[deleted] Dec 28 '18

A lot of the time, if the function is named properly it should be obvious what it is returning.

There are definitely diminishing returns at some point. I'm never going to make a generic function that returns a transformed array, unless that transformation is needed in multiple other functions. Because after all , .map, .filter, .reduce are functions themselves.

19

u/s5fs Dec 27 '18

My biggest takeaway from "The Good Parts" is that languages are usually very large, and since they're created by humans (who make mistakes), not all language features are useful. It's up to us, the end-user, to create a subset of the language that we find valuable.

I would say the biggest thing you see in professional code vs novice/amateur code is consistency. I'm talking about consistency in formatting, variable naming, patterns, etc. If we're talking about a single microservice, you really want to keep the code looking and feeling identical throughout the project. It's okay if two related microservices are developed with slightly different styles, but having too much goofy stuff within a single codebase is annoying.

The other thing you don't often see in amateur code is test coverage, documentation, and ci/cd.

4

u/[deleted] Dec 28 '18

consistency in formatting, variable naming, patterns, etc

If you use prettier and eslint, this won’t be a problem

3

u/benihana react, node Dec 28 '18

If you use prettier and eslint, this won’t be a problem

this is a short term fix. learn how to name variables, learn how to format code for comprehension, learn how to make code easy to understand and you'll be able to write good code whether linting is available or not. when you can write good code, linting becomes a tool to help you, rather than a crutch you need.

1

u/s5fs Dec 28 '18

Agreed! Tools help immensely with this stuff, and in amateur codebases you don't see them used because there is often a lack of understanding the need for them :) Automation is crucial in professional software work, that's for sure!

17

u/darrenturn90 Dec 27 '18

Copy and paste straight from stack overflow rather than reading the answer and reworking the solution themself

1

u/csmie Dec 28 '18

this is the one . Easy to understand code is irrelevant if it's wrong. I like code where people understand the why.

17

u/[deleted] Dec 27 '18

Adding a lot of unnecessary npm dependencies to avoid solving pretty simple tasks is a big indicator that it’s a novice dev

Running into scoping issues/not being able to determine a bug is from a scoping issue

Using jquery or manipulating the dom along with angular, react, vue, etc. where you’re explicitly NOT supposed to manipulate the dom

Same 5 lines of code across 10 functions within the same file

Over abstraction as well

3

u/Cheezmeister http://bml.rocks Dec 28 '18

Many replies ITT help me distinguish a novice from an intermediate dev. These five will distinguish the intermediate from the pros. Have an upvote.

1

u/thesublimeobjekt Dec 28 '18

i disagree. those are 100% all things that intermediate devs should know. i could maybe give you #3 since those libraries are so popular that i'm sure a lot of devs use them without even really thinking.

1

u/[deleted] Mar 13 '19

Lol... u must be a new lead or not a lead at all

1

u/thesublimeobjekt Mar 14 '19

i'm really curious what makes you say this. perhaps my expectations are just higher than most, but i definitely have the experience that you're questioning with your haughty "lol". i was a team lead/senior full-stack dev for 6 years, and then 2 years ago i left to start my own company, where i obviously also lead my team.

do you really expect intermediate level devs to not know some of this stuff?—to be fair, saying that intermediate devs should 100% know all of those things might be a bit of an exaggeration, but they should definitely know most of them. in addition, maybe our idea of an intermediate dev is different. in your mind, how many years of experience does an intermediate dev have?

8

u/shocked-pikachu Dec 28 '18

I've learned came from w3schools

I highly recommend using MDN rather than W3schools as a source of information.

7

u/JohnWH Dec 27 '18

I think this really applies to all code:

  1. Copy and pasted code, as in I see the exact same functionality re-typed 5 times in the same code review. Make a reusable function.

  2. Not following any sort of style/not linting your code, as in you sometimes put spaces between arguments, other times you don’t.

  3. Side effects in your functions. I consistently see people updating a separate object in a map function, which is completely unreadable and hard to track for any engineer trying to figure out why something is being updated.

  4. Using a full library for something really simplistic, or something that is handled in a lighter weight library. Don’t download $jQuery to just make $ajax calls (some would argue not to download Axios until you really need it).

  5. Ridiculously complex code that is not properly broken down. I have seen 100+ line functions for munging data, where similar code is repeated throughout the code base.

Specifically JS:

  1. Using fat arrow and function interchangeably, not understanding scope in general.

  2. Using == outside of very rare cases

  3. Not considering falsely value when writing functions (is 0 valid compared to null)

  4. Not using destructuring and param defaults, especially when you keep having adding params to a function where some can be null.

3

u/tencircles Dec 28 '18

Not using destructuring and param defaults, especially when you keep having adding params to a function where some can be null.

There's a flipside to this. I've had Jr. Devs who recently learned param defaults add them in places where the code should actually throw due to a missing param. This creates some extremely nasty bugs due to what is essentially Error Hiding. Even more important that having sensible defaults is knowing which params should default, and which should throw/warn if missing. The rule to follow is always "If your function/component/class cannot do what it's supposed to do without param X, then it should throw when param X is undefined/null"

-7

u/PicturElements Dec 27 '18 edited Dec 27 '18

I very much disapprove of === snobbery. If your code is decent, you have checks in place to deal with erroneous types, and you pass the correct types to your functions, there really isn't much harm in loose comparison, not even performance-wise.

If you end up comparing 10 and "10" you have a bigger problem than different types, in my opinion.

Use whatever you want, really. If you use strict comparison by default, do it. If you use loose comparison by default, do it.

11

u/JohnWH Dec 27 '18

I guess I don’t see the reason why you wouldn’t use ===. It adds additional type security at no cost. I have seen so many mistakes related to == that I just cant imagine where there is a benefit to using ==

Understandably, adding typing is a lot more secure, but === is basically effortless.

2

u/PicturElements Dec 27 '18

Yeah, hence why I'm fine with using either, although consistently . I prefer == because when it's not used the reader knows immediately that the correct type is required for the function to function normally (or that the developer has spotted a potential weakness where not using strict comparison would result in bugs in edge cases).

I've personally only had one bug (that I know of) attributable to a rogue ==, but of course that's just me.

Besides, novices can use === too, no problem. I would even say that === is easier for a beginner to grasp, behaving more consistently. I also assume guides and tutorials use strict comparisons anyway as to prevent beginners from making rookie mistakes.

13

u/aminnairi Dec 27 '18

I teach Javascript to some of my classmates in what we call here a Javascript Lab where we try to push the boundary of the use of javascript and the biggest mistake I often see is thinking that they cannot solve the problem because they have never encountered it yet even though everything they need to solve it is already in their possession (language features). I think the biggest mistake IMHO is thinking that a problem cannot be solved. Why don't start by thinking that there must always be a solution but we do not have it. Yet. Maybe not the advice you waited for but I took the opportunity of your post to say that and I think most of us need to hear that.

4

u/thesublimeobjekt Dec 28 '18

Maybe not the advice you waited for but I took the opportunity of your post to say that and I think most of us need to hear that.

i actually think this is some of the best advice in the thread. it's sort of something you don't hear a lot, but i totally agree. i always tell me clients, when they ask "can we do $x?"—"we can do literally anything you want, it just depends on how much time and money you're willing to spend." i won't tell them something's impossible unless it's breaks the conventions of computer science. :D

2

u/OmniscientOCE Dec 28 '18

What kind of things for example do you do that push the boundary of Javascript may I ask. curious

1

u/aminnairi Dec 28 '18

Often, they either don't develop Javascript apps in a daily basis or don't develop apps but are more of a design background so I take real life example problems that I encounter at work and try to help them find the solution (oddly it is more algorithmic than javascriptic).

12

u/PUSH_AX Dec 27 '18

The main difference is software engineering principles, eg: modularity, good separation of concerns, abstractions, single responsibility principle, loose coupling and all that good stuff.

This is generally not stuff you'll learn in a JS book, but there are books that cover it. Also people need to stop reading JS the good parts, it was over rated even when it was relevant, it's massively outdated now, a better book series for JS would be: You Don't Know JS

7

u/mypetocean Dec 27 '18

Also, Martin Fowler's "Refactoring" was just re-released on late last month with modern JavaScript in mind (rather than Java and Ruby, which the other editions focused on).

1

u/[deleted] Dec 28 '18

Hitting this up

1

u/[deleted] Dec 27 '18

[removed] — view removed comment

5

u/PUSH_AX Dec 27 '18

Yes, the Pragmatic Programmer by Andy Hunt and Dave Thomas was very good, and Clean Code by Robert C. Martin.

2

u/bodiewankenobe Dec 28 '18

Yes. A million times yes to Clean Code. I recommend it to every Jr developer regardless of language. It is the one reference I have gone back to over and over throughout years of programming.

1

u/kardnumas Dec 28 '18

So, I was reading Pragmatic programmer and in Goals section, I saw "Learn at least a new language every year" where it says you will get broad knowledge across languages.

What do you think about it? Like myself, I also learned to programme with PHP and OOP concepts with java and now more dynamic things with JS and I think its somewhat relevant but still a language every year or 2 is quite tedious IMO

1

u/PUSH_AX Dec 28 '18

I don't learn a new language every year, I'm not sure I see the point, as you say it's tedious and if I'm not going to use it for work it's just going to fall out of my mind after a few months. I do try and learn a large piece of tech every year I suppose, this year it was graphql for example. That is something that I could use in a job.

14

u/[deleted] Dec 27 '18

one thing i notice i used to do a lot was

var _this = this;
function(){
  doSomethingWith(_this)
};

but now with arrow functions this isn't necessary anymore and makes me cringe whenever i look at old code i wrote.

6

u/PotaToss Dec 27 '18

Even without fat arrows, it's better to give it an actual descriptive name rather than something like _this or that or whatever. You could also use bind or whatever.

3

u/[deleted] Dec 27 '18

this is just an example. I usually did use descriptive names, and bind wasn't usually an option as I needed the natural context variable for the inner function as well.

1

u/kaelwd Dec 28 '18

I've seen loads of people do that even with arrow functions.

1

u/svtguy88 Dec 28 '18

On a related note, if you do use bind, do you still have access to whatever this would have been inside the function? I'll admit that I still use var that = this from time to time...

1

u/[deleted] Dec 28 '18

normally no, unless you can get a reference to it from somewhere else. the whole purpose of bind is to set the "this" variable. you could use the "call" or the "apply" methods too which just change it for a single call whereas bind changes it permanently and returns a whole new function.

-2

u/highmastdon Dec 28 '18

You’d better use bind for that.

function(){
  doSomethingWith(this)
}.bind(this)

2

u/[deleted] Dec 28 '18

read my reply to the other guy who said the exact same thing.

4

u/tchaffee Dec 27 '18

Thinking you are done when your code solves the problem at hand. Experienced devs take what they learned from their first iteration and may rewrite / refactor some or even all the code. I'm usually happy by my second or third iteration.

Not asking enough questions and waiting too long to ask questions. Senior devs are there to help when you get stuck. But don't be lazy. You should show up with your questions along with a list of what you already tried.

Leaving comments with concrete examples of what a function does is great, but even better is a set of automated tests with several examples, especially the edge cases.

4

u/thingsthings Dec 27 '18

TypeScript helped immensely. Thinking in functional programming too.

14

u/[deleted] Dec 27 '18
  • The difference and use of apply, bind, call and when/how to use them.

  • Not managing asynchronous behavior correctly and ending up with race conditions.

  • Not fully understanding that functions are first class objects and you can pass them around as arguments to other functions.

3

u/thesublimeobjekt Dec 28 '18

> The difference and use of apply, bind, call and when/how to use them.

this one gets brought up _so_ often, i feel like, and i truly don't understand how there are people out there that don't know the difference, most likely because they've never even used them. it's possible that i just overestimate the average developer, but especially with libraries like react that used `bind` and `call` pretty often early-on, it still seems strange to me.

2

u/drink_with_me_to_day js is a mess Dec 28 '18

I've yet to use any of those three. Never had a need to do so.

1

u/thesublimeobjekt Dec 28 '18

how long have you been developing?

1

u/drink_with_me_to_day js is a mess Dec 28 '18

8 years. With JS only recently, last 3 years, when adopting React and RN (ES7 and Typescript).

1

u/thesublimeobjekt Dec 28 '18

i guess i could see that then, especially if you’ve mostly only been around post-ES6.

1

u/chauey Dec 28 '18

With fat arrow => and classes, rarely need to use apply bind call from my experience

12

u/[deleted] Dec 27 '18

Just to provide some context, this is what the [deleted] commenter /u/MystK posted:

I get paid a lot of money as a JS developer, so I think I am quite experienced. I feel like your first and last points are outdated. Modern JS code doesn't need apply/call at all and bind very rarely. Passing callbacks aren't too common either with the new async/await syntax.

If this was an interview question, and you gave those answers, I would probably think you aren't keeping up with JS and would not hire you.

Having said that, I definitely think it's important to understand our roots, and I value engineers that understand these concepts, but if this was given as an answer to "novice vs professional" JS code, it'd be a thumbs down for me."

The fact that he/she deleted the comment just goes to show how off the mark this individual is. Which I find ironic, this is the kind of comment someone that isn't a professional developer would throw at you - bragging about salary and trying to put himself in the context that he/she may be interviewing you so as to cast the other person as lesser experienced instead of using constructive arguments to prove a point.

0

u/[deleted] Dec 28 '18

Sorry, but u/MystK has the right of this about (about bind, call and apply anyway). Bind, call and apply are inherently confusing and have poor static analysis support. There is nothing you can do with them that can't be done more clearly with arrow functions, classes and pure functions. Professional developers who have a lot of experience understand the value of clarity.

→ More replies (5)

0

u/[deleted] Dec 27 '18

[deleted]

11

u/phpdevster Dec 27 '18

I feel like your first and last points are outdated

TIL that passing around functions as first class values in JavaScript is "outdated"...

6

u/highmastdon Dec 28 '18

Thou shalt not make a function like map, rather await it /s

12

u/ogurson Dec 27 '18

Modern JS code doesn't need apply/call at all and bind very rarely

Yeah, except each time you need to pass function as event handler and preserve this (I'm omitting function as class properties).

Passing callbacks aren't too common either with the new async/await syntax

Have you heard about that niche thing called Functional Programming?

2

u/[deleted] Dec 28 '18

Yeah, except each time you need to pass function as event handler and preserve this (I'm omitting function as class properties).

Sounds like there is a cleaner way to do whatever is trying to be accomplished there.

1

u/zeugenie Dec 28 '18

Yeah, except each time you need to pass function as event handler and preserve this (I'm omitting function as class properties).

arrow functions

Passing callbacks aren't too common either with the new async/await syntax

Callbacks are a special case of function to be executed after the execution of some other function. In async code, async/await more or less obviates them.

3

u/BasicDesignAdvice Dec 27 '18

Mostly the same things that are bad in any language. Read Code Complete 2, The Pragmatic Programmer, and Eloquent JavaScript.

Now you know too.

3

u/YodaLoL Dec 27 '18

Nested (deeply nested) objects. Large functions. Bad naming. Bad/incorrect function composition. Not adhering to conventions, or well, not sticking to a single coherent style.

3

u/[deleted] Dec 28 '18

Inconsistent code formatting.

3

u/vanweapon Dec 28 '18

Nobody takes the time to go back and refactor their old code. I'm guilty of this myself, but whenever I have the time I try and do this. A good developer should be learning new and better ways of doing things on an almost daily basis, whether through experience, training or just being exposed to wild code. For this reason it's almost certain that you could go back to code you wrote even a couple months ago and make it 'better' in some way.

Additionally, Comments should be used to explain "why" more than "what". Sometimes it's unavoidable, but usually if you need to explain what your code does then you haven't written it very legibly. On the other hand, just because someone knows what you've written, doesn't mean they know what motivated you to do it that way. This also makes it easier for more senior developers to clean up your code if they find it. If you say "I wrote x when it couldve been y because I tried y and it gave me z problem" then other devs with different experiences and ways of thinking will be able to help you if they know a better way.

3

u/jaman4dbz Dec 28 '18

FYI there is no difference between a senior JS dev and a senior anything-else dev. At least as far as skill is concerned.

a senior JS dev may suck at Rust now, but give them a few months and they'd probably do amazing with it.

That may sound unrealistic, but the truth of the matter is, there is no senior JS dev that's been programming for a couple years. If they're senior in JS or anything, they've been programming for at least 5 years if not much much longer.

2

u/couchmonkee Dec 27 '18

Abstractions and Modular code.

2

u/Protato82 Dec 27 '18

Usually, I think what defines novice JS from more experienced programmers is the ease of understanding what they've written. If someone writes their code like someone else is going to pick up the program and work on it as well then they can write much better code. Of course, there are some exceptions and I can't really list them all here.

2

u/Klowner Dec 28 '18

Writing a "UI framework" by adding abstractions atop jQuery, not even once.

2

u/LastOfTheMohawkians Dec 28 '18

Imperative Vs declarative code

2

u/Colonel_White Dec 28 '18

Professionals know when Douglas Crockford is full of shit, and when his advice should be considered law.

Crockford deserves much credit for observing that JavaScript object literals are an efficient and self-documenting data description language in their own right.

JSON has drowned the wicked and obese XML in a bathtub, which is ironic because Crockford loves imposing arbitrary rules and XML is positively totalitarian; but alas, he came of age in an era when computers didn't have unlimited memory or clock cycles or bandwidth, so he's quick to recognize and exploit such sources of clean-burning and renewable mojo.

(There is an anecdote about an ECMAScript meeting Crockford attended where the language's author Brendan Eich tore a copy of "Javascript: The Good Parts" in half and tossed one half into the trash.)

Crockford used to hang out on Google Plus, but when he started rejecting comments from anyone not in his circles I stopped following him.

2

u/[deleted] Dec 28 '18

I'm by no means a JavaScript expert, but one of the things I found extremely challenging when I picked up JavaScript was that it gives you so much freedom in terms of how you approach and structure your software. When you're writing something in Python, you're subject to some pretty strong constraints in regard to how you structure and approach your code, as you are with Java, but with JavaScript not so much, in my opinion, at least. You can conjure a piece of software, adopt an object oriented approach and produce something that doesn't just work but is scalable and maintainable, too.

The catch, however, is that you could also adopt a functional approach, or even a declarative one and achieve the same results, which is not a bad thing, quite the contrary, when you have some grounding in the language; I say it's not a bad thing because I think freedom is good and I'm not a big fan of dogma when it comes to code, or life for that matter.

It's a question of knowing which tool will get the job done, but my n00bier self (I say n00bier because I still think of myself as catastrophic n00b), found all this choice to be very confusing and in the beginning it hampered my ability to adopt good JavaScript practices and the end products that I somehow managed to spawn read like the ramblings of a mad man, locked up in an asylum, with a fever.

To me, this is what separates the JS developer with grey hair and the bouncy whippersnapper; knowing when to use what tool, or approach and structure, if you will, when solving a particular problem in JS. I think two perfect examples of what I'm trying to get at are THREE.js, which is object oriented and for good reasons, and Redux, which draws on a functional approach to programming, also for good reasons.

Oh, and throwing in the DOM into the mix does not make life any easier for a novice JavaScript developer... That much is certain, but please note that much like I learned to like broccoli and black coffee, I've learnt to like the DOM, too, so I'm by no means trying to go all sassy on it, here.

Having said all that, I'd recommend any JavaScript n00b that is serious about understanding the language and adopting good practices to read Addy Osmani's excellent Learning JavaScript Design Patterns. It might not cover all the new awesomely fancy libraries and frameworks that are ought there, but it gives you a deeper understanding of JavaScript, and with that you're ready to start shopping for your favourite framework and argue about how it's better than all the other frameworks out there here on Reddit or wherever you prefer to argue about such matters.

2

u/nscloudnext Dec 29 '18

Novice.

if (name != "" && name != null && name != undefined) {...}

Expert.

if (name) {...}

Novice. this vs that is confusing

Expert. 'this' is the context of invoked function

3

u/name_was_taken Dec 27 '18

Mistakes. Bad/inconsistent formatting. Failure to predict the bad things that could happen and handle them.

3

u/[deleted] Dec 27 '18

Haha yes. One time I was at a code and coffee meet up here in Toronto, where a coffee shop basically hosts and open time for random people to code. I overheard this one girl go on a rant about how 'stupid react was' and that 'i can do everything in jQuery'. To myself I was like... Oh yah I remember having this attitude towards new things...

I remember having my own resistance to every site needing to be responsive , as well as any need for version control. Now, I'm all about responsive design and git is probably the single most useful tool I've used in the last 5 years.

2

u/[deleted] Dec 27 '18

I remember having my own resistance to every site needing to be responsive , as well as any need for version control. Now, I'm all about responsive design and git is probably the single most useful tool I've used in the last 5 years.

Taking that a step further, learning the tools you work with inside and out.

I CAN use Adobe Premiere. I CAN use Adobe Illustrator, but 50% of the time I have to look up how to use a specific tool or do something particular. My basic understanding of the tool does not make me proficient with it.

Back to Git, I used it for several years just fine, but I'll admit I had far too many commits that were something along the lines of "fix this that and 3 dozen other things" with no real separation of concern. I still end up with a working directory full of 10 or more active changes on many occasions, but learning how to properly use `git add -p` and `git diff` has allowed me to avoid the super commit nonsense. I now feel like a professional git user. Before I was just making use of the tool somewhat effectively.

1

u/[deleted] Dec 27 '18

If I'm honest, I have a very cursory knowledge of git. I find the documentation actually offensive to read. That being said, I know at least the bare minimum, and about average amount on my team. Always looking to learn more though...

So any resources you have I'd love to see.

1

u/[deleted] Dec 28 '18

As far as resources, I mostly just use cheat sheets like this one. But with regards to the specific commands I mentioned, git add -p lets you commit partial changes of a file. So if you change 20 lines but only 4 lines apply to the current commit, you can pick just those 4 lines. And you can subdivide (chunk) that set of lines even further if necessary.

I always knew about git diff, but wasn't very efficient with it until I learned a few specific things:

  • git diff compares your working directory to the last commit

  • git diff --cached compares your staged changes to the last commit.

  • git diff -w compares changes while ignoring white space (useful for mixed environments, etc.)

1

u/tencircles Dec 28 '18

To play devil's advocate, I've used React pretty extensively, I've also done more than a little framework design, and I still refer to React's tree diffing as a "hack" which really triggers react die hards. React offers a great abstraction that hides all of the individual add/update/remove operations on the DOM, but like all abstractions, it comes with a cost.

That being said...doing everything in jQuery sounds like a nightmare. I didn't even do that back in the day.

1

u/YsoL8 Dec 28 '18

Git is probably the single most important tool in any development environment period.

0

u/[deleted] Dec 27 '18

[deleted]

2

u/[deleted] Dec 27 '18

I haven't gone in a while, location rotates.

https://www.meetup.com/Coffee-Code/

3

u/deadlyicon Dec 27 '18

Professional code tends to have long, specific and descriptive names for things.

Beginners tend to try and optimize the coding process by abbreviating everything.

I’ll also add: professional code doesn’t need comments. It’s simple, clean and clear enough to understand without added explanation. If you need a comment you’re being to implicit or tricky with your code.

5

u/ZekeyD Dec 27 '18

Id disagree with this, comments used correctly for blocks of code allow clear labelling or summary of what a function actually does.

Im not talking about every line, but honestly if I can read 2 lines of comment about what an unfamiliar 20 line function does, im going to do that every damn time

4

u/deadlyicon Dec 28 '18

The name of the function and it’s arguments and the file it’s define in should convey this. If they don’t you have some growing to do. As we all do. But comments, in my experience, are almost always outdated and more misleading than helpful. Clean code is the way.

1

u/ZekeyD Jan 01 '19

I agree they should, I make every effort to do so but find easier to look back at old code and knowing exactly where to edit

2

u/janjarfalk Dec 28 '18

Even the most simple, clean and clear code can do the wrong thing. I use comments to describe intent, rarely to explain code.

1

u/deadlyicon Dec 28 '18

uh… if it does the wrong thing, it's not clean or clear.

2

u/janjarfalk Dec 28 '18 edited Dec 28 '18

Then we mean different things when we say clean or clear code. I mean that beautiful solutions are always beautiful, but sometimes they are the wrong solution.

Do you agree that it’s easier to fix broken code if you know what the author was trying to accomplish?

1

u/deadlyicon Dec 28 '18

IMHO if you cannot express the "what is this supposed to do" in the name of the function, then the function does too much. And in the more complex cases: the tests should explain whatever the name cannot, in code.

Do you agree that it’s easier to fix broken code if you know what the author was trying to accomplish?

Yes

1

u/janjarfalk Dec 29 '18

I agree that it’s ideal when the function name describes the full intent, but when it doesn’t comments showing intent helps me fill the gap.

https://standards.mousepawmedia.com/csi.html

1

u/jdauriemma Dec 28 '18

Poor unit test hygiene. You can always tell when tests are an afterthought, and it usually is a sign that the source code has logic gaps.

1

u/Poropopper Dec 28 '18

Just read clean code, the language is irrelevant.

1

u/[deleted] Dec 28 '18

My quick way of telling who wrote the code:
beginner code === usually fugly, incoherent code
professional code === uses a code standard

Other than that, i usually look if they namespaced things or not, that's usually a good tell :-P

1

u/tmm84 Dec 28 '18
  • Not using a linter or style rules. Linters help to remind/enforce certain rules that should be applied to code. Style rules ensure everyone on the project writes code according to a given style which saves time.

  • Setting a variable over and over to different types/values.

  • Trying to write JS like it is another language. JS is different and using the style/conventions will save you trouble from stuff that doesn't run 100% like the language you are used to.

  • Trying to do things browser specific. This is something that is getting harder to do (browser security and what not) but so many clients ask for it. Either put up with possible future code breakage or just flat out discourage it.

  • Understanding falsey/truthy, null and undefined.

  • Using MDN for reference. They have one of the best references for JS and it even tells you which browsers support a feature.

  • Console.Log all the things. Callbacks/Promises/Async can make console.log unreliable in certain environments and logging stuff in the browser in production is something you'll either get praise or hate for.

Most programmers won't agree with me on all of this stuff but these things helped me get super good at JS.

1

u/DaveVoyles Dec 28 '18

No comments. For some reason I find many veterans don't find the need to comment their code.

Illustrates that they haven't worked on complex code bases before. The author may know what that line does, but can the person who needs to replace you, even if it is on your sick day, understand what it does?

When reading a line of code, if you ever stop, even for a second, to ask yourself "what does this do again?", that means you need to add a comment.

1

u/[deleted] Dec 28 '18

The same thing I see in every piece of code written by an inexperienced programmer:

It's written like a scrawling maniac, who's not considering the bigger picture.

And it's only getting worse, what with this whole "code now, complain later" mentality. Utter crap. Sure we have rolling requirements, but there are core formats and structures to every language that make it easily shiftable and adaptable to any problem. Shifting requirements and features should be plug and play, not re-write and re-structure.

Like adding another candle to a never-ending cake. All it should take is a little more icing and another candle. Not a whole new mix and bake.

1

u/[deleted] Dec 28 '18

Coding for interviews and for actual production code is quite different. For interviews I don't necessarily expect a lot of thought for naming or proper abstractions (unless that's what the question is about), you should concern yourself more with solving the problem rather than with getting perfect names, DRY, commenting necessary unclarities, etc.

but when reviewing production code, certainly those things would pop up if they're not considered.

Imo you could spend time going over highly maintained open source projects to see how they're written, exposure to professional grade code is better than a book on the topic.

1

u/iSmokeGauloises Dec 28 '18

I absolutely agree, just making a point that you can always trick your way around loops if you want clever boy points from FP wankers.

The operation is awaitable though, it will return a promise that would be resolved when the last promise resolves.

1

u/chauey Dec 28 '18

Using .bind vs => fat arrow? Thoughts?

1

u/[deleted] Dec 28 '18

The same as in any other lang. Verbosity, using loops, failed logic and the lack of tests.

1

u/CalinLeafshade Dec 28 '18

jQuery plugins everywhere.

1

u/CaptainTrip Dec 28 '18

Messy or imprecise thinking as if the writer isn't 100% about which lines are contributing to their code. This is particularly apparent when code has evolved over a period of time as a person tries to just get it working, and various vestigial code paths or functions or variables end up being left in. This is common to all languages not just JavaScript, but unlike stylistic issues it has a real and calculatable cost if code with these problems becomes common in a code base, and when mentoring new hires you can really see their growth when they stop sending you sloppy PRs full of changes they can't quiiiite remember why or if they're needed, and they start sending you precise and concise changes. Like engineers.

1

u/[deleted] Dec 28 '18

==

1

u/[deleted] Dec 28 '18

Overall, I see more "advanced" people forgetting about all the basics... Proper consistent naming, not keeping to high cohesion / loose coupling, etc

1

u/[deleted] Jan 02 '19

One way to identify the difference is to look closely at the structure of the project. ’Professional’ javascript should be well commented and easy to navigate. For example, using MVC (model view controller) or for ReactJS, separating components and containers.

1

u/devlocalca Jan 04 '19 edited Jan 04 '19

Professional Javascript code? ha that's a good one. Javascript is the cockroach of software development. How do you tell a novice cockroach from a professional cockroach? I dunno, they are simply both cockroaches.

The better question is: How do you tell a novice programmer from a professional programmer. If I see any programmer doing anything remotely akin to Javascript, I know they are not a professional programmer. This s*** should have died long ago, I have never seen such a mess as Javascript and all the crap that swirls around it.

We have the great pacific garbage patch, Javascript and all that swirls with it is the equivalent in the software language world. A big pile of swirling shit bigger than any continent, and it keeps getting bigger.

Google's script kiddies played a really big role in feeding this cockroach. If there were three brain cells among the bunch, they would have done something else. This year, seriously, I will be working on stripping anything and everything remotely related to Google from my life, including android, chrome everything, all services. I have setup a paid hosting service for email, no more free email and working steadily towards stripping Javascript from touching any moment of my day.

Also, I hate to tell ya, Javascript is not the same as Java. Javascript's first bad start was for the idiot who invented it to think it was Java, or to call it Java. What a F**ing moron. What story, please tell me, was he telling himself when he named it Javascript? That's how dumb the guy was.

Here is his story:

https://www.youtube.com/watch?v=0eF4d1EfCqc

1

u/TaveGabriel Jan 13 '19

Use ES6 standard! It added some really cool features to JS and it's a lot more readable sometimes.

-9

u/bjenkins2410 Dec 27 '18

Something that I see often in less experienced JS developers are for loops! I used to use them all the time, but I haven't written one now for a long time.

Learn map, filter, reduce, find, some, and every like the back of your hand. You probably don't need [].forEach either. I even use an eslint plugin to disallow loops. Even with that I see developers using forEach a lot, when they could just use one of the other higher order functions.

Just to clarify you'll need forEach here and there, but don't jump for it so fast, and next time you're about to write a for loop, please reconsider :)

15

u/[deleted] Dec 28 '18

I think having an eslint rule banning for loops altogether is a bit extreme. There some niche cases when for loops are needed

4

u/OrangePhi Dec 28 '18

it's not extreme, I use that rule too, among other "functional programming" rules. The goal is not to ban loops but to discourage their usage because map, reduce and filter are better almost 90% of the time. If you really need a for loop you just have to prepend a comment // eslint-disable-next-line fp/no-loops and you are good to go. This is easy to spot in a code review so you'll have to explain why you need the for loop.

5

u/fecal_brunch Dec 28 '18

Isn't the presence of the loop annotation enough?

2

u/nanaIan Dec 28 '18

yeah, just code review properly

hey man, it's probably better to use .filter here instead of this for loop

0

u/[deleted] Dec 28 '18

[deleted]

7

u/filleduchaos Dec 28 '18

I'm curious as to how you've never run into a situation where you need to perform a bunch of asynchronous actions in series before. In my experience people come up hard against that limitation of the array HOFs in short order.

6

u/iSmokeGauloises Dec 28 '18

I mean I completely disagree with the no loops rule because it's absolutely retarded, but this is quite a trivial problem to solve without loops:
[async1, async2, async3].reduce((p, n) => p.then(n), Promise.resolve())

10

u/filleduchaos Dec 28 '18 edited Dec 28 '18

And you don't see how

  1. that's a borderline silly alternative to for (let p of [async1, async2, async3]) { await p }? I thought the aim was "readability"

  2. you can't actually await the operation, making it non-viable as a complete solution I'm blind (execution immediately hands off to the next line, and in some cases you would actually want to halt it)?

3

u/Quabouter Dec 28 '18

2) you can't actually await the operation, making it non-viable as a complete solution (execution immediately hands off to the next line, and in some cases you would actually want to halt it)?

Sure you can, the result is just a promise.

await [async1, async2, async3].reduce((p, n) => p.then(n), Promise.resolve())

That said, this example is completely nonsensical: there is no effective difference in waiting for n promises sequentially vs waiting for all of them in parallel. This code should simply be await Promise.all([async1, async2, async3]).

5

u/filleduchaos Dec 28 '18

Oh true - brain fart. It skipped my mind that you had passed in a promise as the initial value.

there is no effective difference in waiting for n promises sequentially vs waiting for all of them in parallel.

Are...you actually serious? You don't think there's a difference between code executed in series and code executed in parallel? Order of execution is completely unguaranteed with the latter and is actually important in solving a variety of problems (couple of examples I've had to deal with in the past month alone: a folder of bash scripts that are supposed to be executed one after the other and a helper function for cascade-saving a bunch of related DB entities)

5

u/Quabouter Dec 28 '18

Of course there is a difference between code being executed in series vs parallel, but that's not what we're talking about here: a promise is a result of an execution, and waiting for a promise does not execute it. series vs parallel is relevant when resolving promises, not when awaiting them. e.g. these are all equivalent:

// 1
await Promise.all([promise1, promise2]);

// 2
await promise1;
await promise2;

// 3
for (let p of [promise1, promise2]) {
  await p;
}

// 4
await [promise1, promise2].reduce(reduce((p, n) => p.then(n), Promise.resolve());

What's more, none of these actual tell you anything about the order in which the promises are resolved.

On the other hand, these definitely aren't equivalent:

async function f(a) { /* ... */ }

// 1: executes in parallel
await Promise.all([f(1), f(2)]);

// 2: executes sequential
await f(1);
await f(2);

// 3: executes in parallel
for (let p of [f(1), f(2)]) {
  await p;
}

// 4: executes sequential
for (let a of [1, 2]) {
  await f(a);
}
→ More replies (2)

7

u/yazalama Dec 28 '18

What's wrong with using for loops?

4

u/[deleted] Dec 28 '18

Easier to make off by 1 errors imo

3

u/bjenkins2410 Dec 28 '18 edited Dec 28 '18

If you’re using a for loop to create or change an array you’re most likely mutating it. All the higher order functions mentioned create a new array.

For loops therefore can lead to some pretty annoying bugs. And all the higher order functions are clearer, and less verbose imo.

2

u/beizhia Dec 28 '18

Personally, I've bought in to functional programming, so I rarely use loops. The idea that you produce new data rather than altering existing data helps me write code with less side effects and unexpected results.

I think these array functions make code more readable too. [...].map(something).filter(some predicate) has a more obvious intention than having to read through a loop's body with nested if-else statements to try to parse what's being done.

6

u/phpdevster Dec 28 '18 edited Dec 28 '18

I would also throw in ES6 Map types as well.

Stop using object literals as map storage and then doing janky shit like

  Object.keys(myObject).map(key => myObject[key].whatever());

Whenever you want to store something as an easy to index map, reach for the Map type. It was designed explicitly for this purpose.

1

u/[deleted] Dec 28 '18

Professionally-written, industry-grade Javascript runs extremely slowly and uses about 200mb of libraries for what could be done with about half a page of code. I really wouldn't worry too much about professional standards in the world of Javascript.

1

u/justrhysism Jan 06 '19

What you're talking about is intermediate developers.

Experienced developers are often happy to do the minimum amount because they do consider things like performance, page-weight and time/value - and are also typically library-averse.

-1

u/Tysonzero Dec 28 '18

The biggest mistake I see people making with regards to JavaScript is using it by choice.

0

u/omgdracula Dec 27 '18

Lack of comments pointing out what the script does or what things it might control on a site. Nothing worse than looking at a bunch of functions with no comments as to what they are tied to.

6

u/ogurson Dec 27 '18

Comments are tricky area - good code is readable without any comments.

Whatsmore comments needs maintenance just like code otherwise they could be misleading.

1

u/[deleted] Dec 27 '18

Just to tack on, naming itself is a form of documentation.

1

u/omgdracula Dec 28 '18

I agree with you, and I am not talking just comments within JS but just in general. I would never hand over a project post launch that moves into support to one of our interns with out comments so they know what will be affected by changes that they make.

1

u/YsoL8 Dec 28 '18 edited Dec 28 '18

I'm of a mind that if your code needs more than a brief declaration of purpose above function definitions to understand what stuff does you need to refactor. Explaining code inside a function indicates you have made assumptions about the input / output or you are introducing a non trivial fork into your one purpose function. There are exceptions here and there for functions that are inherently complex but few are.

Also, you should assume parameter lists in comments are just wrong, because they almost always are.

2

u/neonWednesdays Dec 27 '18

I'll support you on this opinion. While I do want my functions to be well written and understandable just by looking at it - most of the time I'm looking at other code in order to walk through a stack of operations or looking at a series of functions and would greatly appreciate reduce the need for mental overhead.

It's pretty easy to see that we all have different ideas of how to write code, and we interpret things differently; a function named `getTotalValue()` for you might be doing calculations but to another it might just be return an attribute or property. I like looking at comments that explain what the author's intent and reasons for why they chose a specific implementation direction.

3

u/phpdevster Dec 27 '18

This is super sketchy. A function, by nature, should have no knowledge or opinion of what it's "tied" to or where it's used. It's a mercenary. You give it what it wants, and it will give you what you want. No questions asked. It shouldn't care, have any opinions, or even any knowledge about who is calling it.

There's a formatting function in my codebase that's probably used in 300 different places. Should I have included every place it's used in a comment for that function?

What a script or function does should be obvious from its code. Why it does it should be defined assuming it the reason why is not obvious.

Comments lie and get outdated. They are mostly untrustworthy. Code tends to be honest, though sometimes even names of variables, functions, and classes can lie.

1

u/omgdracula Dec 28 '18

Well every business functions differently. At my job we re use a lot of components that we built custom for our clients. I would never tell an intern to use XYZ component without any comments to guide them on what is doing what etc.

1

u/qudat Dec 27 '18

I rarely write comments and think people that do aren't writing them very well.

0

u/[deleted] Dec 27 '18

The same things you'd see in any novice code vs professional code.

0

u/akshay-nair Dec 28 '18

If statements

0

u/silvenon Dec 28 '18

Returning boolean literals 😄