Path: csiph.com!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!newsfeed.straub-nv.de!noris.net!newsfeed.arcor.de!newsspool1.arcor-online.net!news.arcor.de.POSTED!not-for-mail Content-Type: text/plain; charset="UTF-8" Message-ID: <7227299.QoKgMUOf8L@PointedEars.de> From: Thomas 'PointedEars' Lahn Reply-To: Thomas 'PointedEars' Lahn Organization: PointedEars Software (PES) Date: Mon, 24 Sep 2012 01:10:10 +0200 User-Agent: KNode/4.4.11 Content-Transfer-Encoding: 8Bit X-Face: %i>XG-yXR'\"2P/C_aO%~;2o~?g0pPKmbOw^=NT`tprDEf++D.m7"}HW6.#=U:?2GGctkL,f89@H46O$ASoW&?s}.k+&. Followup-To: comp.lang.javascript MIME-Version: 1.0 Lines: 48 NNTP-Posting-Date: 24 Sep 2012 01:10:10 CEST NNTP-Posting-Host: 8164538e.newsspool3.arcor-online.net X-Trace: DXC=97Lc^CCSMY[HigV@eW57PQMcF=Q^Z^V3X4Fo<]lROoRQ8kF On 2012-09-22 14:04, justaguy wrote: >> Code: > [snipped] > >> Question: >> The closure takes so many lines while the function has only 2 lines to >> get the same thing done. So, the question is, why do we use closure? > > You don't, just like you don't actually use "Hello, world" in production > code. This was obviously just an example for how closures work. If this > was code intended for actual use, your "just a function" variant would > be better suited (provided it only returned the value, like in the > "closure" example). You are mistaken as you are overlooking that creating that Array instance and populating it with elements requires resources – memory and runtime. Since we have only automated garbage collection, and the function may be called a number of times, it is better to use a closure here, so that the object would only be created, and the array only populated, once. There is, however, a caveat to intended closures of that kind that can turn out to be a disadvantage: The order of execution matters. All variables used in the outer function must have the proper value *before* the outer function is called that returns the inner function. (As the reader might recall, I have stumbled on that myself in JSX:object.js several times.) In a library that uses closures for optimization and did not start out with the module pattern, this can mean that at one point the whole library must use the module pattern, i. e. all its definitions must be enclosed in one inner function. (I am currently in the process of refactoring JSX:object.js like that so that I do not have to care any longer about execution order, potentially having to sacrifice backwards-compatibility along the way.) > One case where the closure variant would be preferred is if the contents > of then "names" array would take a long time to compute, or if they were > fetched from a remote source. One, and certainly not the only or most likely case. PointedEars -- realism: HTML 4.01 Strict evangelism: XHTML 1.0 Strict madness: XHTML 1.1 as application/xhtml+xml -- Bjoern Hoehrmann