SoFunction
Updated on 2025-04-06

Deep understanding of syntax and code structure in JavaScript

Overview

All programming languages ​​must comply with specific rules before they can run. This set of rules that determine the correct structure of a programming language is called syntax. Many programming languages ​​consist mainly of similar concepts with syntax changes.

In this tutorial, we will introduce many rules and conventions for JavaScript syntax and code structure.

Functionality and readability

When starting with JavaScript, functionality and readability are two important reasons to focus on syntax.

Some syntax rules are required for JavaScript functionality. If they are not followed, the console will throw an error and the script will stop executing.

Consider the syntax error in "Hello, World!". program:

// Example of a broken JavaScript program
("Hello, World!"

This code example lacks the close bracket and does not print the expected "Hello, World!" to the console and the following error will appear:

Uncaught SyntaxError: missing ) after argument list

The missing ")" must be added before the script continues to run. Here is an example of how JavaScript syntax errors can corrupt scripts, because the correct syntax must be followed in order to run the code.

Some aspects of JavaScript syntax and formatting are based on different schools of thought. That is, some style rules or choices are not mandatory and do not cause errors when running the code. However, there are many common conventions worth following, as developers between projects and code bases will be more familiar with this style. Following common practices can improve readability.

Consider the following three examples of variable assignment.

const greeting="Hello";         // no whitespace between variable & string
const greeting =       "Hello"; // excessive whitespace after assignment
const greeting = "Hello";       // single whitespace between variable & string

Although the three examples above function exactly the same in the output, the third option greeting = "Hello"; is by far the most commonly used and readable way of writing code, especially when considered in the context of large programs.

It is important to keep the style of the entire coding project consistent. From one organization to another you will encounter different guidelines, so you must be flexible, too.

We will introduce some code examples below to make you familiar with the syntax and structure of JavaScript code and refer to this article if you have any questions.

blank

Spaces in JavaScript are composed of spaces, tabs and line breaks (press the ENTER keyboard). As mentioned earlier, JavaScript ignores too many spaces outside the string and spaces between operators and other symbols. This means that the following three variable assignment examples will have the exact same computed output:

const userLocation      =    "New York City, "     +  "NY";
const userLocation="New York City, "+"NY";
const userLocation = "New York City, " + "NY";

userLocation will stand for "New York City, NY". No matter which of these styles is written in the script, they will not have an impact on JavaScript, whether the spaces are written in labels or spaces.

A good rule of thumb to follow the most common blank conventions is to follow the same rules as math and linguistic grammar.

A notable exception to this style is in the process of allocating multiple variables. Note the position of = in the following example:

const companyName         = "DigitalOcean";
const companyHeadquarters = "New York City";
const companyHandle       = "digitalocean";

All assignment operators (=) are arranged in a row, with spaces after the variable. This type of organizational structure is not used in every code base, but can be used to improve readability.

JavaScript ignores unnecessary newlines. Typically, additional line breaks are inserted above the comment and after the code block.

parentheses

For keywords such as if, switch, and for, spaces are usually added before and after brackets. Observe the following comparison and loop examples.

// An example of if statement syntax
if () { }
// Check math equation and print a string to the console
if (4 < 5) {
    ("4 is less than 5.");
    }
// An example of 
for loop syntaxfor () { }
// Iterate 10 times, printing out each iteration number to the console
for (let i = 0; i <= 10; i++) {
    (i);
    }

If statements and for loops have spaces on each side of the bracket (but not inside the bracket).

When the code belongs to a function, method, or class, the brackets will touch the corresponding name.

// An example 
functionfunction functionName() {}
// Initialize a function to calculate the volume of a cube
function cube(number) {
    return (number, 3);
}
// Invoke the function
cube(5);

In the example above, cube() is a function, and the bracket() pair will contain arguments or arguments. In this case, the parameters are numeric or 5, respectively. Although cube() with extra space is valid, since the code will perform as expected, it is hardly visible. Putting them together helps easily associate function names with parentheses pairs and any associated passed parameters.

semicolon

