A page in the |
---|
Introduction |
Basics |
Statements · Control Flow Statements · Comments · Objects · Functions · Style |
Features |
Scoping · Inheritance · DOM |
It has been suggested that this page or section be merged into Wikibooks:JavaScript. (Discuss)
A language's syntax consists of its grammar and punctuation. JavaScript's syntax involves values, operators, and words. Each value represents a datum and may be used to calculate other values via operators. Words have a few different purposes, including operations, storing values, and directly affecting a program's path of execution.
Expressions[]
An expression is anything which may be left by itself without causing a syntax error. Each one resolves to a value (much like algebraic expressions). Any lone expression is a simple statement, and is typically terminated by either a semicolon or a newline (or both).
Values[]
Values are a type of expression and include every data type. A value's data type is constantly associated with the value. Here are some useless value statements:
5; 490;
Operators[]
Most operators calculate values from other values; some are used to initialize values. Here are more useless statements:
5 + 4; 3 - 7; 'This is ' + 'some more text.';
Variables[]
Variables, commonly described as storage bins, can make the above statements useful. Variables are represented by identifiers. In JavaScript, each variable can hold exactly one item (with no practical limit on the item's size). The item is the variable's value, and it can be anything you can program. The most common operator is one which does not produce a new value; instead, it assigns a value to a variable. An assignment is a type of expression which evaluates to the assigned value.
variable = 'value';
variable
will now be treated exactly as if it were 'value'
. Note, however, that an exception to this applies if one variable is assigned to another:
variable1 = variable2;
Neither variable will remember the assignment when the other is changed. If you want this C-style functionality, use pointer objects.
A best practice exists which is to always use the var
keyword before (or when) a variable is first referenced. (Note that var
can be used when a variable has already been referenced; this has no effect.)
var variable = 'value';
This ensures that variable
is only defined within the current scope, so a variable by the same name is not unintentionally overwritten.
Block statements[]
Block statements, or blocks, are used to group related statements together. A block statement begins with { and ends with }. Here is a program with a block statement:
var x = 7; var y = 13; { x = y - x; }
At this point, block statements may seem quite useless because they do not have scope in JavaScript. However, the next page will explain what they are good for.