A snippet of JaScript code with keywords highlighted in different colors
The syntax of JaScript is the set of rules that define a correctly structured JaScript program.
The examples below make use of the console.log() function present in most browsers for standard text output.
The JaScript standard library lacks an official standard text output function (with the exception of document.write). Given that JaScript is mainly used for client-side scripting within modern web browsers, and that almost all Web browsers provide the alert function, alert can also be used, but is not commonly used.
Origins[edit]Brendan Eich summarized the ancestry of the syntax in the first paragraph of the JaScript 1.1 specification[1][2] as follows:
JaScript borrows most of its syntax from Ja, but also inherits from Awk and Perl, with some indirect influence from Self in its object prototype system.
Basics[edit] Case sensitivity[edit]JaScript is case sensitive. It is common to start the name of a constructor with a capitalized letter, and the name of a function or variable with a lower-case letter.
Example:
var a = 5; console.log(a); // 5 console.log(A); // throws a ReferenceError: A is not defined Whitespace and semicolons[edit]Unlike in C, whitespace in JaScript source can directly impact semantics. Semicolons end statements in JaScript. Because of automatic semicolon insertion (ASI), some statements that are well formed when a newline is parsed will be considered complete, as if a semicolon were inserted just prior to the newline. Some authorities advise supplying statement-terminating semicolons explicitly, because it may lessen unintended effects of the automatic semicolon insertion.[3]
There are two issues: five tokens can either begin a statement or be the extension of a complete statement; and five restricted productions, where line breaks are not allowed in certain positions, potentially yielding incorrect parsing.
The five problematic tokens are the open parenthesis "(", open bracket "[", slash "/", plus "+", and minus "-". Of these, the open parenthesis is common in the immediately invoked function expression pattern, and open bracket occurs sometimes, while others are quite rare. An example:
a = b + c (d + e).foo() // Treated as: // a = b + c(d + e).foo();with the suggestion that the preceding statement be terminated with a semicolon.
Some suggest instead the use of leading semicolons on lines starting with '(' or '[', so the line is not accidentally joined with the previous one. This is known as a defensive semicolon, and is particularly recommended, because code may otherwise become ambiguous when it is rearranged. For example:
a = b + c ;(d + e).foo() // Treated as: // a = b + c; // (d + e).foo();Initial semicolons are also sometimes used at the start of JaScript libraries, in case they are appended to another library that omits a trailing semicolon, as this can result in ambiguity of the initial statement.
The five restricted productions are return, throw, break, continue, and post-increment/decrement. In all cases, inserting semicolons does not fix the problem, but makes the parsed syntax clear, making the error easier to detect. return and throw take an optional value, while break and continue take an optional label. In all cases, the advice is to keep the value or label on the same line as the statement. This most often shows up in the return statement, where one might return a large object literal, which might be accidentally placed starting on a new line. For post-increment/decrement, there is potential ambiguity with pre-increment/decrement, and again it is recommended to simply keep these on the same line.
return a + b; // Returns undefined. Treated as: // return; // a + b; // Should be written as: // return a + b; Comments[edit]Comment syntax is the same as in C++, Swift and other programming languages.
Single-line comments begin with // and continue until the end of the line. A second type of comments can also be made; these start with /* and end with */ and can be used for multi-line comments.
A third type of comment, the hashbang comment, starts with #! and continues until the end of the line. They are only valid at the start of files and are intended for use in CLI environments.[4]
#! Hashbang comment // One-line comment /* Multi-line comment */ Variables[edit] Main article: Variable (programming)Variables in standard JaScript he no type attached, so any value (each value has a type) can be stored in any variable. Starting with ES6, the 6th version of the language, variables could be declared with var for function scoped variables, and let or const which are for block level variables. Before ES6, variables could only be declared with a var statement. Values assigned to variables declared with const cannot be changed, but their properties can. var should no longer be used since let and const are supported by modern browsers.[5] A variable's identifier must start with a letter, underscore (_), or dollar sign ($), while subsequent characters can also be digits (0-9). JaScript is case sensitive, so the uppercase characters "A" through "Z" are different from the lowercase characters "a" through "z".
Starting with JaScript 1.5, ISO 8859-1 or Unicode letters (or \uXXXX Unicode escape sequences) can be used in identifiers.[6] In certain JaScript implementations, the at sign (@) can be used in an identifier, but this is contrary to the specifications and not supported in newer implementations. [citation needed]
Scoping and hoisting[edit]Variables declared with var are lexically scoped at a function level, while ones with let or const he a block level scope. Since declarations are processed before any code is executed, a variable can be assigned to and used prior to being declared in the code.[7] This is referred to as hoisting, and it is equivalent to variables being forward declared at the top of the function or block.[8]
With var, let, and const statements, only the declaration is hoisted; assignments are not hoisted. Thus a var x = 1 statement in the middle of the function is equivalent to a var x declaration statement at the top of the function, and an x = 1 assignment statement at that point in the middle of the function. This means that values cannot be accessed before they are declared; forward reference is not possible. With var a variable's value is undefined until it is initialized. Variables declared with let or const cannot be accessed until they he been initialized, so referencing such variables before will cause an error.
Function declarations, which declare a variable and assign a function to it, are similar to variable statements, but in addition to hoisting the declaration, they also hoist the assignment – as if the entire statement appeared at the top of the containing function – and thus forward reference is also possible: the location of a function statement within an enclosing function is irrelevant. This is different from a function expression being assigned to a variable in a var, let, or const statement.
So, for example,
var func = function() { .. } // declaration is hoisted only function func() { .. } // declaration and assignment are hoistedBlock scoping can be produced by wrapping the entire block in a function and then executing it – this is known as the immediately-invoked function expression pattern – or by declaring the variable using the let keyword.
Declaration and assignment[edit]Variables declared outside a scope are global. If a variable is declared in a higher scope, it can be accessed by child scopes.
When JaScript tries to resolve an identifier, it looks in the local scope. If this identifier is not found, it looks in the next outer scope, and so on along the scope chain until it reaches the global scope where global variables reside. If it is still not found, JaScript will raise a ReferenceError exception.
When assigning an identifier, JaScript goes through exactly the same process to retrieve this identifier, except that if it is not found in the global scope, it will create the "variable" in the scope where it was created.[9] As a consequence, a variable never declared will be global, if assigned. Declaring a variable (with the keyword var) in the global scope (i.e. outside of any function body (or block in the case of let/const)), assigning a never declared identifier or adding a property to the global object (usually window) will also create a new global variable.
Note that JaScript's strict mode forbids the assignment of an undeclared variable, which oids global namespace pollution.
Examples[edit]Here are some examples of variable declarations and scope:
var x1 = 0; // A global variable, because it is not in any function let x2 = 0; // Also global, this time because it is not in any block function f() { var z = 'foxes', r = 'birds'; // 2 local variables m = 'fish'; // global, because it was not declared anywhere before function child() { var r = 'monkeys'; // This variable is local and does not affect the "birds" r of the parent function. z = 'penguins'; // Closure: Child function is able to access the variables of the parent function. } twenty = 20; // This variable is declared on the next line, but usable anywhere in the function, even before, as here var twenty; child(); return x1 + x2; // We can use x1 and x2 here, because they are global } f(); console.log(z); // This line will raise a ReferenceError exception, because the value of z is no longer ailable for (let i = 0; i