A JavaScript program consists of a series of instructions called statements, just as a written paragraph consists of a series of sentences. Although the sentence will end with a period, the javascript statement usually ends with a semicolon (;).

// A single JavaScript statement
const now = new Date();

If two or more statements are adjacent, they must be separated by semicolons.

// Get the current timestamp and print it to the console
const now = new Date(); (now);

If the statement is separated by a newline character, a semicolon is optional.

// Two statements separated by newlines
const now = new Date()
(now)

A safe and universal convention is to separate statements with semicolons without considering line breaks. In general, it is considered good practice to include them to reduce the likelihood of error.

// Two statements separated by newlines and semicolons
const now = new Date();
(now);

A semicolon is also required between the initialization, conditions, and increments or decrements of the for loop.

for (initialization; condition; increment) { 
   // run the loop
}

A semicolon is not included after any type of block statement, such as if, for, do, while, class, switch, and function. These block statements are contained in braces. Please note the example below.

// Initialize a function to calculate the area of a square
function square(number) {
    return (number, 2);
}
// Calculate the area of a number greater than 0
if (number > 0) {
    square(number);
}

Note that not all codes enclosed in braces end with semicolons. Objects are enclosed in braces and end with semicolons.

// An example object
const objectName = {};
// Initialize triangle object
const triangle = {
    type: "right",
    angle: 90,
    sides: 3,
};

It is widely accepted that each JavaScript statement after it is a semicolon, which end in braces.

indentation

Technically, a complete JavaScript program can be written in one line. However, this can quickly become very difficult to read and maintain. Instead, we use line breaks and indents.

Below is an example of a conditional if/else statement, which is either written on a line or is indented with newlines and indented.

// Conditional statement written on one line
if (x === 1) { /* execute code if true */ } else { /* execute code if false */ }
// Conditional statement with indentation
if (x === 1) {
    // execute code if true
    }else {
        // execute code if false
        }

Note that any code contained in the block is indented. Indentation can be done with two spaces, four spaces, or by tab. The use of tabs or spaces depends on your personal preferences (for individual projects) or organization's guidelines (for collaborative projects).

Like the example above, including the opening brace at the end of the first line is a regular way to construct JavaScript block statements and objects. Another way you might see block statements written is to use braces on their own lines.

// Conditional statement with braces on newlines
if (x === 1){
    // execute code if true
    }else{
    // execute code if false
    }

This style is not as common in JavaScript as it is in other languages, but it is not unheard of.

Any nested block statements will be further indented.

// Initialize a functionfunction isEqualToOne(x) {
    // Check if x is equal to one
    if (x === 1) {        // on success, return true
        return true;
    } else {      return false;
    }
}

Correct code indentation is essential to maintain readability and reduce confusion. An exception to remember this rule is that the compressed library will remove unnecessary characters, thus rendering a smaller file size to speed up page loading times (such as and).

Identity ID

The names of variables, functions, or attributes are called identifiers in JavaScript. Identifiers are composed of letters and numbers, but cannot contain any symbols other than $ and u, nor can they begin with numbers.

case sensitive

These names are case sensitive. The following two examples myvariable and myvariable will refer to two different variables.

var myVariable = 1;
var myvariable = 2;

The convention for javascript names is written in camelcase, which means that the first word is lowercase, but each word that follows begins with a capital letter. You can also see global variables or constants written in capital letters, separated by underscores.

const INSURANCE_RATE = 0.4;

The exception to this rule is the class name, which is usually written for every word starting with a capital letter (pascalcase).

// Initialize a class
class ExampleClass {
    constructor() { }
}

To ensure that the code is readable, it is best to use significantly different identifiers in the program file.

Keep keywords

Identifiers cannot be composed of any reserved keywords. Keywords are words with built-in features in JavaScript, such as var, if, for and this.

For example, you cannot assign a value to a variable named var.

var var = "Some value";

Since JavaScript understands var as a keyword, it will cause syntax errors:

SyntaxError: Unexpected token (1:4)

The above is a detailed content of deeply understanding the syntax and code structure in JavaScript. For more information about syntax and structure in JavaScript, please pay attention to my other related articles!