DEV Community

Cover image for Do's and Don'ts for Javascript Newbies
JelenaKalaba for JSGuru

Posted on • Updated on • Originally published at jsguru.io

Do's and Don'ts for Javascript Newbies

Since the day Brendan Eich created it, JS has had many makeovers, changes, additions, and frameworks added to its body. After a lifetime of turbulence, JS has been shaped into how we see it now in 2018, and yet there is much more growth awaiting in its future.

Today, I think the current state of JavaScript is best described by Atwood’s quote: “Any application that can be written in JavaScript will eventually be written in JavaScript.” Virtually anything you imagine can be written in JavaScript.

In this post, we will give you some tips on what to do, and what not to do, for both JS newbies and for those who have had some previous experience in this language.

There are some common rules of thumb when it comes to writing JavaScript code that should always be on your mind. Such rules relate to variable declarations, naming conventions, code commenting, striving to write cleaner code and keeping up with the JavaScript world in general. Let’s tackle some of these.

VARIABLES

When it comes to naming variables, using the camelCase rule is generally considered to be the best practice. That’s how we at JSGuru name them and it helps when the whole team uses this rule as it helps keep the code uniform.

It is also important to keep variable names short, concise, and descriptive. This should be adhered to as much as possible due to the fact that code is shared most of the time. The reader should be able to figure out what is stored in that variable or what it refers to without logging it in the console and backtracking your code. A good variable name should tell the reader about the context it is being used in within a chunk of code, and not refer to its value or purpose it is being used for from the user’s point of view. For example, “userAnswer” is a better variable name than “userInput”, as it clearly refers to, from a coding standpoint to a question asked earlier. You know exactly what input it refers to. Along the same lines, avoid using generic names such as “num” and “arr”, without at least appending it with information related to what it refers to, i.e. “selectedColors”. Along the same lines, “wantsSubscriptions” or “shouldRemember” is better than “trueOrFalse”. Use verbs and plural/singular to help indicate the value, instead of some acronym related to the type of value inside of a name.

Making the code cleaner and easier to read is considered a good practice. You can do this by placing the declaration of the variables at the beginning of your script, adding var or let in front of the first variable in the list, and only the first one. A comma can divide the rest, and to seal the deal place a semi-colon at the end of this declaration. Initialize variables first-hand when you declare them so that we avoid undefined values, and then do everything else.

LET OR CONST INSTEAD OF VAR

Since the adoption of ES6 (also known as the ECMAScript 2015) standard, variables should be declared using the keywords let and const. The reason behind abandoning the var keyword is that it should provide clearer meaning regarding the purpose of the variable and the context in which it is used. Const should generally hold references to values that will not be changed over time, even though, in cases of objects and arrays, it is allowed to mutate them. On the other hand, the keyword let indicates that a value might be changed or that a different value will be assigned to the particular variable. If you try to change the value of a const, JavaScript will tell you about it and help you avoid bugs. A good use case for const is storing a reference to a DOM element which you always want to keep in that variable. Keyword let is meant to be used with loops or mathematical algorithms, generally when its value is expected to vary. Variables declared with let and const aren’t hoisted, like those declared with var.

Body image - comments

COMMENTS

Have you ever found yourself in a situation where you looked at your old code only to see there are no comments related to it? Maybe you forgot to write them at the time or you accidentally postponed writing them and wound up forgetting to do so later. Whatever the case may be, now you’re in a situation where you’re looking at a bunch of hieroglyphs and start feeling overwhelmed because you don’t know where to start reading and understanding it. Writing clean code and adhering to good naming conventions can surely help, but a more complex chunk of code sometimes just simply needs one or two comments to help the reader understand it quicker. I remember returning to my code on multiple occasions and spending a good amount of time figuring out what I wrote and how exactly I went about it. This is when I learned the importance of writing some logic inside comments, just to serve as notes and help me understand it quicker in the future. You will, almost undoubtedly, find yourself in a situation where you are trying to understand the code you or someone else wrote and wishing there were some comments around it just to speed up the process of catching up.

Use this experience as a motivation to help you understand the importance of writing comments and keep it in mind next time you write some complex logic. Just write a short sentence capturing the essence of that chunk and trust me, you’ll thank yourself in the future. More importantly, whoever reads your code will be grateful as well. As a side note, it doesn’t hurt to make your comments humorous and positive since negativity and arrogance are counterproductive.

FORMATTING CODE

