JavaScript basic syntax

Basic syntax of JavaScript

The syntax of JavaScript is similar to the Java language. Each statement ends with;, and statement blocks use {...}. However, JavaScript does not require adding ; at the end of each statement. The engine in the browser responsible for executing JavaScript code will automatically add ; at the end of each statement.

Note: Allowing the JavaScript engine to automatically add semicolons will change the semantics of the program in some cases, causing the running results to be inconsistent with expectations. In this tutorial, we will not omit ;, all statements will add ;.

For example, the following line of code is a complete assignment statement:

var x = 1;

The following line of code is a string, but it can still be regarded as a complete statement:

'Hello, world';

The following line of code contains two statements, each statement uses; to indicate the end of the statement:

var x = 1; var y = 2;

// It is not recommended to write multiple statements in one line!

The statement block is a A collection of group statements. For example, the following code first makes a judgment. If the judgment is true, all statements in {...} will be executed:

if (2 > 1) { x = 1; y = 2; z = 3; }

Pay attention to the statements in curly brackets {...} Have indentation, usually 4 spaces. Indentation is not required by JavaScript syntax, but indentation helps us understand the hierarchy of the code, so we must abide by the indentation rules when writing code. Many text editors have an "auto-indent" feature that can help organize your code.

{...} can also be nested to form a hierarchical structure:

if (2 > 1) { x = 1; y = 2; z = 3; if (x < y) { z = 4; } if (x > y) { z = 5; } }

JavaScript itself has no limit on the level of nesting, but too much nesting will undoubtedly greatly increase the ability to understand the code. difficulty. In this case, you need to extract part of the code and call it as a function, which can reduce the complexity of the code.

Comments

Characters starting with // until the end of the line are considered line comments. Comments are for developers to see, and the JavaScript engine will automatically ignore them:

// This It's a line of comments alert('hello'); // This is also a comment

Another type of block comment is to use /*...*/ to wrap multi-line characters and put a big "block" ” is treated as a comment:

/* Starting here is a block comment
is still a comment
is still a comment
end of comment*/

//alert('我不想执行'); alert('我也不想执行');
   
...


Continuing Learning
||
RunJS 演示代码
submit Reset Code
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!