r/javascript • u/FunPieceOfPaper • 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.
72
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.jsfile 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
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
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
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
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
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:
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.
Not following any sort of style/not linting your code, as in you sometimes put spaces between arguments, other times you don’t.
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.
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).
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:
Using fat arrow and
functioninterchangeably, not understanding scope in general.Using
==outside of very rare casesNot considering falsely value when writing functions (is
0valid compared tonull)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
1
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
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
_thisorthator whatever. You could also use bind or whatever.3
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
1
u/svtguy88 Dec 28 '18
On a related note, if you do use bind, do you still have access to whatever
thiswould have been inside the function? I'll admit that I still usevar that = thisfrom time to time...1
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
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
14
Dec 27 '18
The difference and use of
apply,bind,calland 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
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.
→ More replies (5)0
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.
0
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
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
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
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
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
2
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
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
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
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
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
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
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
1
u/deadlyicon Jan 02 '19
Here is a great comment https://github.com/endlesssoftware/sqlite3/blob/master/os.h#L133
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.
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
1
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
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
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
1
Dec 28 '18
The same as in any other lang. Verbosity, using loops, failed logic and the lack of tests.
1
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
1
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
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:
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
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,reduceandfilterare 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-loopsand 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
.filterhere instead of this for loop0
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
that's a borderline silly alternative to
for (let p of [async1, async2, async3]) { await p }? I thought the aim was "readability"
you can't actually await the operation, making it non-viable as a complete solutionI'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
npromises sequentially vs waiting for all of them in parallel. This code should simply beawait 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
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
Maptype. It was designed explicitly for this purpose.
1
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
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
0
0
0
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.