Formatting code can be tricky sometimes. To help you with this you should try out code linters like ESLint or JSLint (links to official site ). Both of these tools will help you have cleaner and better code in line with community standards. The least you can do is use whitespace and newlines to group your code into related chunks. This will make your code that much more readable and you will be able to make sense of it a lot quicker!

EFFICIENCY

In this section, we will remind you of the importance of general efficiency in programming. These are some common newbie pitfalls when it comes to Javascript.

1. Fetching DOM elements

If I got a dollar every time I saw document.getElementById scattered all around the code, I'd be a millionaire by now. If the DOM elements haven't actually changed, just store it in a variable an use it later down the road.

    let container = document.getElementById("someElementId"); 
        container.innerHTML = "<h1>Hello World!</h1>";
        container.addEventListener('mouseover', function(e) {
            this.innerHTML = "<h1>Hello Again!</h1>";
        })
Enter fullscreen mode Exit fullscreen mode

This is especially common with jQuery, we've all seen code like this:

    $('#button').addClass('actioned');
    $('#button').hover(function () { ... });
    $('#button').click(function () { ... });
Enter fullscreen mode Exit fullscreen mode

Instead of:

let button = $('#button');
    button.addClass('actioned');
    button.hover(function () { ... });
    button.click(function () { ... });
Enter fullscreen mode Exit fullscreen mode

What you should also keep on your mind is that fetching a DOM element by Id is the fastest method, so you should use it over other methods like document.getElementsByClassName, document.getElementsByTagName document.querySelector, etc. whenever you can.

2. DOM manipulation in the loop

This is an example of what not to do. Here we fetch a DOM element from within our loop. That means that we unnecessarily fetch it on every iteration and then subsequently we fill its inner HTML on every iteration as well.

function processArray(myArray) {
    for (let i = 0; i < myArray.length; i++){
      let div = document.getElementById("container");
      div.innerHTML = div.innerHTML + myArray[i];
      if (i < myArray.length - 1) {
        div.innerHTML = div.innerHTML + ", ";
      }
    }
  }
Enter fullscreen mode Exit fullscreen mode

The first thing we can do to optimize this code is to move the fetch statement above the loop. By doing this, we will not change the logic of this code block but give the code a significant velocity boost, while also decreasing the memory usage at the same time. To avoid the constant updating of the DOM with every iteration, as this is quite time-consuming, it would be a good idea to move the innerHTML out of the loop, as well.

    let container = document.getElementById("someElementId"); 
        container.innerHTML = "<h1>Hello World!</h1>";
        container.addEventListener('mouseover', function(e) {
            this.innerHTML = "<h1>Hello Again!</h1>";
        })
Enter fullscreen mode Exit fullscreen mode

These examples help us keep two things in mind when we talk about the code's efficiency. Firstly, to declare variables outside the loop and secondly to reduce DOM operations and make sure to use them intelligently.

In addition, it's important to remember to use let more then var when you're creating new variables.

However, global variables defined with let will not be added as properties on the global window object like those defined with var.

STRICT MODE

We are encouraged to use ''Strict Mode'' when our goal is to create more robust JavaScript code. Strict Mode changes (previously accepted) ''bad syntax'' into real errors. It means that trying to add values to the properties of a mistyped variable, which would create a new global variable in the regular mode, will now give you an error. In Strict Mode, any assignment with a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.

Staying up to date with the newest JavaScript standards is perhaps the most important thing on this list.

Firstly, your code will be modern and most likely written close to what industry standards are at the time. In addition by using the newest features, you and all other developers are encouraging and creating a need for browsers to implement those features and start supporting them out of the box. Right now, this is done with the help of transpilation tools such as Babel. If you’re not familiar with Babel, simply put, it “translates” newest JavaScript code into the format which browsers of today can understand. Babel reads your JavaScript code and compiles the newest features you used down to ES5, which all browsers can understand. Some browsers support ES6 features already, but using Babel and similar tools is still necessary because we want our JavaScript to be supported by all browsers and older versions as well.

For further information regarding Babel, I recommend you visit their website they have a great documentation which will get you started quickly.

What's more, you will make your life easier! Newest JavaScript features are amazing and they get better and better with each specification. They are an improvement to the old ways of doing things, i.e. using Promises or Async/Await to avoid being in a callback pyramid of doom.

Learning new things means leaving your comfort zone, but trust me, once you pick them up, you’ll never look back. Couple of features I’d recommend looking into are Array methods (map, reduce, filter), async/await, and of course, my favorite - String Literals.

