Let’s Learn JavaScript • Lesson 6 • Statements and Comments

📅 August 18, 2017
The JavaScript interpreter executes lines of code one by one from top to bottom. A statement is a line of code that tells JavaScript what to do.

Statements contain keywords, which are words reserved by the JavaScript language for specific instructions. These keywords, combined with user data, form the statements that comprise a script.

Example of JavaScript statements.

Each statement begins with a new line and ends with a semicolon (;).

“Must I terminate statements with semicolons?”

JavaScript is “loose.” Meaning, you can get away with some things that other languages would throw a fit over. No, semicolons are not absolutely required every time, but they are recommended, and it is considered good programming practice to use them. Sure, your script might execute in the absence of semicolons, but it makes your code more difficult to read. There are also situations were semicolons are required in order to avoid ambiguity.

document.write('This statement ends with a semicolon.');

document.write('No semicolon here, but it still works.')

Both of these lines are simple enough. JavaScript executes each one whether or not a semicolon exists at the end of a statement. To avoid any potential problems, always use semicolons.

Code Blocks

Some statements consist of multiple lines. Groups of statements that belong together for their execution must be enclosed within curly braces { }. This tells the interpreter, “When you enter this block of code, execute all of these statements. They work together.”

A code block begins with a left brace ({) and ends with a right brace (}). Statements within the braces belong to the same code block. Statements outside the braces are not a part of the code block.

All statements within the braces is a code block that belongs to the switch statement. The var color statement at the top is outside the braces, so it is not a part of the switch statement.

Notice that code blocks do NOT end with a semicolon. So, do not put a semicolon after the closing (ending) brace. No errors occur and there is no penalty, but it is redundant and useless to do so. JavaScript knows that the ending brace terminates the multi-line statement.

However, individual statements within the code block must end with semicolons as seen in the image above.

Code blocks may be nested within code blocks. Here, an IF statement has its own code blocks relevant to the red case condition. If the color is red, then the if statement takes action where two outcomes are possible. Each outcome is represented by its own code block. Again, we do not terminate code blocks with semicolons as shown on the last line in the example here.

“What about case sensitivity?”

JavaScript is case sensitive, so this makes statements case sensitive too. Keywords are also case sensitive. Always have the browser’s developer tools open so you can view any errors due to improper case usage.

Lining Up Braces

You will encounter two main types of brace alignment:

Two common techniques for lining up braces.

In the example above, the top for loop lines up both braces at the same indentation level with the for keyword. The example below it places the opening brace at the end of the line while the closing brace exists on its own line indented to the same level as the opening statement.

“Which is correct?”

Neither is more correct than the other. Both will work. The difference is personal preference. Which do you like better? Syntactically, both styles mean the same thing.

Try both for yourself and use the method that feels most comfortable to you unless someone else’s coding guidelines dictate which to use.

However, use only ONE style throughout a script or program. Do not mix the two styles together within the same source code. This helps maintain consistent readability. If you mix styles, then it looks like different people collaborated on the same code — and they were unable to agree upon anything. This applies to cases if you must edit someone else’s code. Use the brace style that is already in use even if it is not your preference.

Readability and consistency produce code that is easier to understand.

 

Comments

One of the most useful but overlooked-due-to-laziness features of any programming language is the humble comment.

A comment allows you to add descriptive text to your code. This text is not interpreted or parsed in any way. It is simply a comment.

Example of comment usage. Multi-line comments and single-line comments are shown.

There are two types of comments:

  • Multi-line comments are enclosed within /* and */ and they may span multiple lines.
  • Single-line comments begin with // and end with the new line character.

In the image above, a multi-line comment acts as the header. It contains the name of the script, the date it was written, and a brief description. You can add whatever you like, including update and revision information.

Single-line comments are used to describe sections of code, such as where the variables are declared (we will look into variables later), and a few other key areas where lengthy descriptions are not needed.

In all cases, the JavaScript interpreter ignores all comments. They do not appear in the browser or console output.

Comments Are Useful

Comments are some of the most helpful programming aids available. Always comment your code with a brief description of its purpose, and comment code blocks involving operations that might take time to understand simply by reading the code.

A script might be fresh in your mind when you write it, but details will probably be fuzzy if you must ever return to the same code eight months later. What about somebody else who must maintain your code? How will he understand how your program works in order to update it? It takes time trying to figure out somebody else’s coding genius, and comments save time.

Comments help refresh your mind and help others understand your script without having to read every line.

If there is one programming rule to remember, it is this one:

Always comment your code. Always comment your code. Always comment your code.

No matter how “l33t” you think you are, you are never above commenting your code. Professional programmers are often required by their companies to comment their code in a specific manner for maintainability, and this is a good practice.

It is not a sign of weakness or “newbieness” to comment your code. It is smart. You will thank yourself many times over.

“What should I include in the comments?”

Keep comments concise. Do not state the obvious. The point of comments is to quickly update the reader about what the script does. Always include a title and a brief description. Coding dates are useful in order to get an idea of how long a program has been in operation. Revision dates with update information are also helpful.

