<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[DeepScan - Medium]]></title>
        <description><![CDATA[DeepScan is a cutting-edge static analysis tool providing comprehensive inspection for your JavaScript code. - Medium]]></description>
        <link>https://medium.com/deepscan?source=rss----8588eac5caa4---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>DeepScan - Medium</title>
            <link>https://medium.com/deepscan?source=rss----8588eac5caa4---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 17 Jun 2026 14:21:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/deepscan" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Detecting JavaScript Errors and Code Smells with Static Analysis]]></title>
            <link>https://medium.com/deepscan/detecting-javascript-errors-and-code-smells-with-static-analysis-504787b0acad?source=rss----8588eac5caa4---4</link>
            <guid isPermaLink="false">https://medium.com/p/504787b0acad</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[static-analysis]]></category>
            <dc:creator><![CDATA[Kangho Kim]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 04:05:30 GMT</pubDate>
            <atom:updated>2018-04-24T04:05:29.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*looOrO7GeQVCttFg47qtUA.png" /></figure><p>JavaScript is the most commonly used programming language and has been at the top of the GitHub annual highlights. Its open source ecosystem will be much bigger as it is widely applied to developing server, mobile, and desktop applications beyond just websites.</p><p>While code bases written in JavaScript are larger, debugging and managing the code bases are getting more difficult especially due to the dynamic features of JavaScript language. But you can significantly reduce this quality cost by catching code defects at the earlier stage of the development cycle.</p><p>Static analysis tools come into play at this stage.</p><p>To help JavaScript folks find static analysis tools helpful, we rummaged our database regarding run-time errors and code smells found by our JavaScript static analysis tool. It was gathered by analyzing code from thousands of public JavaScript and TypeScript projects on GitHub.</p><p>This whitepaper describes how static analysis tools work and shows some types of problems that static analysis tools can prevent. Feel free to download the whitepaper for a look on how static analysis tools cope with the troubles of JavaScript.</p><figure><a href="https://deepscan.io/docs/whitepapers/deepscan_detecting-javascript-errors-and-code-smells-with-static-analysis.pdf?utm_source=deepscan&amp;utm_medium=email&amp;utm_campaign=deepscan-2018-apr"><img alt="" src="https://cdn-images-1.medium.com/max/261/1*3hX4U7DKQs_KO7VAPp666Q.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=504787b0acad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deepscan/detecting-javascript-errors-and-code-smells-with-static-analysis-504787b0acad">Detecting JavaScript Errors and Code Smells with Static Analysis</a> was originally published in <a href="https://medium.com/deepscan">DeepScan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Case Studies for Common Pitfalls That JavaScript Developers Should Know]]></title>
            <link>https://medium.com/deepscan/case-studies-for-common-pitfalls-that-javascript-developers-should-know-d7ba6bc91f87?source=rss----8588eac5caa4---4</link>
            <guid isPermaLink="false">https://medium.com/p/d7ba6bc91f87</guid>
            <category><![CDATA[coding-pitfalls]]></category>
            <category><![CDATA[static-analysis]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kangho Kim]]></dc:creator>
            <pubDate>Thu, 24 Aug 2017 08:08:19 GMT</pubDate>
            <atom:updated>2017-11-23T10:09:39.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*l_p_cvcBQANo--vlswOOXw.png" /></figure><p>Recently, I saw an awful comic about the coding pitfall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PfFGDTfScfavjnG5wrHLKA.jpeg" /><figcaption>from <a href="https://www.reddit.com/r/funny/comments/4x28gw/this_is_why_code_reviews_are_a_good_thing/">reddit</a></figcaption></figure><p>After some laugh, I regretted not having shared our experiences and practices about coding pitfall. The scientists would have been alive if they knew <a href="https://deepscan.io/docs/rules/bad-assign-in-condition">this rule</a>, RIP.</p><p>Okay, let’s get down to business.</p><p>As can be seen from the <a href="https://octoverse.github.com/">GitHub statistics</a> recently announced, JavaScript is very popular. However, because of its dynamic nature, JavaScript is more challenging to manage its code quality as codebases become larger.</p><p>With this concern, I have developed a JavaScript static analyzer (<a href="https://deepscan.io">DeepScan</a>) that finds potentially error-prone code without executing the code. Instead of detecting mere code convention violations, it tries to find ECMAScript exceptions and common mistakes developers make.</p><p>For benchmarking the analyzer, we have applied it to in-house projects and also to various open source projects in GitHub. Although the analyzed sources are committed ones after local development, there are still some errors not caught by human developers and testing.</p><p>In this article, I’ll share common pitfalls found in the benchmark. I hope this article will give you some insight on what you consider in JavaScript development.</p><h3>1. Misuse of typeof operator</h3><p>Possible return values of typeof operator are the following strings:</p><ul><li>“undefined”</li><li>“object”</li><li>“boolean”</li><li>“number”</li><li>“string”</li><li>“symbol”</li><li>“function”</li></ul><p>Unlike the right operand of instanceof in Java, it’s not arbitrary. When a developer compares with the value not listed above, it will always result in false undesirably.</p><p>I found some developers seem to use typeof operator to check if an object is an array type.</p><pre>var param = typeof pChangeMessageList == &quot;Array&quot; ? pChangeMessageList.join(&#39;|&#39;) : pChangeMessageList;</pre><p>Isn’t it natural?</p><p>But, “Array” (or “array”) is not a valid return value of typeof and pChangeMessageList will not be joined even when it is really an array. Developers should use Array.isArray() or utility functions in jQuery, lodash, ….</p><p>Also, because the return value is a string, typo is common.</p><p>In <a href="https://github.com/apache/ambari">Apache Ambari</a>, let’s see a typo udefined: <a href="https://github.com/apache/ambari/blob/61abd869b64eae39b77aa5da143034887dca3875/ambari-web/app/controllers/main/host/details.js">app/controllers/main/host/details.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62afd733aaae079fb84d54995bae150/href">https://medium.com/media/e62afd733aaae079fb84d54995bae150/href</a></iframe><p>In other projects, I also could see typo like undeifned.</p><pre>if (typeof Object.prototype[k] != &quot;undeifned&quot; &amp;&amp; Object.prototype[k] === this._table[k]) continue;</pre><p>Pleasantly, I found above problems were fixed by the refactoring commit like <a href="https://github.com/apache/ambari/commit/6c38d84b1152807c0b94f175e090d90ad0c74a28#diff-9a408c49bd06f1c8c99617d8a738a6e7">this</a>.</p><p>Note that typeof operator returns <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof">a predefined string only</a>.</p><h3>2. Use of undeclared variables</h3><p>Let’s look at the example first. (Our in-house code)</p><pre>var rows = [];<br>for (var i = 0; i &lt; args.length; i++) {<br>    var obj = {<br>        patternId: <strong>patternId</strong><br>    };<br>    rows.push(obj);<br>}</pre><pre><strong>var patternId</strong> = $(&quot;#pattern&quot;).attr(&quot;patternId&quot;);<br>$.post(&#39;/delete.do&#39;, { data: JSON.stringify(rows) });</pre><p>Since patternId variable is used before its declaration and assignment, obj has a wrong value.</p><p>In Java, the compiler will grumble about this “Unresolved variable” case. But the lifecycle of JavaScript variables allows above prior-usage pattern because patternId variable is hoisted and initialized as undefined immediately when the surrounding function is executed.</p><p>Just use let. It will throw ReferenceError(“patternId is not defined”) and you cannot send erroneous data to the server at least.</p><p>I recommend you read this article about <a href="https://rainsoft.io/variables-lifecycle-and-why-let-is-not-hoisted/">var hoisting</a>. Frankly, I did not know exactly the difference between var and let.</p><p>For your information, this is why some JavaScript coding conventions say a developer should declare all the variables in the beginning of function body.</p><h3>3. Unused and Uninitialized variables</h3><p>Unused variables can cause a problem. Below in-house code was appending userName parameter and trimming special characters.</p><pre>if ($.browser.msie == true) {<br>    var <strong>target</strong> = url + &quot;userName&quot; + userName;<br>    <strong>target</strong> = url.replace(/\.|\?|\&amp;|\/|\=|\:|\-|\s/gi,&quot;&quot;);<br>}</pre><p>But target variable appended with userName is not used afterwards, the final value of target variable does not include the parameter.</p><p>I’ll bet the developer intended to write target = target.replace but he made a mistake. To avoid this kind of mistake, double check when you are not using a variable that is assigned a value.</p><p>Unused variable case like the above is not specific to JavaScript, but the following uninitialized case is so.</p><p>In <a href="https://github.com/Modernizr/Modernizr">Modernizr</a>, you can see an incorrect use of uninitialized variable html5: <a href="https://github.com/Modernizr/Modernizr/blob/9f4f44bb4906718f85ac6b5a9636d1e71897375a/src/html5shiv.js">/src/html5shiv.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b63fc168fae1df737e8104dd5ba7c0b/href">https://medium.com/media/8b63fc168fae1df737e8104dd5ba7c0b/href</a></iframe><p>You can see html5 variable declaration at line 7. It’s here because a developer wanted “Take the html5 variable out of the html5shiv scope so we can return it”.</p><p>But, 2 years later, another developer made <a href="https://github.com/Modernizr/Modernizr/commit/ae340ed67613336aa1be6a2d602836d7e170b335">a commit</a> adding var at line 23. As a result, html5 variable returned at line 38 has undefined value.</p><p>If you are Java developer, the compiler will complain this “Uninitialized variable” but JavaScript developer can’t get such help. That’s why I developed <a href="https://deepscan.io/docs/rules/uninitialized-local-var">this rule</a> for checking the use of uninitialized variable.</p><h3>4. Use of constant condition</h3><p>Check your code again if you are using constant or redundant checks in conditional statements.</p><p><strong>null/undefined</strong></p><p>In <a href="https://github.com/apache/ambari">Apache Ambari</a>, let’s see an argument check: <a href="https://github.com/apache/ambari/blob/0fe39d5e856f43ccfca00a70b9354e8bf899e768/ambari-web/app/utils/number_utils.js">app/utils/number_utils.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef190b1f1de1a9a8ad8e2ceb260e8d80/href">https://medium.com/media/ef190b1f1de1a9a8ad8e2ceb260e8d80/href</a></iframe><p>Condition str==undefined is always false because of the previous condition str==null. Note that undefined equals to null by non-strict equality operator ==. The condition is completely unnecessary.</p><p>Also when I review code, I often see argument check code like:</p><pre>if (arg == null || arg == undefined || arg == &#39;&#39;)</pre><p>You can just do dead simple because == operator in JavaScript treats equally null, undefined and empty string &#39;&#39;.</p><pre>if (!arg)</pre><p><strong>Nested if</strong></p><p>In <a href="https://github.com/apache/ambari">Apache Ambari</a>, let’s see an argument check: <a href="https://github.com/apache/ambari/blob/b175d8f697c8690e719c8a3f8dbcd20df073d2a6/ambari-web/app/controllers/main/host/bulk_operations_controller.js">app/controllers/main/host/bulk_operations_controller.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79037f972777b94d9157dad3b4c101a4/href">https://medium.com/media/79037f972777b94d9157dad3b4c101a4/href</a></iframe><p>turn_off at line 12 is always false because it’s in false branch of the condition at line 5. Therefore line 13 is never executed and included_hosts parameter is never set.</p><p>Similar problem can be found in <a href="https://github.com/adobe/brackets">Adobe Brackets</a>: <a href="https://github.com/adobe/brackets/blob/074382aaa2b3ccf16f64d3be05b6229182865b04/src/extensions/default/UrlCodeHints/main.js">src/extensions/default/UrlCodeHints/main.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f29f0ca4764aabe0934725fac98e87d/href">https://medium.com/media/1f29f0ca4764aabe0934725fac98e87d/href</a></iframe><p>self.cachedHints at line 11 is null because it’s checked by the condition if (this.cachedHints) at line 3. So line 12 is never executed and it implies you need to check the logic for rejection. Whether the rejection was unnecessary or processed at the wrong branch.</p><p>As a rule of thumb, check the logic again when you see constant condition and remove it if it turns out to be unnecessary.</p><h3>5. Inconsistent null checks</h3><p>Check for null arguments should be performed consistently.</p><p>Let’s see an inconsistent example in <a href="https://github.com/hakimel/reveal.js">reveal.js</a>: <a href="https://github.com/adobe/brackets/blob/074382aaa2b3ccf16f64d3be05b6229182865b04/src/extensions/default/UrlCodeHints/main.js">plugin/markdown/markdown.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7d054eb9d6a40d40df71fcfde91b0a8/href">https://medium.com/media/b7d054eb9d6a40d40df71fcfde91b0a8/href</a></iframe><ul><li>At line 3, argument element is checked whether it is null.</li><li>At line 11, it is accessed without any check.</li><li>It can cause TypeError when null argument is passed. The check is needed also here if the argument can be null.</li></ul><p>Another example in <a href="https://github.com/apache/ambari">Apache Ambari</a>: <a href="https://github.com/apache/ambari/blob/a61a83fae8170ebf3be7d4bc58b91b75dc7e0b32/ambari-web/app/mixins/common/serverValidator.js">app/mixins/common/serverValidator.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/404628fa1d27529220b157a5d255066c/href">https://medium.com/media/404628fa1d27529220b157a5d255066c/href</a></iframe><ul><li>At first, argument data is checked and a warning is printed.</li><li>But flow does not stop!</li><li>Falsy value is saved as recommended at line 5.</li><li>Finally, TypeError is thrown when accessing resources array at line 6.</li></ul><p>For your information, check for data argument was removed in the current code. Like this, consider the following when you check an argument:</p><ul><li>Remove the check itself if the argument cannot be null.</li><li>Add checks consistently for each use.</li></ul><h3>6. Null pointer</h3><p>I’ve found some cases trying to access the property of null object. It is often found in an else branch or inline initialization block. Seems that developers used up all their energy in coding the main execution flow.</p><p>Let’s see <a href="https://github.com/adobe/brackets">Adobe Brackets</a>: <a href="https://github.com/adobe/brackets/blob/074382aaa2b3ccf16f64d3be05b6229182865b04/src/language/HTMLInstrumentation.js">src/language/HTMLInstrumentation.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fef88f14067a5f67ff123fee09123cf/href">https://medium.com/media/7fef88f14067a5f67ff123fee09123cf/href</a></iframe><p>At line 20 (else branch), match variable is set to null. But match.mark is accessed at the end of the function, causing TypeError.</p><p>I think the fix should be return match &amp;&amp; match.mark; and I happily found the problem is gone by <a href="https://github.com/adobe/brackets/commit/1cfb24fd9313233d399660f9b9b202ba40ec96a9#diff-a2486b8e2efec7415bca07a4043edd5b">this commit</a> saying “This fixes `TypeError: Cannot read property ‘mark’ of null`”. Good job!</p><p>Another case in <a href="https://github.com/jquery/jquery-mobile">jQuery Mobile</a>: <a href="https://github.com/jquery/jquery-mobile/blob/a0a1763174f81b909e190797acb35eca86be0d29/demos/popup-alignment/popup.alignment.js">demos/popup-alignment/popup.alignment.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be6c72b8d634ad16b76073f0ce3b88d2/href">https://medium.com/media/be6c72b8d634ad16b76073f0ce3b88d2/href</a></iframe><p>See align.x at line 11 (inline initialization block). Because align is uninitialized at that point, accessing align.x throws TypeError.</p><p>Seems that the desire to save one line of code caused this error. I guess the developer’s intent as follows:</p><pre>    var arX = parseFloat( ar[ 0 ] );<br>    align = {<br>        x: arX,<br>        y: ar.length &gt; 1 ? parseFloat( ar[ 1 ] ) : arX<br>    };</pre><p>Null pointer is one of the major runtime errors. Therefore, if you set a variable to null or access an object in initialization block, pay attention to the way the variable is used afterwards or the object is properly initialized.</p><h3>7. Misuse of return values</h3><p>There are two erroneous cases about the return value of a function:</p><ul><li>You use a return value from the function which returns nothing</li><li>You do not use a return value from the function which has no side effect</li></ul><p>Let’s see the first case in <a href="https://github.com/codemirror/CodeMirror">CodeMirror</a>: <a href="https://github.com/codemirror/CodeMirror/blob/28abf35b52c31726ad273ad6c82dc79077f7689a/mode/vb/vb.js">mode/vb/vb.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/354320c280dcc040652a9b78571ad3bc/href">https://medium.com/media/354320c280dcc040652a9b78571ad3bc/href</a></iframe><p>Function dedent does not return anything. So if (dedent(stream, state)) is always false and ERRORCLASS is not returned.</p><p>When should ERRORCLASS be returned? I guess that might be when dedent returns zero or negative index. In other words, it implies that a return statement is missing in the function.</p><p>And the second case is often found when using built-in API of JavaScript string.</p><p>Below is our in-house code.</p><pre><strong>var</strong> retString = i18n.RESTOREDLG_SUCCESS + &#39; : ( &#39; + returnValue.unitServiceName + &#39; )&#39;;<br><strong>if</strong>(returnValue.isRenamed) {<br>    <strong>retString.concat</strong>(&#39; , &#39;+i18n.RESTOREDLG_RENAME);<br>}<br>Notify.success(retString);</pre><p>String.prototype.concat() always returns a new string without side effect. But the developer missed the return value of it. Therefore, users see the same notification message regardless of his action.</p><p>For the API of array, there is similar confusion. Array.prototype.concat() returns a new array without side effect while Array.prototype.push() appends an item to the input array itself.</p><p>It will be better if a tool can check these kinds of confusion rather than the problem is found after deployment. This is why I developed <a href="https://deepscan.io/docs/rules/no-effect-call">this rule</a> for checking an ignored result of built-in APIs.</p><h3>8. Bad operators</h3><p>Next let’s see bad uses of assignment, bitwise, and negation operators.</p><p>See below negation operator in our in-house code.</p><pre>if (!data instanceof Object) {</pre><p>The expression is evaluated as (!data) instanceof Object, comparing boolean with Object. I bet the developer wanted !(data instanceof Object). If not, using parentheses will be helpful to indicate the rare situation.</p><p>The second is about bitwise operator. See <a href="https://github.com/fzaninotto/uptime">uptime</a>: <a href="https://github.com/fzaninotto/uptime/blob/8b6fe4bfdbf9c5d3f6d49634e336909e4d95a487/lib/pollers/webpagetest/webPageTestPoller.js">lib/pollers/webpagetest/webPageTestPoller.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb5412e7a3525cb6205a95ae16f83c85/href">https://medium.com/media/cb5412e7a3525cb6205a95ae16f83c85/href</a></iframe><p>config.webPageTest.testOptions | {} is definitely typo of config.webPageTest.testOptions || {} because bitwise operator in the former converts an object to NaN, resulting zero.</p><p>Therefore, you should check it out when the bitwise operator is used in the initialization pattern like bar | {}.</p><p>Although JSHint can prohibit the use of bitwise operator, it might be annoying because it detects all uses literally. For example, below code seems correct to me while JSHint complains.</p><pre>function foo(option) {<br>    const OPTION_1 = 1 &lt;&lt; 0;<br>    const OPTION_2 = 1 &lt;&lt; 1;</pre><pre>    let isOption1 = option | OPTION_1;</pre><p>For the assignment operator, let’s see <a href="https://github.com/MichMich/MagicMirror">MagicMirror</a>: <a href="https://github.com/MichMich/MagicMirror/blob/94169800968eb944c7ff7995600e0a282c89dcae/modules/default/alert/alert.js">modules/default/alert/alert.js</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1498f9bf197e5ab1f193a75246ff0fe2/href">https://medium.com/media/1498f9bf197e5ab1f193a75246ff0fe2/href</a></iframe><p>At line 6, you can see an assignment operator in conditional statement. As a result, show_notification is called even when the payload type is not “notification”.</p><p>Pay attention to the assignment operator if it’s in conditional statement.</p><h4>Thanks for reading!</h4><p>JavaScript is easy to learn but error-prone unless a developer is extra careful.</p><p>So I wanted to share some patterns I’ve found while developing our JavaScript static analysis tool, <a href="https://deepscan.io">DeepScan</a>. I hope being aware of these patterns will be helpful to developers.</p><p>Tell me if you have an idea for the pattern to be checked in JavaScript. We will realize and spread that idea!</p><p>You can find me here:</p><ul><li>Official Website: <a href="https://deepscan.io">https://deepscan.io</a></li><li>Email: <a href="mailto:support@deepscan.io">support@deepscan.io</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7ba6bc91f87" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deepscan/case-studies-for-common-pitfalls-that-javascript-developers-should-know-d7ba6bc91f87">Case Studies for Common Pitfalls That JavaScript Developers Should Know</a> was originally published in <a href="https://medium.com/deepscan">DeepScan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A few things every new React developer should know (part 2)]]></title>
            <link>https://medium.com/deepscan/a-few-things-every-new-react-developer-should-know-part-2-913e089e8fc2?source=rss----8588eac5caa4---4</link>
            <guid isPermaLink="false">https://medium.com/p/913e089e8fc2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[static-analysis]]></category>
            <dc:creator><![CDATA[Kangho Kim]]></dc:creator>
            <pubDate>Thu, 20 Jul 2017 06:14:00 GMT</pubDate>
            <atom:updated>2017-07-20T06:13:59.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*z3-OY_9f9f3gH08W6zQjoA.png" /></figure><p><a href="https://medium.com/deepscan/a-few-things-every-new-react-developer-should-know-part-1-93940e11800a">In the previous post</a> I discussed the following mistake patterns of React with the examples from open sources.</p><ul><li>Typo of React API</li><li>Incorrect return value from render()</li><li>Invalid event handler function</li><li>…</li></ul><p>Today I will go into additional pitfalls. These are as follows:</p><ul><li>Invalid event handler of string type</li><li>Event handler not bound with this</li><li>Incorrect style property</li><li>Missing key property in a React element</li></ul><p>Let’s start part two. Before you proceed, I recommend reading <a href="https://medium.com/deepscan/a-few-things-every-new-react-developer-should-know-part-1-93940e11800a">the previous post</a>.</p><p>In this article, I explain other confusing things for new React developers with the examples from open source projects.</p><h3>1. Invalid event handler of string type</h3><p>In HTML, an event handler is specified as a string. For example, script code inside string literal represents onclick handler like &lt;image src=&quot;hello.png&quot; onclick=&quot;alert(&#39;Hi&#39;)&quot; /&gt;.</p><p>However, only function objects are allowed for React’s event handler. So when you specify an event handler as a string, React throws an exception.</p><p>In the test code of <a href="https://github.com/facebook/react">React</a>, you can see a test for this invalid string-typed event handler.</p><p>Let’s see an example: <a href="https://github.com/facebook/react/blob/197e184859140524e1de92abfc6d678bbc85b340/src/renderers/__tests__/EventPluginHub-test.js">__tests__/EventPluginHub-test.js</a> (Line numbers are different because only relevant parts are shown.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f689078edc4cbed9753bb06ccd0c04d/href">https://medium.com/media/5f689078edc4cbed9753bb06ccd0c04d/href</a></iframe><p>Note that you should not write an event handler like &lt;div onClick=&quot;console.log(&#39;clicked&#39;)&quot;&gt;. Right way is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/856f26ef8e664551d60836ff8a57271b/href">https://medium.com/media/856f26ef8e664551d60836ff8a57271b/href</a></iframe><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/bad-event-handler/">BAD_EVENT_HANDLER</a> rule can prevent developers from making this mistake by checking whether a string is specified as a React event handler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmbU5PLka2T1q89o7Nu7RQ.png" /><figcaption>Invalid event handler of string type</figcaption></figure><h3>2. Event handler not bound with this</h3><p>Let’s look at another thing about React event handler.</p><p>Since React does not provide this object when calling an event handler, a TypeError exception is thrown when you access the property of this in the event handler.</p><p>To solve this problem, you need to do one of the following:</p><ul><li>Use Function.prototype.bind() to explicitly bind this with the handler</li><li>Use an arrow function of ES6 that automatically bind this</li></ul><p>Note that React.createClass() automatically binds member functions to this, so you need to be especially careful when converting it to a ES6 class.</p><p>In the below <a href="https://github.com/Automattic/wp-calypso/blob/a843773ea709cca3b078a4391ae295335794a1ad/client/my-sites/site-settings/form-general.jsx">site-settings/form-general.jsx</a> example from open source project <a href="https://github.com/Automattic/wp-calypso">wp-calypso</a>, an error occurs because unbound this.trackUpgradeClick function is specified as an event handler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4de0cb1e0a4c362067dc434125ed174/href">https://medium.com/media/a4de0cb1e0a4c362067dc434125ed174/href</a></iframe><p>I’m glad to see this problem is fixed by changing trackUpgradeClick as an arrow function. (Check <a href="https://github.com/Automattic/wp-calypso/commit/ea5848efa50b071da28529580d2e7778a2ee2dc9">this commit</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*DdJ1IaSqYe2D2zYf.png" /><figcaption>Change to an arrow function for a valid binding</figcaption></figure><p>I think this kind of mistakes can be common especially to front-end developers not familiar with ES6.</p><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/event-handler-invalid-this/">EVENT_HANDLER_INVALID_THIS</a> rule can prevent developers from making this mistake by checking whether an event handler function is bound to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7v8FHrzQEtU7e-JFmqDhA.png" /><figcaption>Invalid event handler functions not bound with ‘this’</figcaption></figure><p>You can track down the problem easily because the alarm says this is accessed in trackUpgradeClick function body.</p><h3>3. Incorrect style property</h3><p>Similar to the case that an event handler cannot be specified as a string, React’s style property does not accept a string that represents CSS rules.</p><p>Unlike HTML, you should always specify style property as an object. React will throw an exception when you specify a value other than an object, null, or undefined.</p><p>You can see this case in the test code of React. (<a href="https://github.com/facebook/react/blob/197e184859140524e1de92abfc6d678bbc85b340/src/renderers/dom/shared/__tests__/ReactDOMComponent-test.js">__tests__/ReactDOMComponent-test.js</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ebc2184207f45fbec7af45ff9853c50/href">https://medium.com/media/2ebc2184207f45fbec7af45ff9853c50/href</a></iframe><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/bad-style-prop/">BAD_STYLE_PROP</a> rule can prevent developers from making this mistake by checking whether style property is specified as a non-object value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4xwxu35eI2up7h8_dOwRw.png" /><figcaption>Invalid non-object ‘style’ property</figcaption></figure><h3>4. Missing key property in a React element</h3><p>When updating the DOM tree React optimizes rendering through <a href="https://facebook.github.io/react/docs/reconciliation.html#recursing-on-children">diff algorithm utilizing </a><a href="https://facebook.github.io/react/docs/reconciliation.html#recursing-on-children">key property</a>.</p><p>So, rendering can be inefficient if each child element of a DOM node does not have a key property. Also, React warns about this situation.</p><p>Therefore, you should specify a key property when you define a child element in the collection.</p><p>Below <a href="https://github.com/uber/react-vis/blob/baf8a946bc39b9e36c597107f347e532b8b26f62/docs/docs-app/components/home.js">components/home.js</a> code from open source project <a href="https://github.com/uber/react-vis">react-vis</a> has missing key property problem for the collection stored at content.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9416604a12e92ed0f1abfb28328272f6/href">https://medium.com/media/9416604a12e92ed0f1abfb28328272f6/href</a></iframe><p>This problem was fixed in the later <a href="https://github.com/uber/react-vis/commit/6d003947f5a9807f129be8d0cb463c819d617820">commit</a> by adding a key property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*MCn6mysUdkZ2mhWg.png" /><figcaption>Add a ‘key’ property for the child element</figcaption></figure><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/missing-key-prop/">MISSING_KEY_PROP</a> rule can prevent developers from making this mistake by checking each element in the collection for the existence of key property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWXrGsAQSGJPwQ6blZq2ig.png" /><figcaption>Child React element does not have a ‘key’ prop</figcaption></figure><h4>Thanks for reading!</h4><p>You can check the above codes by directly pasting it on this <a href="https://deepscan.io/demo/">Demo</a> page.</p><p>I’ll continue to share what will be helpful in React and JavaScript development. If you have feedback or suggestions, you can find me here:</p><ul><li>Official Website: <a href="https://deepscan.io">https://deepscan.io</a></li><li>Email: <a href="mailto:support@deepscan.io">support@deepscan.io</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=913e089e8fc2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deepscan/a-few-things-every-new-react-developer-should-know-part-2-913e089e8fc2">A few things every new React developer should know (part 2)</a> was originally published in <a href="https://medium.com/deepscan">DeepScan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A few things every new React developer should know (part 1)]]></title>
            <link>https://medium.com/deepscan/a-few-things-every-new-react-developer-should-know-part-1-93940e11800a?source=rss----8588eac5caa4---4</link>
            <guid isPermaLink="false">https://medium.com/p/93940e11800a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[static-analysis]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Kangho Kim]]></dc:creator>
            <pubDate>Tue, 04 Jul 2017 14:13:20 GMT</pubDate>
            <atom:updated>2019-03-07T03:02:25.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/114/1*z3-OY_9f9f3gH08W6zQjoA.png" /></figure><p>My colleagues and I set out to build JavaScript static analysis tool <a href="https://deepscan.io/">DeepScan</a> which aims to support React well in addition to common JavaScript errors.</p><p>We have developed dozens of <a href="https://deepscan.io/docs/rules/#react">React validation rules</a> by gathering common pitfalls and feedback from React developers. Among them, I will share a few rules that new React developers are easy to make mistakes.</p><p>Let’s start part one.</p><p>React is a decent JavaScript UI library that Facebook leads the development and marketing.<br>It’s getting a lot of popularity with features such as component structure, state management separated from DOM, fast rendering, and JavaScript-centric implementation. But it’s also a bit difficult to front-end developers who are accustomed to direct handling of DOM and working with separate HTML.</p><p>In this article, I explain a few difficult things for new React developers with the examples from open source project <a href="https://github.com/Automattic/wp-calypso">wp-calypso</a>.</p><h3>1. Typo of React API</h3><p>Developers often make a typo in the React component’s lifecycle method or PropTypes.</p><h4>Lifecycle methods</h4><p>React component has lifecycle methods that are invoked when the component is created or a state change occurs.</p><ul><li>componentWillMount()</li><li>componentDidMount()</li><li>componentWillUnmount()</li><li>componentWillReceiveProps()</li><li>shouldComponentUpdate()</li><li>componentWillUpdate()</li><li>componentDidUpdate()</li><li>render()</li></ul><p>But these names are a bit long and camelCased, so it’s easy to make a typo.</p><p>Let’s see an example: <a href="https://github.com/Automattic/wp-calypso/blob/7b44d03539f5519d0448aa071d714f53245f3804/client/components/data/sync-reader-follows/index.js">sync-reader-follows/index.js</a></p><pre>import { Component } from &#39;react&#39;;<br><br>class SyncReaderFollows extends Component {<br>    check() {<br>        if ( this.props.shouldSync ) {<br>            this.props.requestFollows();<br>        }<br>    }<br> <br>    componentDidMount() {<br>        this.check();<br>    }<br> <br><strong>    componentDidUpate() {</strong><br>        this.check();<br>    }<br> <br>    render() {<br>        return null;<br>    }<br>}</pre><p>The developer intented to call check() in componentDidUpdate after state has changed, but it is not called because of a typo componentDidUpate.</p><h4>PropTypes</h4><p>React’s PropTypes allows to specify the types of properties (whether they are required, the type of values, etc.) that a component has.</p><pre>import React from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br><br>export default class Item extends React.Component {<br><strong>    static propTypes = {</strong><br>        id: PropTypes.number.isRequired,<br>        comment: PropTypes.string,<br>    }<br>}</pre><p>PropTypes is defined as camelCased propTypes (see above), but developers sometimes use it as PropTypes (see below example <a href="https://github.com/Automattic/wp-calypso/blob/0f9275a3ceef14565f9cfb58918967186633092b/client/components/share/google-plus-share-preview/index.js">google-plus-share-preview/index.js</a>).</p><pre>import React, { PureComponent, PropTypes } from &#39;react&#39;;<br>import { localize } from &#39;i18n-calypso&#39;;<br>import { truncateArticleContent } from &#39;../helpers&#39;;<br><br>export class GooglePlusSharePreview extends PureComponent {<br><strong>    static PropTypes = {</strong><br>        articleUrl: PropTypes.string,<br>        externalProfilePicture: PropTypes.string,<br>        externalProfileUrl: PropTypes.string,<br>        externalName: PropTypes.string,<br>        imageUrl: PropTypes.string,<br>        message: PropTypes.string,<br>    };<br>}</pre><p>PropTypes check for GooglePlusSharePreview component is not performed because of a typo PropTypes.</p><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/react-api-typo/">REACT_API_TYPO</a> rule can prevent developers from making this mistake by finding these typos. Also, developers can easily fix the code by using the suggested method name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mR5M-2SB5yUDIlM_9eDoPA.png" /><figcaption>A typo for ‘propTypes’</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwMa7LXSDNQ3J5IsnbwQKg.png" /><figcaption>A typo for ‘componentDidUpdate’</figcaption></figure><h3>2. Incorrect return value from render()</h3><p>React’s render function returns a DOM tree (React element) to display in the UI. When there is no information to display, it can return null or false. An error occurs if any other value is returned.</p><p>Let’s see an example: <a href="https://github.com/Automattic/wp-calypso/blob/2c00bb4cb7310560f9111313b04143caed5079ed/client/my-sites/plugins/plugin-site-update-indicator/index.jsx">plugin-site-update-indicator/index.jsx</a></p><pre>var React = require( &#39;react&#39; );<br><br>module.exports = React.createClass( {<br>    render: function() {<br>        if ( ! this.props.site || ! this.props.plugin ) {<br><strong>            return;</strong><br>        }<br>        if ( this.props.site.canUpdateFiles &amp;&amp;<br>                ( ( this.props.site.plugin.update &amp;&amp; ! this.props.site.plugin.update.recentlyUpdated ) || this.isUpdating() ) ) {<br>            if ( ! this.props.expanded ) {<br>                /* eslint-disable wpcalypso/jsx-gridicon-size */<br>                return &lt;Gridicon icon=&quot;sync&quot; size={ 20 } /&gt;;<br>                /* eslint-enable wpcalypso/jsx-gridicon-size */<br>            }<br>     <br>            return this.renderUpdate();<br>        }<br>        return null;<br>    }<br>} );</pre><p>The developer would have checked props and returned immediately because there is nothing to display.</p><p>However, render function of React can only return React element, null, and false. So when undefined is returned, an exception will be thrown and lifecycle methods to be executed after the rendering will not be invoked.</p><p>It’s easy to get confused, right?</p><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/bad-render-return-value/">BAD_RENDER_RETURN_VALUE</a> rule can prevent developers from making this mistake by checking the return value of render() and suggesting the proper values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7PlvPEWYXPUuSjqgd3zgdg.png" /><figcaption>Incorrect return value from render()</figcaption></figure><h3>3. Invalid event handler function</h3><p>Event handler in React should be a function object, but a developer might make a mistake to use an invalid one.</p><p>Let’s see an example: <a href="https://github.com/Automattic/wp-calypso/blob/5a0ad4ef359b404eec128eec336e1f417acd297e/client/my-sites/people/edit-team-member-form/index.jsx">edit-team-member-form/index.jsx</a></p><pre>import React, { Component } from &#39;react&#39;;<br><br>const EditUserForm = React.createClass( {<br><strong>    recordFieldFocus( fieldId ) {<br>        analytics.ga.recordEvent( &#39;People&#39;, &#39;Focused on field on User Edit&#39;, &#39;Field&#39;, fieldId );<br>    },</strong><br><br>    handleChange( event ) {<br>        this.setState( {<br>            [ event.target.name ]: event.target.value<br>        } );<br>    },<br><br>    renderField( fieldId ) {<br>        let returnField = null;<br>        switch ( fieldId ) {<br>            case &#39;roles&#39;:<br>                returnField = (<br>                    &lt;RoleSelect<br>                        id=&quot;roles&quot;<br>                        name=&quot;roles&quot;<br>                        key=&quot;roles&quot;<br>                        siteId={ this.props.siteId }<br>                        value={ this.state.roles }<br>                        onChange={ this.handleChange }<br><strong>                        onFocus={ this.recordFieldFocus( &#39;roles&#39; ) }</strong><br>                    /&gt;<br>                );<br>                break;<br>        }<br>    }<br>} );</pre><p>You need to assign a function as onFocus event handler.</p><p>But the result of calling recordFieldFocus() which does not have return statement comes to be undefined. As a result, event handler is not specified correctly and Google Analytics will not track the focus events.</p><p>In this case, you can fix the problem as follows:</p><p>ES5 bind function:</p><pre>onFocus={ this.recordFieldFocus.bind( this, &#39;roles&#39; ) }</pre><p>ES6 arrow function:</p><pre>onFocus={ () =&gt; this.recordFieldFocus( &#39;roles&#39; ) }</pre><p>However, since the above approaches create a new function for each render, there can be a performance issue. It is <a href="https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md">recommended</a> to bind the handler once in the constructor or use separate component.</p><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/missing-return-value/">MISSING_RETURN_VALUE</a> rule can prevent developers from making this mistake by checking the return value of a function. Since the message tells the location of the event handler function, the developer can immediately check the function causing the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*et8lYh9yTOvERcIDvwf9EA.png" /><figcaption>A specified event handler is not a function</figcaption></figure><h3>4. Incorrect property in DOM element</h3><p>React’s DOM element uses camelCased property names apart from the existing DOM property and attribute names.</p><p>Two typical examples are:</p><ul><li>React requires you to use className to specify the class</li><li>React’s click event handler is onClick than onclick. It seems to be particularly confusing to existing frontend developers who are familiar with HTML that is case insensitive.</li></ul><p>Let’s see an example: <a href="https://github.com/Automattic/wp-calypso/blob/c7b9c133e53c053ea0591a61957ecd46b1982bc3/client/my-sites/importer/error-pane.jsx">importer/error-pane.js</a></p><pre>import React, { PropTypes } from &#39;react&#39;;<br><br>export default React.createClass( {<br>    getImportError: function() {<br>        return this.translate(<br>            &#39;%(errorDescription)sTry again or contact support.&#39;, {<br>                args: {<br>                    errorDescription: this.props.description<br>                },<br>                components: {<br><strong>                    a: &lt;a href=&quot;#&quot; onclick={ this.retryImport }/&gt;,</strong><br>                    br: &lt;br /&gt;,<br><strong>                    cs: &lt;a href=&quot;#&quot; onclick={ this.contactSupport } /&gt;</strong><br>                }<br>            }<br>        );<br>    }<br>} );</pre><p>In the above code, click event handler will not be executed.</p><p>In the open source project <a href="https://github.com/ptmt/react-native-macos">react-native-macos</a>, we can find an error that uses frameborder property instead of correct frameBorder property.</p><pre>var React = require(&#39;React&#39;);<br><br>var Modal = React.createClass({<br>  render: function() {<br>    return (<br>      &lt;div&gt;<br>        &lt;div className=&quot;modal&quot;&gt;<br>          &lt;div className=&quot;modal-content&quot;&gt;<br>            &lt;button className=&quot;modal-button-close&quot;&gt;×&lt;/button&gt;<br>            &lt;div className=&quot;center&quot;&gt;<br><strong>              &lt;iframe className=&quot;simulator&quot; src={url} width=&quot;256&quot; height=&quot;550&quot; frameborder=&quot;0&quot; scrolling=&quot;no&quot;&gt;&lt;/iframe&gt;</strong><br>              &lt;p&gt;Powered by &lt;a target=&quot;_blank&quot; href=&quot;https://appetize.io&quot;&gt;appetize.io&lt;/a&gt;&lt;/p&gt;<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div className=&quot;modal-backdrop&quot; /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>});</pre><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/bad-unknown-prop/">BAD_UNKNOWN_PROP</a> rule can prevent developers from making this mistake by checking the property name and providing the proper one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RakOCDqtXRZEhQm4yafenA.png" /><figcaption>‘onclick’ is invalid</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stQenjFM5eWjMjuGhAT6MA.png" /><figcaption>‘frameborder’ is invalid</figcaption></figure><h3>5. Direct use of the return value from render()</h3><p>You might use the ReactComponent instance returned by the ReactDOM.render function.</p><p>This is not recommended because <a href="https://facebook.github.io/react/docs/react-dom.html#render">rendering can happen asynchronously</a> in the future version of React and the ReactComponent instance might not be available as the return value.</p><p>In the open source project <a href="https://github.com/kriasoft/react-starter-kit">react-starter-kit</a> below, the return value of render function is used but this value may be undefined. So a desired initialization may not be executed.</p><p>Let’s see an example: <a href="https://github.com/kriasoft/react-starter-kit/blob/1d6153ed75919075bdd13a7b9715418b546da05f/src/client.js">src/client.js</a></p><pre>import ReactDOM from &#39;react-dom&#39;;<br><br>let appInstance;<br><br>async function onLocationChange(location, action) {<br><strong>    appInstance = ReactDOM.render(</strong><br>      &lt;App context={context}&gt;{route.component}&lt;/App&gt;,<br>      container,<br>      () =&gt; onRenderComplete(route, location),<br>    );<br>}<br><br>if (appInstance) {<br>  // Force-update the whole tree, including components that refuse to update<br>  deepForceUpdate(appInstance);<br>}</pre><p>In this case you need to get the instance through the ref callback function.</p><pre>function cb(instance) {<br>}<br><br>async function onLocationChange(location, action) {<br>    ReactDOM.render(<br>      &lt;App context={context} <strong>ref={cb}</strong>&gt;{route.component}&lt;/App&gt;,<br>      container,<br>      () =&gt; onRenderComplete(route, location),<br>    );<br>}</pre><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/async-render-return-value/">ASYNC_RENDER_RETURN_VALUE</a> rule can prevent developers from making this mistake by checking the direct use of return value from render().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bL5wPUx-ZgJRhzj6FZ1Vg.png" /><figcaption>Do not use the return value from render() directly</figcaption></figure><h3>6. Invalid stopping of an event propagation</h3><p>In HTML, event propagation and default behavior will be aborted when the event handler function returns false.</p><p>However, React uses a separate event system and you must explicitly call stopPropagation() or preventDefault() on the React event object to stop event propagation or prevent the default behavior.</p><p>In the open source project <a href="https://github.com/brave/browser-laptop">browser-laptop</a> below, onMaximizeClick event handler uses the old-fashioned way returning false. So event propagation is not stopped.</p><p>Let’s see an example: <a href="https://github.com/brave/browser-laptop/blob/87428bc2430fd743798ae910a17dcdb585141415/app/renderer/components/navigation/windowCaptionButtons.js">navigation/windowCaptionButtons.js</a></p><pre>const React = require(&#39;react&#39;)<br><br>class WindowCaptionButtons extends ImmutableComponent {<br>  onMaximizeClick (e) {<br>    if (isFullScreen()) {<br>      // If full screen, toggle full screen status and restore window (make smaller)<br>      windowActions.shouldExitFullScreen(getCurrentWindowId())<br>      if (isMaximized()) windowActions.shouldUnmaximize(getCurrentWindowId())<br><strong>      return false</strong><br>    }<br>    return (!isMaximized()) ? windowActions.shouldMaximize(getCurrentWindowId()) : windowActions.shouldUnmaximize(getCurrentWindowId())<br>  }<br><br>  render () {<br>    const props = { tabIndex: -1 }<br><br>    return &lt;div&gt;<br>      &lt;div className=&#39;container&#39;&gt;<br>        &lt;button<br>          {...props}<br>          onClick={this.onMaximizeClick}<br>          title={locale.translation(this.maximizeTitle)}&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  }<br>}</pre><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/bad-event-handler-return-false/">BAD_EVENT_HANDLER_RETURN_FALSE</a> rule can prevent developers from making this mistake by checking whether false is returned from an event handler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLk5j74fiDGNb9V2EPpIZA.png" /><figcaption>Do not return false to stop event propagation</figcaption></figure><h3>7. JavaScript comment in JSX</h3><p>In JSX, developers should attend to using JavaScript comments such as // or /* */.</p><p>If the comment is recognized as a text node of a component, it will be visible on the browser screen. A comment should be enclosed in curly braces like {/* */}.</p><p>In open source project <a href="https://github.com/nikgraf/belle">belle</a>, the comment itself is displayed. Oops!</p><p>Let’s see an example: <a href="https://github.com/nikgraf/belle/blob/d6472a632b2f1c62f6e8954cae659bee3e6d8a9d/examples/components/RatingPlayground.js">components/RatingPlayground.js</a></p><pre>import React from &#39;react&#39;;<br><br>export default React.createClass({<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h2&gt;Rating&lt;/h2&gt;<br><br>        &lt;Card&gt;<br><br>          &lt;Button onClick={ this._updateRatingToThree }&gt;Update Rating to value 3&lt;/Button&gt;<br><br><strong>          //onUpdate should not be called for valueLink</strong><br>          &lt;h3&gt;ValueLink&lt;/h3&gt;<br><br>        &lt;/Card&gt;<br><br>      &lt;/div&gt;<br>    );<br>  }<br>});</pre><p>In this case, write as the following:</p><pre><strong>{/* onUpdate should not be called for valueLink */}</strong><br>&lt;h3&gt;ValueLink&lt;/h3&gt;</pre><p>In the opposite, when you really need “//” literally like &lt;h3&gt;// a is a double slash.&lt;/h3&gt;, it is good to write like &lt;h3&gt;{&quot;// is a double slash.&quot;}&lt;/h3&gt; for clarity.</p><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/bad-jsx-comment/">BAD_JSX_COMMENT</a> rule can prevent developers from making this mistake by checking JavaScript comments in JSX.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKEiUo3czMR-xOJxD1wgvA.png" /><figcaption>JavaScript comment in JSX</figcaption></figure><h3>8. Checking length property directly</h3><p>A child element as undefined, null, true or false is not rendered. Therefore, developers use JSX expression like cond &amp;&amp; &lt;div&gt;…&lt;/div&gt; when they want to render something selectively.</p><p>However, this is not applied for the numeric value 0. For example, if array is empty in array.length &amp;&amp; &lt;div&gt;…&lt;/div&gt;, 0 is displayed on the screen.</p><p>In this case, consider the following:</p><ul><li>Use comparison expression explicitly like array.length &gt; 0</li><li>Add an empty string as OR condition like array.length &amp;&amp; &lt;div&gt;…&lt;/div&gt; || &#39;&#39;</li></ul><p>The open source project <a href="https://github.com/ptmt/react-native-macos">react-native-macos</a> below checks length property directly, so 0 will be displayed when this.props.params is empty.</p><p>Let’s see an example: <a href="https://github.com/ptmt/react-native-macos/blob/5d32075363993191ba94605247992497f70aeb20/website/layout/AutodocsLayout.js">layout/AutodocsLayout.js</a></p><pre>var React = require(&#39;React&#39;);<br><br>var Method = React.createClass({<br>  render: function() {<br>    return (<br>      &lt;div className=&quot;prop&quot;&gt;<br>        &lt;Header level={4} className=&quot;methodTitle&quot; toSlug={this.props.name}&gt;<br>          {this.props.modifiers &amp;&amp; this.props.modifiers.length &amp;&amp; &lt;span className=&quot;methodType&quot;&gt;<br>            {this.props.modifiers.join(&#39; &#39;) + &#39; &#39;}<br>          &lt;/span&gt; || &#39;&#39;}<br>          {this.props.name}<br>          &lt;span className=&quot;methodType&quot;&gt;<br><strong>            ({this.props.params &amp;&amp; this.props.params.length &amp;&amp; this.props.params</strong><br>              .map((param) =&gt; {<br>                var res = param.name;<br>                res += param.optional ? &#39;?&#39; : &#39;&#39;;<br>                return res;<br>              })<br>              .join(&#39;, &#39;)})<br>              {this.props.returns &amp;&amp; &#39;: &#39; + this.renderTypehint(this.props.returns.type)}<br>          &lt;/span&gt;<br>        &lt;/Header&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>});</pre><p>I’m just glad to see a mindful developer fixed a problem by appending || &#39;&#39; condition. (Check <a href="https://github.com/ptmt/react-native-macos/commit/a7a3922b89d821b9a34d26bdcc7676e747a27160#diff-0c2bccba86d026e1fc586ac3c113d4a9">this commit</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*MRtE1cnuItEztJMw.png" /><figcaption>The problem is fixed</figcaption></figure><h4>DeepScan Rule</h4><p>DeepScan’s <a href="https://deepscan.io/docs/rules/bad-length-check/">BAD_LENGTH_CHECK</a> rule can prevent developers from making this mistake by checking the direct use of length property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75Qu8dPEd5_cBtrsqkql0Q.png" /><figcaption>Do not check length property directly</figcaption></figure><h3>Thanks for reading!</h3><p>You can check the above codes by directly pasting it on this <a href="https://deepscan.io/demo/">Demo</a> page.</p><p>I’ll continue to share what will be helpful in React development. If you have feedback or suggestions, you can find me here:</p><ul><li>Official Website: <a href="https://deepscan.io">https://deepscan.io</a></li><li>Email: <a href="mailto:support@deepscan.io">support@deepscan.io</a></li></ul><h3>Resources</h3><p>Check out additional starting resources for React:</p><ul><li><a href="https://www.toptal.com/react/react-tutorial-pt1">React Tutorial: How to Get Started and How it Compares</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93940e11800a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deepscan/a-few-things-every-new-react-developer-should-know-part-1-93940e11800a">A few things every new React developer should know (part 1)</a> was originally published in <a href="https://medium.com/deepscan">DeepScan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>