Home > Web Front-end > JS Tutorial > Get a deeper understanding of syntax and code structure in JavaScript

Get a deeper understanding of syntax and code structure in JavaScript

青灯夜游
Release: 2019-11-25 14:56:15
forward
2756 people have browsed it

All programming languages ​​must follow specific rules in order to run. The set of rules that determine the correct structure of a programming language is called its grammar. Many programming languages ​​consist primarily of similar concepts with syntactic variations.

Get a deeper understanding of syntax and code structure in JavaScript

#In this tutorial, we will cover the many rules and conventions of JavaScript syntax and code structure. [Related course recommendations: JavaScript Video Tutorial]

Functionality and Readability

When starting to use JavaScript , functionality and readability are two important reasons to pay attention to grammar.

Some syntax rules are required for JavaScript to function. If you don't follow them, the console will throw an error and the script will stop executing.

Consider the grammatical errors in "Hello, World!" Program:

// Example of a broken JavaScript program
console.log("Hello, World!"
Copy after login

This code example is missing the closing bracket and does not print the expected "Hello, World!" to the console, and the following error will occur:

Uncaught SyntaxError: missing ) after argument list
Copy after login

must be added before the script can continue running Lack of")". This is an example of how JavaScript syntax errors can break a script because correct syntax must be followed in order for the code to run.

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 will not cause errors when running the code. However, there are a number of common conventions worth following as developers across projects and codebases will become more familiar with this style. Following common conventions improves 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
Copy after login

Although the three examples above function exactly the same in the output, the third option greeting = "Hello"; is by far the most common and readable way to write code, especially on large when considered within the context of the program.

It is important to maintain a consistent style throughout your coding project. You'll encounter different guidelines from one organization to another, so you'll have to be flexible as well.

We will introduce some code examples below so that you can become familiar with the syntax and structure of JavaScript code and refer to this article when you have questions.

White space

White space in JavaScript consists of space, tab, and newline characters (press ENTER on the keyboard). As mentioned before, JavaScript ignores excessive whitespace outside strings and whitespace between operators and other symbols. This means that the following three variable assignment examples will have the exact same calculated output:

const userLocation      =    "New York City, "     +  "NY";
const userLocation="New York City, "+"NY";
const userLocation = "New York City, " + "NY";
Copy after login

userLocation will represent "New York City, NY" regardless of which of these styles is written in the script. There will also be no effect on JavaScript, whether the spaces are written with tabs or spaces.

A good rule of thumb for following the most common whitespace conventions is to follow the same rules as for math and language syntax.

One notable exception to this style is during assignment of multiple variables. Note the position of = in the following example:

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

All assignment operators (=) are in one line, with spaces after the variables. This type of organizational structure is not used by every codebase, but it can be used to improve readability.

JavaScript will ignore extra newlines. Typically, extra line breaks are inserted above comments and after code blocks.

Brackets

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

// An example of if statement syntax
if () { }
// Check math equation and print a string to the console
if (4 < 5) {
    console.log("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++) {
    console.log(i);
    }
Copy after login

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

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 Math.pow(number, 3);
}
// Invoke the function
cube(5);
Copy after login

In the above example, cube() is a function and the bracket() pair will contain the arguments or arguments. In this case, the parameters are numbers or 5 respectively. Although cube() with extra space is valid in that the code will execute as expected, it is almost invisible. Putting them together helps to easily associate the function name with the parentheses pair and any associated passed arguments.

Semicolon

A JavaScript program is made up of a series of instructions called statements, just like a written paragraph is made up of a series of sentences. While sentences will end with a period, JavaScript statements usually end with a semicolon (;).

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

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

// Get the current timestamp and print it to the console
const now = new Date(); console.log(now);
Copy after login

Semicolons are optional if statements are separated by newlines.

// Two statements separated by newlines
const now = new Date()
console.log(now)
Copy after login

A safe and common convention is to separate statements with semicolons, regardless of newlines. 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();
console.log(now);
Copy after login

A semicolon is also required between the initialization, condition, and increment or decrement of a for loop.

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

分号不包括在任何类型的块语句之后,例如if、for、do、while、class、switch和function。这些块语句包含在大括号中。请注意下面的示例。

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

注意,并非所有用大括号括起来的代码都以分号结尾。对象用大括号括起来,并以分号结尾。

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

在除了块语句之外的每个JavaScript语句之后包含分号是广为接受的做法,这些语句以大括号结尾。

缩进

从技术上讲,完整的JavaScript程序可以在一行中编写。 但是,这很快就会变得非常难以阅读和维护。 相反,我们使用换行符和缩进。

下面是一个条件if/else语句的例子,它要么写在一行上,要么用换行符和缩进。

// 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
        }
Copy after login

请注意,块中包含的任何代码都是缩进的。缩进可以用两个空格、四个空格或按制表符来完成。选项卡或空间的使用取决于您的个人偏好(对于单独项目)或组织的指导方针(对于协作项目)。

像上面的例子一样,在第一行末尾包括左大括号是构造JavaScript块语句和对象的常规方法。您可能看到块语句编写的另一种方式是在它们自己的行上使用大括号。

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

这种风格在JavaScript中不像在其他语言中那样常见,但并非闻所未闻。

任何嵌套的block语句都将进一步缩进。

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

正确的代码缩进对于保持可读性和减少混乱是必不可少的。要记住这个规则的一个例外是,压缩的库将删除不必要的字符,因此呈现较小的文件大小以加快页面加载时间(如jquery.min.js和d3.min.js)。

身份标识

变量、函数或属性的名称在JavaScript中称为标识符。标识符由字母和数字组成,但不能包含$和u之外的任何符号,也不能以数字开头。

区分大小写

这些名称区分大小写。以下两个示例myvariable和myvariable将引用两个不同的变量。

var myVariable = 1;
var myvariable = 2;
Copy after login

javascript名称的惯例是用camelcase编写,这意味着第一个单词是小写的,但后面的每个单词都以大写字母开头。您还可以看到用大写字母书写的全局变量或常量,用下划线分隔。

const INSURANCE_RATE = 0.4;
Copy after login

这个规则的例外是类名,它通常是以大写字母(pascalcase)开头的每个单词编写的。

// Initialize a class
class ExampleClass {
    constructor() { }
}
Copy after login

为了确保代码可读,最好在程序文件中使用明显不同的标识符。

保留关键字

标识符也不能由任何保留关键字组成。关键字是JavaScript语言中具有内置功能的单词,如var、if、for和this。

例如,您不能将值赋给名为var的变量。

var var = "Some value";
Copy after login

由于JavaScript理解var为关键字,因此会导致语法错误:

SyntaxError: Unexpected token (1:4)
Copy after login

本文来自 js教程 栏目,欢迎学习!

The above is the detailed content of Get a deeper understanding of syntax and code structure in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:digitalocean.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template