It’s important to remember, you can always improve your coding skills and write cleaner code. It’s a marathon, not a sprint, so don’t feel overwhelmed if your code is not as clean as it can be. The most important thing is that it works! Over time, as you become more experienced and start adhering to industry standards, you will start writing cleaner code, and even then, there will be tons of room for improvement, just like there always is with everything! So don’t get discouraged, it just takes time.

I hope that you found this article helpful guide. Until next time, Jelena, signing out...

Top comments (21)

Collapse
 
tamouse profile image
Tamara Temple

Formatting code: Prettier is something folks should know about; it integrates with ESLint quite nicely, and can be added to most code editors pretty easily.

let, const, and var: In the examples given, doing let container = document.getElementByID('SomeId') is more of a signal to the developers that it will somehow be changing. In fact, the variable itself never changes, it still points to the same DOM element object, which is changing internally. This can be hugely confusing to realize that const container = document.getElementById('SomeId') ; container.innerHTML = "Hello" will work exactly the same way. Kyle Simpson (@getify) has a great discussion on this in YDKJS.

Also, don't completely discard var from your vocabulary as it still has uses; instead understand when and where to apply it.

The adage "use const until you can't" is a good one if everyone understands that.

Great article!

Collapse
 
jelenakalaba profile image
JelenaKalaba

Thank you.

Collapse
 
qm3ster profile image
Mihail Malo

Came here to make literally these two comments!

Collapse
 
juliavii profile image
juliavii

I come to the comments looking for an explanation about the let/const and why we should use them instead of var.

Can you clarify the difference for me?

Collapse
 
tamouse profile image
Tamara Temple

No where near as well as Kyle does: github.com/getify/You-Dont-Know-JS...

Collapse
 
nickytonline profile image
Nick Taylor

DOM elements are also global when accessed by ID. e.g. window['my_element_id'] or my_element_id #oldschoolweb

Collapse
 
nektro profile image
Meghan (she/her)

this is a big DON'T

Thread Thread
 
nickytonline profile image
Nick Taylor

For sure a bad idea. Just a little anecdote.

Thread Thread
 
nickytonline profile image
Nick Taylor • Edited

Here's some more web anecdotes

Collapse
 
mudlabs profile image
Sam

I like using snake_case for variables. It improved readability by distinguishing them form camelCasedMethods.

And when it comes to let vs const, use const everywhere until you can't.

Collapse
 
clintongallagher profile image
Clinton Gallagher

Consistency is also a Best Practice. When authoring an article and suggesting that Javascript developers use:

const container = document.getElementById("someElementId");

And then later in that same article the author uses:

let container = document.getElementById("someElementId");

It can elicit the pernicious WTF response followed by an emoji :-)

Collapse
 
enscripter profile image
Isaiah Griego

Like the article says the let syntax indicates that the value is to be changed which happens in the code snippet.

Collapse
 
qm3ster profile image
Mihail Malo

Formatting

Use Prettier. All formatting should be deterministic and fixable automatically.

const vs let

I see a lot of people using let for an object when they plan to mutate it.
Even if they understand it's unnecessary and just use it as a convention it's very confusing to other developers who look for the binding being redefined further on.

Collapse
 
dandevri profile image
Danny de Vries • Edited

On formatting code: using linters is a good way to make sure your code is consistent (e.g. in a team or contributions to open-source projects) but maybe more important is to look at recommended and standard configs to see which rules a specific linter enforces.

Collapse
 
reisclef profile image
Richard C • Edited

Nice. I only found out about let the other week when chatting with a colleague and seeing let used frequently. I'd been a var user since I originally picked up JavaScript. It's really nice to read best practice articles.

Anyone can learn to code, but coding well, and not picking up bad habits are hugely important.

Collapse
 
duduindo profile image
Eduardo Paixão

Nice :D

Collapse
 
kalaspuffar profile image
Daniel Persson

Great guide for javascript, but most thoughts apply to all languages independent of syntax.

Keep up the great work.

 
mr21 profile image
Thomas Tortorini

Because it's seems not standard :/ but you can easely recreate this idea:

document.querySelectorAll("[id]").forEach(el => window[el.id] = el);

Thread Thread
 
qm3ster profile image
Mihail Malo

It's totally standard.

Collapse
 
ddaypunk profile image
Andy Delso

Just getting into js and coming from Java. Great to know about the linters and Babel!

Collapse
 
jelenakalaba profile image
JelenaKalaba

You are welcome 💪😉