MDN may have intermittent access issues April 18 13:00 - April 19 01:00 UTC. See for all notifications.

Your Search Results

    Новое в JavaScript 1.7

    JavaScript 1.7 is a language update introducing several new features, in particular generators, iterators, array comprehensions, let expressions, and destructuring assignment. It also includes all the features of JavaScript 1.6.

    JavaScript 1.7 support is available starting in Firefox 2 Beta 1, as well as in current Minefield (trunk) builds.

    The code samples included in this article can be experimented with in the JavaScript shell. Read Introduction to the JavaScript shell to learn how to build and use the shell.

    Использование JavaScript 1.7

    Чтобы воспользоваться новыми возможностями JavaScript 1.7, необходимо явно указать, что будет использоваться эта версия JavaScript. В HTML- или XUL-коде для этого следует использовать конструкцию:

    <script type="application/javascript;version=1.7"/>

    При работе в оболочке JavaScript, необходимо указывать версию, используя функцию version():


    Генераторы и итераторы

    When developing code that involves an iterative algorithm (such as iterating over a list, or repeatedly performing computations on the same data set), there are often state variables whose values need to be maintained for the duration of the computation process. Traditionally, you have to use a callback function to obtain the intermediate values of an iterative algorithm.


    Consider this iterative algorithm that computes Fibonacci numbers:

    function do_callback(num) {
      document.write(num + "<BR>\n");
    function fib() {
      var i = 0, j = 1, n = 0;
      while (n < 10) {
        var t = i;
        i = j;
        j += t;

    This code uses a callback routine to perform operations on each iterative step of the algorithm. In this case, each Fibonacci number is simply printed to the console.

    Generators and iterators work together to provide a new, better, way to do this. Let's see how the Fibonacci number routine looks written using a generator:

    function fib() {
      var i = 0, j = 1;
      while (true) {
        yield i;
        var t = i;
        i = j;
        j += t;
    var g = fib();
    for (var i = 0; i < 10; i++) {
      document.write( + "<BR>\n");

    The function containing the yield keyword is a generator. When you call it, its formal parameters are bound to actual arguments, but its body isn't actually evaluated. Instead, a generator-iterator is returned. Each call to the generator-iterator's next() method performs another pass through the iterative algorithm. Each step's value is the value specified by the yield keyword. Think of yield as the generator-iterator version of return, indicating the boundary between each iteration of the algorithm. Each time you call next(), the generator code resumes from the statement following the yield.

    You cycle a generator-iterator by repeatedly calling its next() method until you reach your desired result condition. In this example, we can obtain however many Fibonacci numbers we want by continuing to call until we have the number of results we want.


    An iterator is a special object that lets you iterate over data.

    In normal usage, iterator objects are "invisible"; you won't need to operate on them explicitly, but will instead use JavaScript's and for statements to loop naturally over the keys and/or values of objects.

    var objectWithIterator = getObjectSomehow();
    for (var i in objectWithIterator)
      document.write(objectWithIterator[i] + "<BR>\n");

    If you are implementing your own iterator object, or have another need to directly manipulate iterators, you'll need to know about the next method, the StopIteration exception, and the __iterator__ property.

    You can create an iterator for an object by calling Iterator(objectname); the iterator for an object is found via the object's __iterator__ property, which by default implements iteration according to the usual and for model. If you wish to provide a custom iterator, you should override the getter for __iterator__ to return an instance of your custom iterator. To get an object's iterator from script, you should use Iterator(obj) rather than accessing the __iterator__ property directly.

    Once you have an iterator, you can easily fetch the next item in the object by calling the iterator's next() method. If there is no data left, the StopIteration exception is thrown.

    Here's a simple example of direct iterator manipulation:

    var obj = {name:"Jack Bauer", username:"JackB", id:12345, agency:"CTU", region:"Los Angeles"};
    var it = Iterator(obj);
    try {
      while (true) {
        document.write( + "<BR>\n");
    } catch (err if err instanceof StopIteration) {
      document.write("End of record.<BR>\n");
    } catch (err) {
      document.write("Unknown error: " + err.description + "<BR>\n");

    The output from this program looks like this:

    name,Jack Bauer
    region,Los Angeles
    End of record.

    You can, optionally, specify a second parameter when creating your iterator, which is a boolean value that indicates whether or not you only want the keys returned each time you call its next() method. Changing var it = Iterator(obj); to var it = Iterator(obj, true); in the above sample results in the following output:

    End of record.

    In both cases, the actual order in which the data is returned may vary based on the implementation. There is no guaranteed ordering of the data.

    Iterators are a handy way to scan through the data in objects, including objects whose content may include data you're unaware of. This can be particularly useful if you need to preserve data your application isn't expecting.

    Array comprehensions

    Array comprehensions are a use of generators that provides a convenient way to perform powerful initialization of arrays. For example:

    function range(begin, end) {
      for (let i = begin; i < end; ++i) {
        yield i;

    range() is a generator that returns all the values between begin and end. Having defined that, we can use it like this:

    var ten_squares = [i * i for (i in range(0, 10))];

    This pre-initializes a new array, ten_squares, to contain the squares of the values in the range 0..9.

    You can use any conditional when initializing the array. If you want to initialize an array to contain the even numbers between 0 and 20, you can use this code:

    var evens = [i for (i in range(0, 21)) if (i % 2 == 0)];

    Prior to JavaScript 1.7, this would have to be coded something like this:

    var evens = [];
    for (var i=0; i <= 20; i++) {
      if (i % 2 == 0)

    Not only is the array comprehension much more compact, but it's actually easier to read, once you're familiar with the concept.

    Scoping rules

    Array comprehensions have an implicit block around them, containing everything inside the square brackets, as well as implicit let declarations.

    Add details.

    Block scope with let

    There are several ways in which let can be used to manage block scope of data and functions:

    • The let statement provides a way to associate values with variables, constants, and functions within the scope of a block, without affecting the values of like-named variables outside the block.
    • The let expression lets you establish variables scoped only to a single expression.
    • The let definition defines variables, constants, and functions whose scope is constrained to the block in which they're defined. This syntax is very much like the syntax used for var.
    • You can also use let to establish variables that exist only within the context of a for loop.

    The let statement

    The let statement provides local scoping for variables, constants, and functions. It works by binding zero or more variables in the lexical scope of a single block of code. The completion value of the let statement is the completion value of the block.

    For example:

    var x = 5;
    var y = 0;
    let (x = x+10, y = 12) {
      document.write(x+y + "<BR>\n");
    document.write(x+y + "<BR>\n");

    The output from this program will be:


    The rules for the code block are the same as for any other code block in JavaScript. It may have its own local variables established using the let declarations.

    Note: When using the let statement syntax, the parentheses following let are required. Failure to include them will result in a syntax error.
    Scoping rules

    The scope of variables defined using let is the let block itself, as well as any inner blocks contained inside it, unless those blocks define variables by the same names.

    let expressions

    You can use let to establish variables that are scoped only to a single expression:

    var x = 5;
    var y = 0;
    document.write( let(x = x + 10, y = 12) x+y  + "<BR>\n");
    document.write(x+y + "<BR>\n");

    The resulting output is:


    In this case, the binding of the values of x and y to x+10 and 12 are scoped solely to the expression x+y.

    Scoping rules

    Given a let expression:

    let (decls) expr

    There is an implicit block created around expr.

    let definitions

    The let keyword can also be used to define variables, constants, and functions inside a block.

     ** This code doesn't run in FF 2.0 b1. **
    if (x > y)
       let const k = 37;
       let gamma : int = 12.7 + k;
       let i = 10;
       let function f(n) { return (n/3)+k; }
       return f(gamma) + f(i);
    Scoping rules

    Variables, functions, and constants declared by let, let function, and let const have as their scope the block in which they are defined, as well as in any sub-blocks in which they aren't redefined. In this way, let works very much like var.

    In programs and classes let does not create properties on the global and class objects like var does; instead, it creates properties in an implicit block created for the evaluation of statements in those contexts. This essentially means that let won't override variables previously defined using var. For example:

    ** Doesn't work in FF 2.0 b1. Returns "42", not "global".
    var x = 'global';
    let x = 42;
    document.write(this.x + "<BR>\n");

    The output displayed by this code will display "global", not " 42".

    An implicit block is one that is not bracketed by braces; it's created implicitly by the JavaScript engine.

    In functions, let executed by eval() does not create properties on the variable object (activation object or innermost binding rib) like var does; instead, it creates properties in an implicit block created for the evaluation of statements in the program. This is a consequence of eval() operating on programs in tandem with the previous rule.

    In other words, when you use eval() to execute code, that code is treated as an independent program, which has its own implicit block around its code.

    let-scoped variables in for loops

    You can use the let keyword to bind variables locally in the scope of for loops, just like you can with var.

    ** Add obj **
       var i=0;
       for ( let i=i ; i < 10 ; i++ )
         document.write(i + "<BR>\n");
       for ( let [name,value] in obj )
         document.write("Name: " + name + ", Value: " + value + "<BR>\n");
    Scoping rules
    for (let expr1; expr2; expr3) statement

    In this example, expr2, expr3, and statement are enclosed in an implicit block that contains the block local variables declared by let expr1. This is demonstrated in the first loop above.

    for (let expr1 in expr2) statement
    for each(let expr1 in expr2) statement

    In both these cases, there are implicit blocks containing each statement. The first of these is shown in the second loop above.

    Destructuring assignment

    Destructuring assignment makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

    The object and array literal expressions provide an easy way to create ad-hoc packages of data. Once you've created these packages of data, you can use them any way you want to. You can even return them from functions.

    One particularly useful thing you can do with destructuring assignment is to read an entire structure in a single statement, although there are a number of interesting things you can do with them, as shown in the section full of examples that follows.

    This capability is similar to features present in languages such as Perl and Python.


    Destructuring assignment is best explained through the use of examples, so here are a few for you to read over and learn from.

    Note: If you have more interesting examples of ways to use destructuring assignment, please consider adding them to this section.
    Swapping values

    You can use destructuring assignment, for example, to swap values:

    var a = 1;
    var b = 3;
    [a, b] = [b, a];

    After executing this code, b is 1 and a is 3.

    Or to rotate values: (poor code format)

    <body bgcolor = "black">
    <script type="application/javascript;version=1.7"/>
    var a = 'o';
    var b = "<font color = 'green'>o</font>";
    var c = 'o';
    var d = 'o';
    var e = 'o';
    var f = "<font color = 'blue'>o</font>";
    var g = 'o';
    var h = 'o';
    for (lp=0;lp<40;lp++)
    	{[a, b, c, d, e, f, g, h] = [b, c, d, e, f, g, h, a];
    	 document.write(a+''+b+''+c+''+d+''+e+''+f+''+g+''+h+''+"<br />");}

    After executing this code, a visual colorful display of the variable rotation will be displayed

    Multiple-value returns

    Thanks to destructuring assignment, functions can return multiple values. While it's always been possible to return an array from a function, this provides an added degree of flexibility.

    function f() {
      return [1, 2];

    As you can see, returning results is done using an array-like notation, with all the values to return enclosed in brackets. You can return any number of results in this way. In this example, f() returns the values [1, 2] as its output.

    var a, b;
    [a, b] = f();
    document.write ("A is " + a + " B is " + b + "<BR>\n");

    The command [a, b] = f() assigns the results of the function to the variables in brackets, in order: a is set to 1 and b is set to 2.

    You can also retrieve the return values as an array:

    var a = f();
    document.write ("A is " + a);

    In this case, a is an array containing the values 1 and 2.

    Ignoring some returned values

    You can also ignore return values that you're not interested in:

    function f() {
      return [1, 2, 3];
    var [a, , b] = f();
    document.write ("A is " + a + " B is " + b + "<BR>\n");

    After running this code, a is 1 and b is 3. The value 2 is ignored.

    Looping across objects

    You can also use destructuring assignment to pull data out of an object:

    var obj = { width: 3, length: 1.5, color: "orange" };
    for (let[name, value] in obj) {
      document.write ("Name: " + name + ", Value: " + value + "<BR>\n");

    This loops over all the key/value pairs in the object obj and displays their names and values. In this case, the output looks like the following:

    Name: width, Value: 3
    Name: length, Value: 1.5
    Name: color, Value: orange
    Looping across values in an array of objects

    You can loop over an array of objects, pulling out fields of interest from each object:

    var people = [
        name: "Mike Smith",
        family: {
          mother: "Jane Smith",
          father: "Harry Smith",
          sister: "Samantha Smith"
        age: 35
        name: "Tom Jones",
        family: {
          mother: "Norah Jones",
          father: "Richard Jones",
          brother: "Howard Jones"
        age: 25
    for each (let {name: n, family: { father: f } } in people) {
      document.write ("Name: " + n + ", Father: " + f + "<BR>\n");

    This pulls the name field into n and the family.father field into f, then prints them. This is done for each object in the people array. The output looks like this:

    Name: Mike Smith, Father: Harry Smith
    Name: Tom Jones, Father: Richard Jones

    Метки документа и участники

    Contributors to this page: fscholz, Dionys
    Обновлялась последний раз: fscholz,