When writing blocks of code, we need to consider how to best leverage the features of a programming language to create clean and structured code. It means being able to create clear and readable code and organize files and folders in a logical and intuitive way.
But first of all let's have a look on what actually blocks of code are made of.
A statement example is the
alert() method, which shows the message "Hello, world!".
In our code, we can have as many statements as we want, but it's important to write them on separate lines, in order to make the code more readable:
1alert('Hello, world!');2alert('🖐️ 🌐');
As you can see from the example above, statements are usually separated with semicolon.
The code below, for instance, works perfectly fine:
In this example, the line break is considered as an 'implicit' semicolon, which will be inserted automatically.
There are also cases where a new line does not mean a semicolon:
They represent a great way to describe what the code does to give more insights on the complex areas of your codebase. You can leave comments also to remind yourself or other developers to refactor some particular functions in the near future, or simply to temporarily disable a part of code.
It starts with two forward slash characters
// and anything else that comes after it is a comment.
The location of this type of comment depends on your preference of codebase style.
It can occupy an entire line of its own, or follow a statement.
Here are few examples on this type of comment:
1// This comment occupies an entire line2alert('Example where comment occupies an entire line!');
1// This comment follows the statement2alert('Example where the comment follows the statement');
This type of comment starts with a forward slash and an asterisk
/* and ends with an asterisk and a forward slash
Anything that you include inside the two asterisks will be ignored when the code will run.
1/*2This is a multiline comment.3It spans on two different lines.4*/56alert('Hi');7alert('There');
Keep in mind that you cannot have multiline comment inside another multiline comment.
1/*2 /* This is a nested comment! */3*/4alert('No nested comments!');
The above code, for instance, will return an error
Uncaught SyntaxError: Unexpected token '*'.
Eslint and Prettier
Going over your code base and fixing missing commas, semicolons or broke comments can be time consuming. Nowadays, this process can be automated with tools like Eslint and Prettier.
Even if it can be frustrating in the beginning to, not only setup, but also to fix all the highlighted warnings that you might get, in the long time it will be worth it.
It will help you prevent bugs that might originate by typos, comments not properly closed and many more common errors that tend to happen when coding. So just start with one configuration and modify it to fit your personal coding style.