ECMAScript Syntax

Developers familiar with languages such as Java, C, and Perl will find ECMAScript syntax easy to master, as it borrows syntax from these languages.

Java and ECMAScript have some key syntactic features in common, and some that are completely different.

Case sensitivity

Like Java, variables, function names, operators, and everything else are case-sensitive.

For example:

The variable test is different from the variable TEST.

Variables are weakly typed

Unlike Java and C, variables in ECMAScript do not have a specific type, and only the var operator is used to define variables, which can be initialized to any value.

Therefore, the type of data stored in a variable can be changed at any time (try to avoid doing this as much as possible).

Example

var color = "red";
var num = 25;
var visible = true;

The semicolon at the end of each line is optional

Java, C, and Perl all require that each line of code ends with a semicolon (;) to be syntactically correct.

ECMAScript allows developers to decide for themselves whether to end a line of code with a semicolon. If there is no semicolon, ECMAScript considers the end of the line as the end of the statement (similar to Visual Basic and VBScript), provided that this does not break the semantics of the code.

The best coding habit is to always add semicolons, as some browsers cannot run correctly without semicolons. However, according to the ECMAScript standard, the following two lines of code are both correct:

var test1 = "red"
var test2 = "blue";

Comments are the same as those in Java, C, and PHP languages

ECMAScript borrows the comment syntax from these languages.

There are two types of comments:

  • Single-line comments start with a double slash (//)
  • Multi-line comments start with a single slash and an asterisk (/*) and end with an asterisk and a single slash (*/)
//this is a single-line comment
/*this is a multi-
line comment*/

Braces indicate a code block

Another concept borrowed from Java is the code block.

A code block represents a sequence of statements that should be executed in order, enclosed in curly braces ({}) on both sides.

For example:

if (test1 == "red") {
    test1 = "blue";
    alert(test1);
}