Content deleted Content added
Insouciance (talk | contribs) m Disambig "hack" |
Quamaretto (talk | contribs) Improved quality of beginning of article, still needs a true introduction and it's lacking completion and accuracy (e.g. Regular Expression literals). DOM hacks aren't really syntax. |
||
Line 1:
The '''syntax of JavaScript''' is a set of rules that defines how a [[JavaScript]] program will be written and [[Interpreter (computing)|interpreted]].
===Variables===
[[Variable]]s in standard JavaScript have no type attached, and any value can be stored in any variable. Variables can be declared with a <code>var</code> statement. These variables are [[Variable#Scope_and_extent|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 used without being declared with 'var', are global (can be used by the entire program).
Here is an example of variable declarations and global values:
<code>
x = 0; // A global variable;
var y = 'Hello!'; // Another global variable
function f(){
var z = 'foxes'; // A local variable;
twenty = 20; // Another global
return x; // We can use x here because it is global
}
// The value of z is no longer available
</code>
==Basic data types==
===Numbers===
Line 47 ⟶ 54:
[[Array]]s are implemented so that only the elements defined use memory; they are "[[sparse array]]s". Setting <code>myArray[10] = 'someThing'</code> and <code>myArray[57] = 'somethingOther'</code> only uses space for these two elements, just like any other object. The <code>length</code> of the array will still be reported as 58.
===Strings===
Object literals allow one to define generic structured data:▼
Strings in Javascript are a sequence of characters. Strings in JavaScript can be created directly by placing the series of characters between double or single quotes.
var greeting = "Hello, ronald!";
var another_greeting = 'Greetings, people of Earth.';
Individual characters within a string can be accessed (as strings with only a single character) through the same notation as arrays:
var h = greeting[0]; // Now h contains 'H'
===Objects===
The most basic objects in JavaScript act as dictionaries. These dictionaries can have any type of value paired with a key, which is a string. Objects with values can be created directly through object literal notation:
var o = {name: 'My Object', purpose: 'This object is utterly without purpose.', answer: 42};
Properties of objects can be created, set, and read individually using the familiar dot ('.') notation or by a similar syntax to arrays:
var name = o.name; // name now contains 'My Object'
var answer = o['answer'] // answer now contains 42
▲Object literals and array literals allow one to
var myStructure = {
Line 58 ⟶ 86:
};
This is the basis for [[JSON]], which is a simple notation that uses JavaScript-like syntax for data exchange.
==Operators==
|