JavaScript Syntax

JavaScript grammar

The syntax of a programming language is the formal grammar of that language. The syntax of a computer language is the set of rules that defines the combinations of characters that are considered to be correctly structured expressions or statements in that language. Expressions and statements (phrases) are composed of tokens (words), i.e. strings of characters with identified meaning. The lexical grammar is the part of the syntax that specifies how characters form tokens. Tokens can be:

Programming code may also include (in or outside statements and expressions) line terminators, comments and white spaces (spaces, tabs, line feeds, etc).

Throughout the rest of this tutorial, statements, expressions and the different tokens will frequently recur and will be explained in detail.

Expressions

An expression is a unit of code that evaluates to a value. An example of an expression is 3 + 6 in which 3, + and 6 are tokens. Expressions are usually part of statements. In the statement let a = 2;, a = 2 is an expression and token let is a keyword, token a is an identifier, token = is an operator, token 2 is a literal and token ; is a separator. The expression and the statement also include white space (spaces).

Statements

Like any computer program, a JavaScript is a list of instructions that can be executed by a computer to produce some desired output. In JavaScript these instructions, or statements are generally executed, one by one, top down and from left to right. A single statement may span multiple lines, optionally ending with a semicolon. If a statement is not ended by a semicolon, the JS engine automatically interprets an ending semicolon at run-time, based on what constitutes correct JS syntax. This is called Automatic Semicolon Insertion (ASI). A statement may follow an other statement on the same line if separated by a semicolon. It is often recommended as good practice to end all statements with a semicolon and not to start a new statement on a line were another ended. A semicolon directly following the end of a previous statement constitutes an empty, idle statement.

While executing JavaScript, the engine ignores superfluous white spaces and line terminators. These are white spaces and line terminators not really mandatory to comply with JS syntax rules. White spaces (space bar, tab key) and line terminators (return key) can be added to your script to make it more readable. Be aware that different code/text editors may interpret tabs and returns in different ways.

JavaScript statements can be grouped together in block statements (or compound statements or simply "blocks"), enclosed by a pair of braces (curly brackets) "{}". Block statements are typically used in association with functions, conditional statements and loop statements. A block can also be empty, e.g. to provide an idle statement where a statement is required. Ending a block statement with a semicolon ({};) is not common practice (in fact, the semicolon adds an empty statement after the block statement).


// A conditional statement with two code blocks:
if (doorIsOpen) {
  closeTheDoor = true;
  console.log(
    'Door is open. Door must be closed'
  );
} else {
  closeTheDoor = false;
  console.log('Door is closed, no action needed');
}	

JavaScript is case sensitive. JS developers generally use an informal naming convention for variables and functions. Later some of these informal rules will be discussed.

Identifiers

Identifiers are names that identify variables, functions, or object properties.

In JavaScript identifiers are case-sensitive and valid identifiers are only allowed to contain letters, $, _, and digits (0-9), but may not start with a digit.

Keywords

Statements may use keywords, such as if, else or let. These keywords are reserved and may not be used for identifiers, such as for variable names, function names or argument names. Here is a list of reserved keywords.

Future ECMAScript versions will likely introduce new syntax, including some new keywords. In strict mode also these possible future keywords are reserved. Here is a list of future reserved keywords.

Comments

Comments can be included in the JavaScript to explain the overall purpose and working of the script, why some choices were made, the name of the developer, the source where the developer found the used solution, etc. Comments can be very useful when code is developed in teams or when code needs to be updated, maintained or altered in the future. Making portions of code (temporarily) a comment prevents this code from being executed and is often used in debugging.

Any code between // and the end of the line will be considered a comment and ignored at execution of the script. Any code between /* and */, optionally over multiple lines, will be considered a comment (a comment block) and will be ignored at execution of the script.


/* This portion of code
is a comment block.
It will be ignored at execution
of the code.
Now let's end the comment block: */

let exampleVariable; // from here, up to the end of this line is a comment.
exampleVariable = "exampleValue"; // from here, up to the end of this line is a comment.
// console.log("This line of code will never be executed."); 	

Code should be as self-descriptive as possible. For example, names of variables or functions should be self-descriptive. It should not be necessary to add a comment to explain what a variable represents or what a function does. However, how a portion of code works might need a comment, especially when the working is complex and not directly obvious.

In the many code examples in this tutorial an abundance of comments are included. They are used to provide references, context and explanation to you, the reader. Of course this is not the same way as how comments are used in production code.

Minification

White spaces, line terminators and comments are used to make code easier to read and understand for humans. The downside is that it makes the file size unnecessary large for computers. This affects loading time and computer memory in a negative way. JS-files often have a "developers version" and a "minified version". In the minified version unnecessary semicolons, white spaces and line terminators as well as comments are removed. Also variable and function names are shortened, and shorter alternative syntax is used, if possible. The minified version is the version that is actually uploaded to the web server and attached to the web page(s).

There are build automation tools available to automatically compress JS-code. Just google "minify js", and you'll find plenty. Minifiers are often integrated in an IDE.