DEV Community

Cover image for JavaScript Best Practices for Beginners
Raghav Khanna
Raghav Khanna

Posted on

JavaScript Best Practices for Beginners

Use === Instead of ==

JavaScript utilizes two different kinds of equality operators: === | !== and == | != It is considered best practice to always use the former set when comparing.

"If two operands are of the same type and value, then === produces true and !== produces false." - JavaScript: The Good Parts

However, when working with == and !=, you'll run into issues when working with different types. In these cases, they'll try to coerce the values, unsuccessfully.

Don't Use Short-Hand

Technically, you can get away with omitting most curly braces and semi-colons. Most browsers will correctly interpret the following:
'''js

if(someVariableExists)
x = false

However, consider this:

if(someVariableExists)
x = false
anotherFunctionCall();
One might think that the code above would be equivalent to:

if(someVariableExists) {
x = false;
anotherFunctionCall();
}
Unfortunately, he'd be wrong. In reality, it means:

if(someVariableExists) {
x = false;
}
anotherFunctionCall();

'''
As you'll notice, the indentation mimics the functionality of the curly brace. Needless to say, this is a terrible practice that should be avoided at all costs. The only time that curly braces should be omitted is with one-liners, and even this is a highly debated topic.

if(2 + 2 === 4) return 'nicely done';
Always Consider the Future
What if, at a later date, you need to add more commands to this if statement. In order to do so, you would need to rewrite this block of code. Bottom line - tread with caution when omitting.

The Fastest Way to Build a String

Don't always reach for your handy-dandy "for" statement when you need to loop through an array or object. Be creative and find the quickest solution for the job at hand.

Comment Your Code

It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can't easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment important sections of your code.

Embrace Progressive Enhancement

Always compensate for when JavaScript is disabled. It might be tempting to think, "The majority of my viewers have JavaScript enabled, so I won't worry about it." However, this would be a huge mistake.

Have you taken a moment to view your beautiful slider with JavaScript turned off? (Download the Web Developer Toolbar for an easy way to do so.) It might break your site completely. As a rule of thumb, design your site assuming that JavaScript will be disabled. Then, once you've done so, begin to progressively enhance your layout!

Always Use Semicolons

Technically, most browsers will allow you to get away with omitting semi-colons.

var someItem = 'some string'
function doSomething() {
return 'something'

Self-Executing Functions

Rather than calling a function, it's quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function.

Top comments (15)

Collapse
 
miketalbot profile image
Mike Talbot ⭐

The article could do with the code being in Markdown code escapes:



   ```js
   
   code goes here

   ```


  • I hate semicolons - unless you are using something like Prettier - most people add too many. A fanatical debate of course, but I don't use them.

  • Perhaps an example of building a string using Array.join()?

Collapse
 
erraghavkhanna profile image
Raghav Khanna

Sure

Collapse
 
jozsefsallai profile image
József Sallai

I agree with most of these, except the semicolon one. It's perfectly fine if you don't use them.

I think what this article is missing is a section about consistency. Double quotes vs single quotes? Semicolons or not? It doesn't matter as long as you're consistent with it. Also, you could perhaps suggest using ESLint.

Collapse
 
jamesthomson profile image
James Thomson

I'd argue that beginners should use semicolons to understand the implications of writing without them.

For the most part you shouldn't have any issues, but there are some gotchas that will trip up beginners.

For example,

const test = () => {
 return 
 {
  ok : true
 }
}
console.log(test())

In the eyes of a beginner, what do they expect this code to do? If they're not used to writing with semicolons they might expect it to return the object, but instead they get undefined.

I do 100% agree about consistency. Whichever way you go, be consistent.

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Agreed!

Collapse
 
erraghavkhanna profile image
Raghav Khanna

Thanks for the suggestion. I'll include that too..
Have a good day😋

Collapse
 
xavierbrinonecs profile image
Xavier Brinon

That's what standardjs.com/ and prettier.io/ are for I guess.

I tend to format code the way I like before starting reading it, so the original styling is gone anyway.

Devs should focus more on making the code readable to other humans first; spend some time finding the most relevant names. Show the intent and make the context of the code obvious. The comments should be about the why not the how. Always name your functions. Be as declarative as possible, don't try to go for the creative solution if that makes it unreadable (I assume everybody should know how to read an Array.reduce... 👍🏻 ).

Technically you should use === when you are not sure about the types of what you are comparing. If you know them, == is perfectly fine. Based on the specs === switches to == when the 2 values are of the same types. I linter forces the === anyway 🤷🏻‍♂️

I don't see why an IFFE is best practice btw.

A best practice I like to add is to follow the new features appearing every year as they tend to make the code more declarative. I get sad everytime I see a index === -1.

Collapse
 
etienneburdet profile image
Etienne Burdet • Edited

You can write excellent spec compliant code and omit semi-colons. See : 

It's a preference, not a bad/good practice. The debate is endless, nobody ever won it. It's down to preferences.

Collapse
 
richardlikestea profile image
Richard Shepherd

A useful reference. Thank you for sharing.

Collapse
 
erraghavkhanna profile image
Raghav Khanna

If you want to add something please go ahead.
You can write anything in comments and i will add it to the post!! Cheers😋

Collapse
 
kaleman15 profile image
Kevin Alemán

As you'll notice, the indentation mimics the functionality of the curly brace.
First, what indentation? I see every line at the same indentation level. And second, what do you mean?

Collapse
 
nombrekeff profile image
Keff

It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. What happens when you return to the project months later, only to find that you can't easily remember what your line of thinking was. Or, what if one of your colleagues needs to revise your code? Always, always comment on important sections of your code.

I understand your point, but I tend to not agree with this because code should explain itself, otherwise, we would use Machine code directly, for me, Programming languages (at least high-level ones) tend to be quite readable already if you code in such a way that is understandable. If not, you might want to look into clean code examples and principles, they can make a huge difference.

"Good code should explain itself with the need for few comments"

Another bad thing about comments IMHO is that you're creating a new "dependency" that you need to update whenever you edit that code, if you forget to update the comment after updating the code it will result in conflicting explanations, on one side the comment says the code does one thing but the code tells you it does another thing.

As you pointed out, I prefer using comments to explaining the line of thought of complex functionality, were just the code must not explain it correctly, or it uses an abstraction of some kind, which cannot be interpreted just by looking at the code.

I think comments can be useful, but it is not a sign of good code IMO.

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Totally agree:

     function process(b) {
       //Get the angle
       let a = b.rotation
       //Rotate
       a += Math.PI
       //Return the rotated angle
       return a
   }

Or

     function getReverseAngle(gameObject) {
          return Math.PI + gameObject.rotation;
     }
Collapse
 
willemodendaal profile image
Willem Odendaal

Do people really use the web nowadays with javascript disabled? Maybe I've just been web-devving so long that I don't think of that as an option anymore.

Collapse
 
nombrekeff profile image
Keff

Doubt it, although some institutions or old school people might still use it. I know people that have it disabled on mail clients, as well as automatic image rendering...