search
HomeWeb Front-endJS TutorialGet a deeper understanding of syntax and code structure in JavaScript

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!"

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

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

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";

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";

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);
    }

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);

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();

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);

Semicolons are optional if statements are separated by newlines.

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

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);

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

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

分号不包括在任何类型的块语句之后,例如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);
    }

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

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

在除了块语句之外的每个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
        }

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

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

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

这种风格在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;
    }
}

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

身份标识

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

区分大小写

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

var myVariable = 1;
var myvariable = 2;

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

const INSURANCE_RATE = 0.4;

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

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

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

保留关键字

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

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

var var = "Some value";

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

SyntaxError: Unexpected token (1:4)

本文来自 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!

Statement
This article is reproduced at:digitalocean. If there is any infringement, please contact admin@php.cn delete
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software