04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 22: The Evolution of JavaScript<br />

In this code, the let statement defines an area within which the num variable is equal to 10 and the<br />

multiplier variable is equal to 2. This definition of num overrides the previously declared value using<br />

var , so within the let statement the result of multiplying by the multiplier is 20. Outside the let<br />

statement, the value of num remains 5. Since each let statement creates its own scope, the variable<br />

values inside it have no bearing on the values outside.<br />

You can use a similar syntax to create a let expression where variable values are set only for a single<br />

expression. Here is an example:<br />

var result = let(num=10, multiplier=2) num * multiplier;<br />

alert(result); //20<br />

Here, a let expression is used to calculate a value using two variables. The value is then stored in the<br />

result variable. After that point, the variables num and multiplier no longer exist.<br />

Using block - level scopes in JavaScript gives you more control over which variables exist at what point<br />

during code execution.<br />

Generators<br />

A generator is an object that generates a sequence of values one at a time. With JavaScript 1.7, you can<br />

create a generator by defining a function that returns a specific value using the yield operator. When a<br />

function is called that uses yield , a new Generator instance is created and returned. The next()<br />

method can then be called to retrieve the first value of the generator. When this happens, the original<br />

function is executed and stops execution when it comes to yield , returning the specified value. In this<br />

way, yield works in a similar manner to return . If next() is called again, code execution continues at<br />

the next statement following yield and then continues to run until yield is encountered again, at<br />

which point a new value is returned. Here is an example:<br />

function myNumbers(){<br />

for (var i=0; i < 10; i++){<br />

yield i * 2;<br />

}<br />

}<br />

var generator = myNumbers();<br />

try {<br />

while(true){<br />

document.write(generator.next() + “ < br / > ”);<br />

}<br />

} catch(ex){<br />

//intentionally blank<br />

} finally {<br />

generator.close();<br />

}<br />

When the function myNumbers() is called, a generator is returned. The myNumbers() function itself is<br />

very simple, containing a for loop that yields a value each time through the loop. Each call to next()<br />

causes another trip through the for loop and returns the next value. The first value is 0, the second is 2,<br />

710

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!