JavaScript syntax is the set of rules concerning how the code blocks should be constructed for proper execution.

Basic Syntax

Lines 2 and 5 below are JavaScript statements. Each statement ends in a semi-colon (;), and is an instruction to be executed by the browser. The semi-colon tells the browser that the particular instruction has ended and the next line of code will be a new instruction.

Lines 1 and 5 are comments, not statements. They are merely placed as notes as to what the code does. They do NOT show in the browser.

				
					// place text in the #my_intro element
document.getElementById('my_intro').innerHTML = 'Hello World';
// place text in the #my_outro element
document.getElementById('my_outro').innerHTML = 'Goodbye World';
				
			

Several “lines” of code can technically sit on the same line as long as each instruction ends with a semi-colon (it is NOT an actual new line that starts a new line of code).

				
					a = 2; b = 3; c = a + b;
				
			

Unlike a statement, a JavaScript function does NOT end with a semi-colon. But each statement within WILL end with a semi-colon.

				
					function my_function() {
    // statements go here
}
				
			
				
					function my_function() {
    document.getElementById('my_intro').innerHTML = 'Hello World';
    document.getElementById('my_outro').innerHTML = 'Goodbye World';
}
				
			

Double or Single Quotes

When using JavaScript, single or double quotation marks are acceptable and work identically to one another. Choose whichever you prefer, and stay consistent. However, if you are writing a string to the page that contains either a double or single quote, you will need to either use the opposite set, or place a backslash prior to the quote.

				
					document.getElementById('my_output').innerHTML = "Johnny's World";
				
			
				
					document.getElementById('my_output').innerHTML = 'Johnny's World';
				
			

Case Sensitive

JavaScript is a case-sensitive language. What this means is that the two following statements are NOT the same.

				
					let firstname = 'Johnny';
// is NOT the same variable as...
let firstName = 'Johnny';
				
			

Camel Case, Hypens, and Underscores

When creating variables, there cannot be a space. So if you have a longer, descriptive variable, you need to use one of the following methods.

				
					// camel case (each word after the first is capitalized)
let firstName = 'Johnny';
// hypens
let first-name = 'Johnny';
// underscores
let first_name = 'Johnny';
				
			

White Space

JavaScript ignores multiple spaces and all extra whitespace. White space to your script to make it more readable.

The following lines are equivalent. Remember, what tells the browser that a particular JavaScript statement has ended is the semi-colon (;), not white space or an actual line break.

				
					let firstName = 'Johnny';
let first-name =        'Johnny';
let first_name = 
'Johnny';