JavaScript syntax
This article is part of
the JavaScript series. |
JavaScript |
JavaScript syntax |
ECMAScript |
JavaScript topics |
|
The syntax of JavaScript is a set of rules that defines what constitutes a valid program in the Javascript language.
Origin of Syntax
Brendan Eich summarized the ancestry of the syntax in the first paragraph of the JavaScript 1.1 specification as follows:
Variables
Variables in standard JavaScript have no type attached, and any value can be stored in any variable. Variables can be declared with a var
statement. These variables are lexically scoped and once a variable is declared, it may be accessed anywhere inside the function where it is declared. Variables declared outside any function, and variables first used within functions without being declared with 'var', are global. Here is an example of variable declarations and global values:
x = 0; // A global variable var y = 'Hello!'; // Another global variable function f(){ var z = 'foxes'; // A local variable twenty = 20; // Global because keyword var is not used return x; // We can use x here because it is global } // The value of z is no longer available
Basic data types
Numbers
Numbers in JavaScript are represented in binary as IEEE-754 Doubles, which provides an accuracy to about 14 or 15 significant digits JavaScript FAQ 4.2. Because they are floating point numbers, they do not always exactly represent real numbers, including fractions.
This becomes an issue when formatting numbers for output, for which JavaScript has no built-in methods. For example:
alert(0.94 - 0.01); // displays 0.9299999999999999
As a result, rounding should be used whenever numbers are formatted for output. The toFixed() method is not part of the ECMAScript specification and is implemented differently in various environments, so it can't be relied upon.
Numbers may be specified in any of these notations:
345; // an "integer", although there is only one numeric type in JavaScript 34.5; // a floating-point number 3.45e2; // another floating-point, equivalent to 345 0377; // an [[octal]] integer equal to 255 0xFF; // a [[hexadecimal]] integer equal to 255, the letters A-F may be upper- or lowercase
In some ECMAScript implementations such as ActionScript, RGB color values are sometimes specified with hexadecimal integers:
var colorful = new Color( '_r