TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

ES6 Coding Style Guide

7 点作者 elierotenberg大约 10 年前

3 条评论

AprilArcus大约 10 年前
I agree with and appreciate nearly all of these suggestions. Just a few well-intentioned quibbles:<p>&gt; Arrays MUST be created using the Array syntax literal.<p>This does enhance readability when vending an empty array, but when you know how large an array will need to be in advance, new Array(someLength) is an important pattern. Consider this naïve implementation of Clojure&#x27;s &quot;reductions&quot; or Haskell&#x27;s &quot;scanl&quot;:<p><pre><code> let reductions = (callback, initial, array) =&gt; array.reduce( (memo, element) =&gt; { memo.push( callback(memo[memo.length - 1], element) ); return memo; }, [initial]); </code></pre> This will call push() array.length times. If the backing store for Array is a typical vector implementation that reallocates every time its length exceeds a power of 2, this means incurring log₂(array.length) reallocations, and suffering the concomitant heap fragmentation. However, if we pre-allocate an array of the appropriate size once before entering the loop,<p><pre><code> let reductions = (callback, initial, array) =&gt; { let result = new Array(array.length + 1); result[0] = initial; array.forEach( (element, index) =&gt; result[index + 1] = callback(result[index], element) ); return result; }; </code></pre> we can avoid creating unnecessary work for the VM.<p>&gt; Regular (named and hoisted) function declarations SHOULD be used instead of anonymous functions by default.<p>I think this is really bad advice. Hoisting makes imperative code harder to reason about; any time that it would actually make a difference, the un-hoisted behavior is the one I would want. The verbosity of let myFunction = function(x,y) {}; over myFunction(x,y) {} is definitely unsightly, but it&#x27;s worth my peace of mind.<p>&gt; undefined MUST NOT be used, void 0 MUST be used instead. [...] Pure convention. Also void 0 looks more l33t.<p>undefined should be preferred on grounds of readability. If ES3 compatibility is really important, you can configure babel to emit void 0 in place of undefined with the spec.undefinedToVoid optional transformer.
cnp大约 10 年前
Really nice (and a fantastic JavaScript overview in general), though the MUST and SHOULD&#x27;s get a bit wearing on the eyes after some time; perhaps a simple <i></i>bold<i></i> would suffice?
glaciusNexus大约 10 年前
Nice !