An identifier is the name of a variable, function, property, or function argument. Identifi ers may be one or more characters in the following format:
- The first character must be a letter, an underscore (_), or a dollar sign ($).
- All other characters may be letters, underscores, dollar signs, or numbers.
Tips: Keywords, reserved words cannot be used as identifiers, such as true, false, and so on.
Strict Mode/Use Strict
You may also specify just a function to execute in strict mode by including the pragma at the top of the function body:
Statements in ECMAScript are terminated by a semicolon, though omitting the semicolon makes the parser determine where the end of a statement occurs, as in the following examples:
var sum = a + b //valid even without a semicolon - not recommended var diff = a - b; //valid - preferred
Even though a semicolon is not required at the end of statements, it is recommended to always include one.
- Including semicolons helps prevent errors of omission, such as not fi nishing what you were typing
- Allows developers to compress ECMAScript code by removing extra white space(if you using the thirdparty software to compress js file to reduce file size, such as yuicompressor)
- Including semicolons also improves performance in certain situations, because parsers try to correct syntax errors by inserting semicolons where they appear to belong.
Multiple statements can be combined into a code block:
Loosely Typed Variables
ECMAScript variables are loosely typed, meaning that a variable can hold any type of data. Every variable is simply a named placeholder for a value. To define a variable, use the var operator followed by the variable name:
Local variable VS Global variable
Tips: Although it's possible to define global variables by omitting the var operator, this approach is not recommended. Global variables defined locally are hard to maintain and cause confusion, because it's not immediately apparent if the omission of var was intentional. Strict mode throws a ReferenceError when an undeclared variable is assigned a value.It is recommended to use the following method:
If you need to defi ne more than one variable, you can do it using a single statement, separating each variable (and optional initialization) with a comma: