Syntaxe JavaScript
Un article de Wikipédia, l'encyclopédie libre.
La syntaxe de JavaScript est un ensemble de règles qui définissent ce qui constitue un programme valide en langage JavaScript.
Sommaire |
[modifier] Origine
Brendan Eich a résumé le lignage de la syntaxe dans le premier paragraphe JavaScript 1.1 des spécifications ainsi: “JavaScript emprunte la plupart de sa syntaxe à Java, mais hérite aussi d'Awk et Perl, avec une influence indirecte de Self pour son système de prototype objet.”
[modifier] Variables
Les Variables en JavaScript n'ont pas de type défini, et n'importe quelle valeur peut être stockée dans n'importe quelle variable. Les variables peuvent être déclarées avec var
. Ces variables ont une portée lexicale et une fois que la variable est déclarée, on peut y accéder depuis la fonction où elle a été déclarée. Les variables déclarées en dehors d'une fonction et les variables utilisées sans avoir été déclarées en utilisant 'var', sont globales (peuvent être utilisées par tout le programme). Voici un exemple de déclaration de variables et de valeurs globales:
x = 0; // Une variable globale var y = 'Hello!'; // Une autre variable globale function f(){ var z = 'foxes'; // Une variable locale twenty = 20; // Globale car le mot-clef var n'est pas utilisé return x; // Nous pouvons utiliser x ici car il s'agit d'une variable globale } // La valeur de z n'est plus accessible à partir d'ici
[modifier] Types de données
[modifier] Nombres
Les nombres en JavaScript sont représentés en binaire comme des IEEE-754 Doubles, ce qui permet une précision de 14 à 15 chiffres significatifs JavaScript FAQ 4.7 (en). Comme ce sont des nombres binaires, ils ne représentent pas toujours exactement les nombres décimaux, en particulier les fractions.
Ceci pose problème quand on formate des nombres pour les afficher car JavaScript n'a pas de méthode native pour le faire. Par exemple:
alert(0.94 - 0.01); // affiche 0.9299999999999999
En conséquence, l'arrondi devrait être utilisé dès qu'un nombre est pour l'affichage (en). La méthode toFixed() ne fait pas partie des spécifications de l'ECMAScript et est implémentée différemment selon l'environnement, elle ne peut donc être invoquée.
Les nombres peuvent être spécifiés dans l'une de ces notations :
345; // un "entier", bien qu'il n'y ait qu'un seul type numérique en JavaScript 34.5; // un nombre flottant 3.45e2; // un autre nombre flottant, équivalent à 345 0377; // un entier octal égal à 255 0xFF; // un entier hexadecimal égal à 255, les lettres A-F peuvent être en minuscules ou en majuscules
Dans certaines implémentations de l'ECMAScript comme l'ActionScript, les couleurs sont parfois spécifiées avec des nombres entiers en écriture hexadécimale :
var colorful = new Color( '_root.shapes' ); colorful.setRGB( 0x003366 );
Le constructeur Number peut être utilisé pour réaliser une conversion numérique explicite :
var myString = "123.456" var myNumber = Number( myString );
Quand il est utilisé comme un constructeur, un objet wrapper numérique est créé (toutefois il est peu employé) :
myNumericWrapper = new Number( 123.456 );
[modifier] Tableaux
An Array is a map from integers to values. In JavaScript, all objects can map from integers to values, but Arrays are a special type of object that has extra behavior and methods specializing in integer indices (e.g., join
, slice
, and push
).
Arrays have a length
property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated if one creates a property with an even larger index. Writing a smaller number to the length
property will remove larger indices. This length
property is the only special feature of Arrays that distinguishes it from other objects.
Elements of Arrays may be accessed using normal object property access notation:
myArray[1]; myArray["1"];
The above two are equivalent. It's not possible to use the "dot"-notation or strings with alternative representations of the number:
myArray.1; // syntax error myArray["01"]; // not the same as myArray[1]
Declaration of an array can use either an Array literal or the Array
constructor:
myArray = [0,1,,,4,5]; // array with length 6 and 4 elements myArray = new Array(0,1,2,3,4,5); // array with length 6 and 6 elements myArray = new Array(365); // an empty array with length 365
Arrays are implemented so that only the elements defined use memory; they are "sparse arrays". Setting myArray[10] = 'someThing'
and myArray[57] = 'somethingOther'
only uses space for these two elements, just like any other object. The length
of the array will still be reported as 58.
You can use the object declaration literal to create objects that behave much like associative arrays in other languages:
dog = {"color":"brown", "size":"large"}; dog["color"]; // this gives you "brown"
You can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both.
cats = [{"color":"brown", "size":"large"}, {"color":"black", "size":"small"}]; cats[0]["size"]; // this gives you "large" dogs = {"rover":{"color":"brown", "size":"large"}, "spot":{"color":"black", "size":"small"}}; dogs["spot"]["size"]; // this gives you "small"
[modifier] Chaînes de caractères
En Javascript la Chaînes de caractères est considéré comme une suite de caractères. Une chaîne de caractères en JavaScript peut être directement créée en plaçant des caractères entre quotes (double ou simple).
var greeting = "Hello, world!"; var another_greeting = 'Greetings, people of Earth.';
In Mozilla based browsers, 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' - Works in Mozilla based browsers
But, for Internet Explorer, you have to access the individual characters using the charAt() method (provided by String class). This is the preferred way when accessing individual characters within a string, as it also works in Mozilla based browsers:
var h = greeting.charAt(0); // Now h contains 'H' - Works in both Internet Explorer // and Mozilla based browsers
however, JavaScript strings are immutable:
greeting[0] = "H"; // ERROR
Applying the equality operator ("==") to two strings returns true if the strings have the same contents, which means: of same length and same cases (for alphabets). Thus:
var x = "world"; var compare1 = ("Hello, " + x == "Hello, world"); // Now compare1 contains true var compare2 = ("Hello, " + x == "hello, world"); // Now compare2 contains false since the // first characters of both operands are // not of the same case
[modifier] Objets
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 easily create flexible data structures:
var myStructure = { name: { first: "Mel", last: "Smith" }, age: 33, hobbies: [ "chess", "jogging" ] };
This is the basis for JSON, which is a simple notation that uses JavaScript-like syntax for data exchange.
[modifier] Opérateurs
The '+' operator is overloaded; it is used for string concatenation and arithmetic addition and also to convert strings to numbers. It also has special meaning when used in a regular expression.
// Concatenate 2 strings var a = 'This'; var b = ' and that'; alert(a + b); // displays 'This and that' // Add two numbers var x = 2; var y = 6; alert(x + y); // displays 8 // Adding a string and a number results in concatenation alert( x + '2'); // displays 22 // Convert a string to a number var z = '4'; // z is a string (the digit 4) alert( z + x); // displays 42 alert( +z + x);// displays 6
[modifier] Arithmétique
Opérateurs binaires
+ Addition - Soustraction * Multiplication / Division (returns a floating-point value) % Modulus (returns the integer remainder)
Opérateurs unaires
- Unary negation (reverses the sign) ++ Increment (can be prefix or postfix) -- Decrement (can be prefix or postfix)
[modifier] Assignation
= Assigne += Ajoute et assigne -= Soustrait et assigne *= Multiplie et assigne /= Divise et assigne
var x = 1; x *= 3; document.write( x ); // affiche: 3 x /= 3; document.write( x ); // affiche: 1 x -= 1; document.write( x ); // affiche: 0
[modifier] Comparaison
== Equal != Not equal > Greater than >= Greater than or equal to < Less than <= Less than or equal to === Identical (equal and of the same type) !== Not identical
[modifier] Booléen
JavaScript has three logical boolean operators: && (logical AND), || (logical OR), and ! (logical NOT).
In the context of a boolean operation, all JavaScript values evaluate to true unless the value is the boolean false itself, the number 0, a string of length 0, or one of the special values null, undefined, or NaN. The Boolean function can be used to explicitly perform this conversion:
Boolean( false ); // returns false Boolean( 0 ); // returns false Boolean( 0.0 ); // returns false Boolean( "" ); // returns false Boolean( null ); // returns false Boolean( undefined ); // returns false Boolean( NaN ); // returns false
The unary NOT operator ! first evaluates its operand in a boolean context, and then returns the opposite boolean value:
var a = 0; var b = 9; !a; // evaluates to true, same as (Boolean( a ) == false) !b; // evaluates to false, same as (Boolean( b ) == true)
A double use of the ! operator can be used to normalize a boolean value:
var arg = null; arg = !!arg; // arg is now the value false, rather than null arg = "finished"; // non-empty string arg = !!arg; // arg is now the value true
In the earliest implementations of JavaScript and JScript, the && and || operators behaved in the same manner as their counterparts in other C derived programming languages, in that they always returned a boolean value:
x && y; // returns true if x AND y evaluate to true: (Boolean( x ) == Boolean( y ) == true), false otherwise x || y; // returns true if x OR y evaluates to true, false otherwise
In the newer implementations, these operators return one of their operands:
expr1 && expr2; // returns expr1 if it evaluates to false, otherwise it returns expr2 expr1 || expr2; // returns expr1 if it evaluates to true, otherwise it returns expr2
This novel behavior is little known even among experienced JavaScripters, and can cause problems if one expects an actual boolean value.
- Short-circuit logical operations means the expression will be evaluated from left to right until the answer can be determined. For example:
a || b is automatically true if a is true. There is no reason to evaluate b. a && b is false if a is false. There is no reason to evaluate b.
&& and || or ! not (logical negation)
[modifier] Logique
Binary operators
& And | Or ^ Xor << Shift left (zero fill) >> Shift right (sign-propagating); copies of the leftmost bit (sign bit) are shifted in from the left. >>> Shift right (zero fill) For positive numbers, >> and >>> yield the same result.
Unary operators
~ Not (inverts the bits)
[modifier] Chaîne de caractère
= Assignation + Concatenation += Concatène et assigne
Exemples
str = "ab" + "cd"; // "abcd" str += "e"; // "abcde"
[modifier] Structures de contrôle
[modifier] If ... else
if (expr) { statements; } else if (expr) { statements; } else { statements; }
[modifier] Switch statement
switch (expr) { case VALUE: statements; break; case VALUE: statements; break; default: statements; break; }
break;
is optional; however, it's recommended to use it in most cases, since otherwise code execution will continue to the body of the nextcase
block.- Add a break statement to the end of the last case as a precautionary measure, in case additional cases are added later.
- Strings can be used for the case values.
- Braces are required.
[modifier] For loop
for (initial-expr; cond-expr; expr evaluated after each loopround) { statements; }
[modifier] For ... in loop
for (var property-name in object-name) { statements using object-name[property-name]; }
- Iterates through all enumerable properties of an object, or the objects at all indices of an array.
- There are differences between the various web browsers with regard to which properties will be reflected with the for...in loop statement. In theory, this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum", but in practice each browser returns a slightly different set of properties during introspection.
[modifier] While loop
while (cond-expr) { statements; }
[modifier] Do ... while
do { statements; } while (cond-expr);
[modifier] With
with(document) { var a = getElementById('a'); var b = getElementById('b'); var c = getElementById('c'); };
- Note the absence of
document.
before eachgetElementById()
invocation.
[modifier] Fonctions
A fonction is a block with a (possibly empty) parameter list that is normally given a name. A function may give back a return value.
function function-name(arg1, arg2, arg3) { statements; return expression; }
Anonymous functions are also possible:
var fn = function(arg1, arg2) { statements; return expression; };
Example: Euclid's original algorithm of finding the greatest common divisor. (This is a geometrical solution which subtracts the shorter segment from the longer):
function gcd(segmentA, segmentB) { while (segmentA != segmentB) { if (segmentA > segmentB) segmentA -= segmentB; else segmentB -= segmentA; } return segmentA; }
The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value undefined
. Within the function the arguments may also be accessed through the arguments
list; this provides access to all arguments using indices (e.g. arguments[0], arguments[1], ... arguments[n]
), including those beyond the number of named arguments. Note that while the arguments list has a .length property, it is not an instance of Array; it does not have methods such as .slice(), .sort(), etc.
Basic data types (strings, integers, ...) are passed by value whereas objects are passed by reference.
[modifier] Objets
For convenience, Types are normally subdivided into primitives and objects. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values, ("slots" in prototype-based programming terminology). JavaScript objects are often mistakenly described as associative arrays or hashes, but they are neither.
JavaScript has several kinds of built-in objects, namely Array, Boolean, Date, Function, Math, Number, Object, RegExp and String. Other objects are "host objects", defined not by the language but by the runtime environment. For example, in a browser, typical host objects belong to the DOM (window, form, links etc.).
[modifier] Créer un objet
Objects can be created using a declaration, an initialiser or a constructor function:
// Declaration var anObject = new Object(); // Initialiser var objectA = {}; var objectB = {'index1':'value 1','index2':'value 2'}; // Constructor (see below)
[modifier] Constructeurs
Constructor functions are a way to create multiple instances or copies of the same object. JavaScript is a prototype based object-based language. This means that inheritance is between objects, not between classes (JavaScript has no classes). Objects inherit properties from their prototypes.
Properties and methods can be added by the constructor, or they can be added and removed after the object has been created. To do this for all instances created by a single constructor function, the prototype
property of the constructor is used to access the prototype object. Object deletion is not mandatory as the scripting engine will garbage collect any variables that are no longer being referenced.
Example: Manipulating an object
// constructor function function MyObject(attributeA, attributeB) { this.attributeA = attributeA; this.attributeB = attributeB; } // create an Object obj = new MyObject('red', 1000); // access an attribute of obj alert(obj.attributeA); // access an attribute using square bracket notation alert(obj["attributeA"]); // add a new property obj.attributeC = new Date(); // remove a property of obj delete obj.attributeB; // remove the whole Object delete obj;
[modifier] Héritage
JavaScript supports inheritance hierarchies through prototyping. For example:
function Base() { this.Override = function() { alert("Base::Override()"); } this.BaseFunction = function() { alert("Base::BaseFunction()"); } } function Derive() { this.Override = function() { alert("Derive::Override()"); } } Derive.prototype = new Base(); d = new Derive(); d.Override(); d.BaseFunction();
will result in the display:
Derive::Override() Base::BaseFunction()
Another way to implement the override method is:
// Base class. function Base(paramA) { this.paramA = paramA; } Base.prototype.Override = function() { alert("Base::Override()"); } Base.prototype.BaseFunction = function() { alert("Base::BaseFunction()"); } // Derived class. function Derive(paramA, paramB) { this.parent = Base; this.parent(paramA); this.paramB = paramB; } Derive.prototype = new Base(); Derive.prototype.Override = function() { alert("Derive::Override()"); } d = new Derive(); d.Override(); d.BaseFunction();
[modifier] Exceptions
Newer versions of JavaScript (as used in Internet Explorer 5 and Netscape 6) include a try ... catch ... finally
exception handling statement to handle run-time errors.
The try ... catch ... finally
statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:
try { // Statements in which exceptions might be thrown } catch(error) { // Statements that execute in the event of an exception } finally { // Statements that execute afterward either way }
Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. Once the catch block finishes, or the try block finishes with no exceptions thrown, then the statements in the finally block execute. This is generally used to free memory that may be lost if a fatal error occurs—though this is less of a concern in JavaScript. This figure summarizes the operation of a try...catch...finally statement:
try { // Create an array arr = new Array(); // Call a function that may not succeed func(arr); } catch (...) { // Recover from error logError(); } finally { // Even if a fatal error occurred, we can still free our array delete arr; }
The finally
part may be omitted:
try { statements } catch (err) { // handle errors }
In fact, the catch
part may also be omitted:
try { statements } finally { // ignore potential errors and just go directly to finally }
Note that at least one of catch and finally are required. It is an error to simply use the try block alone, even if you don't need to handle the error:
try { statement; } // ERROR
The catch argument is also required, even if you don't need to use it:
try { statement; } catch( ) { statement; } // ERROR
The Mozilla implementation allows for multiple catch statements, as an extension to the ECMAScript standard. They follow a syntax similar to that used in Java:
try { statement; } catch ( e if e == "InvalidNameException" ) { statement; } catch ( e if e == "InvalidIdException" ) { statement; } catch ( e if e == "InvalidEmailException" ) { statement; } catch ( e ) { statement; }
[modifier] Divers
[modifier] Sensibilité à la casse
JavaScript est sensible à la casse. Usuellement, les noms d'objets commencent par une majuscule et les fonctions ou variables par une minuscule.
[modifier] Espace
Spaces, tabs and newlines used outside of string constants are called whitespace. Unlike C, whitespace in JavaScript source can directly impact semantics. Because of a technique called "semicolon insertion", any statement that is well formed when a newline is parsed will be considered complete (as if a semicolon were inserted just prior to the newline). Programmers are advised to supply statement terminating semicolons explicitly to enhance readability and lessen unintended effects of the automatic semicolon insertion.
Unnecessary whitespace, whitespace characters that are not needed for correct syntax, can increase the amount of wasted space, and therefore the file size of .js files. The easiest way to address the problem of file size is to set the server to use zip compression. This compression will work far better than any whitespace parser and will reduce the size of all other source your server uploads. This method will work with or without semi-colons.
[modifier] Commentaires
La syntaxe des commentaires est la même qu'en C++.
// commentaire /* commentaire multiligne */
[modifier] Voir aussi
[modifier] References
- David Flanagan, Paula Ferguson: JavaScript: The Definitive Guide, O'Reilly & Associates, ISBN 0-596-10199-6
- Danny Goodman, Brendan Eich: JavaScript Bible, Wiley, John & Sons, ISBN 0-7645-3342-8
- Thomas A. Powell, Fritz Schneider: JavaScript: The Complete Reference, McGraw-Hill Companies, ISBN 0-07-219127-9
- Emily Vander Veer: JavaScript For Dummies, 4th Edition, Wiley, ISBN 0-7645-7659-3