Within the code, use comments to describe lengthy sections of code that might take too long to understand when read statement by statement.

If coding the same project without others, avoid using the comments as a chat forum. Nobody needs to know that you ordered pizza on line 3003. Keep comments relevant to the code.

Do Not Overcomment

Avoid the newbie mistake of commenting every line. Unless you are new to programming and still learning, this is a pointless, unnecessary waste of time.

Example of overcommenting. Almost every line is commented. This is a waste of extra typing that makes the code harder to read.

Do not comment the obvious. People who read your code will be other programmers. They know what keywords perform what operations, so you do not need to add comments that read, “This is an if statement,” “This is a for loop,” or “This is an ending brace.” Programmers know what these things are, so there is no need to explain them.

It is far more effective to add a single-line comment to a lengthy code block that reads, “This section determines what to do based upon the current user” and write the code block clearly enough so the programmer can follow the details simply by reading the code itself.

Your code should be readable as written. If it is not and you find yourself adding too many comments to explain its operation, then your code is too complex and obfuscated, and you have a problem. Rewrite your code in a simpler-to-understand manner and use fewer comments. You might be the one who has to edit the code in the future. Would you want to unravel messy code a year from now? Do it right the first time.

Readability is more important than impressing your friends with hacks.

“But I don’t wannaaaaaa!”

This is the mark of an amateur.

“Why bother? My code changes as I write it, so it will not match the comments anyway.”

Not entirely true. Comments help you stay focused. By adding comments as placeholders for sections of code first, you will remember to fill them in later and not become sidetracked.

Almost always, your code will change as you write it to the point where the original comments will need revising. Update your code, test it, then update the lengthier comments to reflect the changes. Starting comments provide a goal. A focus. A point you can return to in order to remind yourself of the core operation your program must provide. By staying focused, you can help reduce mind drift.

“But I’ve seen one-liner coding hacks on the Internet without comments, and they work! Wow! That’s impressive. I wannabe l33t 2!”

One-liners — multiple statements written on a single line of code that perform a given task normally requiring several lines of code — do not prove the rule. Readability is more important than how clever you can arrange statements.

There was a time in early computing history when memory was scarce and expensive, so machine language coders had no choice but to cram as much as possible onto a single line. But these days, computing power and memory are abundant, so those restrictions no longer apply.

Write your code so that you or somebody else can easily read and understand it days, weeks, or months later. You will be grateful that you did.

One-liners often take too much time to understand. They have their place in some situations, but not all of the time. Often, it requires many comments to explain a one-liner. If that is the case, then why not rewrite the one-liner into multiple, easy-to-grasp statements where the language itself explains the code?

Comments Are Not Private

Avoid placing your name, location, contact information, email address, or any other personal details in your code comments. This is fine for personal code only you will see, but any code destined for the Internet should be scrubbed clean of anything that identifies you.

Comments in HTML pages, style sheets, and scripts can be opened and viewed by anybody on the Internet. It’s easy! Any comments you write will be world-readable and open to the eyes of all who bother to view the source.

Since anyone can view a site’s code, some creative web designers have sprinkled jokes and teasers within their comments for the amusement of others.

Other web designers use comments as a filtering mechanism to separate the clever people from the morons by adding comments something to the effect of, “If you are reading this, then you demonstrate more initiative and brain power than 99.9% of the ignorant population. I want to talk to you! Please contact me at ________@________.______”

Clever stuff indeed!

Your Code is Art

Comments need not be boring. You can add fancy bars, borders, tables, and even ASCII art to decorate your code in order to improve readability.

 

Fancy, styled comments breathe life into your code.

The example above uses fancy text and ASCII art in the main header. When used sparingly, the effect is impressive and makes otherwise bland code more interesting to peruse.

The styled title was created using figlet.

figlet -f script 'Dr. Chop'
figlet -f shadow 'Detector'

The ASCII art cow was created using cowsay.

cowsay -f cower 'Dr. Chop'

Then, copy and paste the terminal output results into the comments area of the source code.

The Mini-Map

Many text editors, such as gedit, provide a mini-map (also called an overview map) in the right-hand side of the text editor. This is a graphical representation of the entire source code file.

gedit overview map (highlighted in yellow on the right-hand side). A miniature representation of the entire file is available for faster navigation.

You can scroll up and down the mini-map in order to jump to different areas quickly.

Comments are helpful with the mini-map. By adding comment sections to code blocks, such as function declarations or objects, those commented areas will appear as colored sections in the mini-map. Simply drag the map’s cursor to that commented region to jump to that part of the code. This saves the time and hassle of scrolling up and down through the code to find a certain section. Just look for a particular comment block and go.

Conclusion

Your code should look exciting!

Short scripts do not require much commenting, but lengthy programs do. Fancy titles, ASCII art, bordered comment blocks, stars, patterns, consistent indentation, brace alignment, and other ideas that help decorate your essential code and comments can turn a drab script of lone statements into a coherent showpiece. When handled properly, comments are as fun to write as the code itself.

Experiment, be creative, and have fun!

Advertisements

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: