totn JavaScript

JavaScript: Comments

This JavaScript tutorial explains how to use comments in the JavaScript language with syntax and examples.

Description

In JavaScript, you can place comments in your code that are not executed as part of the code. These comments can appear on a single line or span across multiple lines. Let's explore how to comment your JavaScript code.

JavaScript supports the same commenting styles as the C and C++ languages.

Syntax

There are two syntaxes that you can use to create a comment in JavaScript.

Syntax Using // symbol

The syntax for creating a comment in JavaScript using // symbol is:

// comment goes here

A comment started with // symbol must be at the end of a line in your JavaScript code with a line break after it. This method of commenting can only span a single line within the JavaScript and must be at the end of the line.

Syntax Using /* and */ symbols

The syntax for creating a comment in JavaScript using /* and */ symbols is:

/* comment goes here */

A comment that starts with /* symbol and ends with */ can be anywhere in the JavaScript code. This method of commenting can span several lines within the JavaScript.

Example - Comment on a Single Line

Let's look at an example that shows how to create a comment in JavaScript that is on a single line.

For example:

Here is a comment that appears on its own line in JavaScript:

/* Author: TechOnTheNet.com */
var h = 100;

Here is a comment that appears at the end of the line in JavaScript:

var h = 100;   /* Author: TechOnTheNet.com */

or

var h = 100;   // Author: TechOnTheNet.com

Example - Comment on Multiple Lines

You can also create a comment that spans multiple lines in your JavaScript code.

For example:

/*
Author: TechOnTheNet.com
Purpose: To show a comment that spans multiple lines in JavaScript
*/
var h = 100;

This comment spans across multiple lines in JavaScript and in this example, it spans across 4 lines.

JavaScript will assume that everything after the /* symbol is a comment until it reaches the */ symbol, even if it spans multiple lines within the JavaScript code.

Example - Comment to Prevent Execution of Code

You can also use comments to prevent lines of JavaScript code from being executed.

For example:

// var h = 100;
tag = tag.toUpperCase();

This comment will prevent the variable h from being declared with a value of 100 in JavaScript.

You can also prevent multiple lines of JavaScript from being executed.

For example:

/*
var h = 100;
tag = tag.toUpperCase();
*/

By using the /* and */ symbols, we've prevented both lines of JavaScript code from being executed. In this example, both the declaration of the variable h will be prevented as well as the conversion of the variable called tag to uppercase.