JS Syntax

Understanding the JavaScript Syntax

The syntax of JavaScript is the set of rules that dictate how to write a properly structured JavaScript program.

JavaScript programs consist of statements that are written within the <script></script> HTML tags on a web page, or inside an external JavaScript file with a .js extension.

The following example illustrates what JavaScript statements look like:

var x = 5;
var y = 10;
var sum = x + y;
document.write(sum); // Prints variable value

You will understand each of these statements in the following chapters.


Case Sensitivity in JavaScript

JavaScript is case-sensitive. This means that variables, keywords, function names, and other identifiers must always be written with the same capitalization.

For instance, the variable myVar must be typed as myVar and not as MyVar or myvar. Likewise, the method name getElementById() must be typed exactly as it is, not as getElementByID().

var myVar = "Hello World!";
console.log(myVar);
console.log(MyVar);
console.log(myvar);

If you check the browser console by pressing the f12 key on your keyboard, you'll see a line that looks like this: "Uncaught ReferenceError: MyVar is not defined".


JavaScript Comments

A comment is simply a line of text that the JavaScript interpreter completely ignores. Comments are usually added to provide additional information about the source code. They help you understand your code after some time has passed and also assist others who are working on the same project.

JavaScript supports both single-line and multi-line comments. Single-line comments start with a double forward slash (//), followed by the comment text. Here's an example:

// This is my first JavaScript program
document.write("Hello World!");

Meanwhile, a multi-line comment starts with a slash and an asterisk (/*) and ends with an asterisk and slash (*/). Here's an example of a multi-line comment.

/* This is my first program 
in JavaScript */
document.write("Hello World!");