Closure (computer programming): Difference between revisions

Content deleted Content added
Citation bot (talk | contribs)
Add: publisher. | Use this bot. Report bugs. | Suggested by Abductive | #UCB_webform 206/3850
m Use arrow function expressions
Line 102:
// Return a list of all books with at least 'threshold' copies sold.
function bestSellingBooks(threshold) {
return bookList.filter(book => book.sales >= threshold);
function (book) { return book.sales >= threshold; }
);
}
</syntaxhighlight>
 
The arrow operator <code>function=></code> keyword is used hereto insteaddefine ofan <code>lambda<[https:/code>/developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow%20functions arrow function expression], and an <code>Array.filter</code> method<ref>{{cite web |url=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/filter |title=array.filter |work=Mozilla Developer Center |date=10 January 2010 |access-date=2010-02-09}}</ref> instead of a global <code>filter</code> function, but otherwise the structure and the effect of the code are the same.
 
A function may create a closure and return it, as in this example:
Line 116 ⟶ 114:
// using an interval of dx, which should be appropriately small.
function derivative(f, dx) {
return functionx => (f(x + dx) {- f(x)) / dx;
return (f(x + dx) - f(x)) / dx;
};
}
</syntaxhighlight>