CINXE.COM
<!DOCTYPE html><html lang="en" data-theme-enabled="1"><head><script>window.currentUser = null;</script><script>window.shopCurrency = "EUR";</script><script>window.localCurrency = "EUR";</script><script>window.countryCode = "cn";</script><script>window.rateShopTo = {"EUR":1,"USD":1.1331457599385382,"AMD":442.698570763253};</script><title itemprop="name">Ninja code</title><link href="/pack/styles.c582d23a0695e653a6d3.css" rel="stylesheet"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes, minimum-scale=1.0"><meta name="apple-mobile-web-app-capable" content="yes"><script>if (window.devicePixelRatio > 1) document.cookie = 'pixelRatio=' + window.devicePixelRatio + ';path=/;expires=Tue, 19 Jan 2038 03:14:07 GMT';</script><link href="//fonts.googleapis.com/css?family=Open+Sans:bold,italic,bolditalic" rel="stylesheet"><link rel="apple-touch-icon-precomposed" href="/img/favicon/apple-touch-icon-precomposed.png"><link rel="canonical" href="https://javascript.info/ninja-code"><meta name="msapplication-TileColor" content="#222A2C"><meta name="msapplication-TileImage" content="/img/favicon/tileicon.png"><link rel="icon" href="/img/favicon/favicon.png"><meta itemprop="image" content="https://javascript.info/img/site_preview_en_512x512.png"><meta property="og:title" content="Ninja code"><meta property="og:image" content="https://javascript.info/img/site_preview_en_1200x630.png"><meta property="og:image:type" content="image/png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630"><meta property="fb:admins" content="100001562528165"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Ninja code"><meta name="twitter:site" content="@iliakan"><meta name="twitter:creator" content="@iliakan"><meta name="twitter:image" content="https://javascript.info/img/site_preview_en_512x512.png"><meta name="google-adsense-account" content="ca-pub-6204518652652613"><link rel="prev" href="/comments"><link rel="next" href="/testing-mocha"><script data-collect-dnt="true" async src="https://scripts.simpleanalyticscdn.com/latest.js"></script><script>window.GA_ID = "UA-2056213-15";</script><script>window.YANDEX_METRIKA_ID = 32184394;</script><script>{function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","G-2LWB61WGYJ")}</script> <script async src="https://www.googletagmanager.com/gtag/js?id=G-2LWB61WGYJ"></script><script>window.metrika={reachGoal:function(){}},window.yandex_metrika_callbacks=[function(){try{window.metrika=new Ya.Metrika({id:YANDEX_METRIKA_ID,webvisor:!0,clickmap:!0,params:{user:window.currentUser&&window.currentUser.id}}),metrika.trackLinks({delay:150}),window.addEventListener("error",function(r){window.metrika.reachGoal("JSERROR",{src:(r.filename||r.errorUrl)+": "+(r.lineno||r.errorLine),stack:r.stack||r.error&&r.error.stack,message:r.message})})}catch(r){}}];</script><script src="//mc.yandex.ru/metrika/watch.js" async></script><script>window.RECAPTCHA_ID = "6LfmLAEVAAAAAJMykMnf7aY8nkyTRmYi2ynx51R1";</script><script src="/pack/init.c620e89b5f96f3cade19.js"></script><script src="/pack/head.7de24b11bdf2e7982166.js" defer></script><meta property="og:title" content="Ninja code"><meta property="og:type" content="article"><script src="/pack/tutorial.aa68ac65c8ad26a37344.js" defer></script><script src="/pack/footer.818a809d6860f4026867.js" defer></script></head><body class="no-icons"><script>window.fontTest();</script><div class="page-wrapper page-wrapper_sidebar_on"><!--[if IE]><div style="color:red;text-align:center">Sorry, Internet Explorer is not supported, please use a newer browser.</div><![endif]--><div class="sitetoolbar sitetoolbar_tutorial"><script>window.langs = [{"code":"ar","name":"Arabic"},{"code":"az","name":"Azerbaijani"},{"code":"bg","name":"Bulgarian"},{"code":"bn","name":"Bengali"},{"code":"bs","name":"Bosnian"},{"code":"ca","name":"Catalan"},{"code":"cs","name":"Czech"},{"code":"da","name":"Danish"},{"code":"de","name":"German"},{"code":"el","name":"Greek"},{"code":"en","name":"English"},{"code":"es","name":"Spanish"},{"code":"fa","name":"Persian (Farsi)"},{"code":"fi","name":"Finnish"},{"code":"fr","name":"French"},{"code":"he","name":"Hebrew"},{"code":"hi","name":"Hindi"},{"code":"hr","name":"Croatian"},{"code":"hu","name":"Hungarian"},{"code":"hy","name":"Armenian"},{"code":"id","name":"Indonesian"},{"code":"it","name":"Italian"},{"code":"ja","name":"Japanese"},{"code":"ka","name":"Georgian"},{"code":"kk","name":"Kazakh"},{"code":"km","name":"Central Khmer"},{"code":"ko","name":"Korean"},{"code":"ku","name":"Kurdish"},{"code":"ky","name":"Kyrgyz"},{"code":"lt","name":"Lithuanian"},{"code":"me","name":"Montenegrin"},{"code":"ml","name":"Malayalam"},{"code":"ms","name":"Malay"},{"code":"my","name":"Burmese"},{"code":"nl","name":"Dutch"},{"code":"no","name":"Norvegian"},{"code":"pa","name":"Punjabi"},{"code":"pl","name":"Polish"},{"code":"pt","name":"Portuguese"},{"code":"ro","name":"Romanian"},{"code":"ru","name":"Russian"},{"code":"si","name":"Sinhala"},{"code":"sk","name":"Slovak"},{"code":"sl","name":"Slovenian"},{"code":"sq","name":"Albanian"},{"code":"sr","name":"Serbian"},{"code":"ta","name":"Tamil"},{"code":"te","name":"Telugu"},{"code":"test","name":"Test"},{"code":"th","name":"Thai"},{"code":"tk","name":"Turkmen"},{"code":"tr","name":"Turkish"},{"code":"ug","name":"Uyghur"},{"code":"uk","name":"Ukrainian"},{"code":"ur","name":"Urdu"},{"code":"uz","name":"Uzbek"},{"code":"v2","name":"v2"},{"code":"vi","name":"Vietnamese"},{"code":"zh-hant","name":"Chinese Traditional"},{"code":"zh","name":"Chinese"}];</script><script>window.lang = "en";</script><div class="sitetoolbar__content"><div class="sitetoolbar__lang-switcher"><button class="sitetoolbar__dropdown-button" data-dropdown-toggler>EN</button><div class="sitetoolbar__dropdown-wrap"><div class="sitetoolbar__dropdown-body"><div class="sitetoolbar__lang-switcher-body"><div class="supported-langs supported-langs_toolbar"><div class="supported-langs__container"><ul class="supported-langs__list" style="height:200px"><li class="supported-langs__item"><a class="supported-langs__link" href="https://ar.javascript.info/ninja-code"><span class="supported-langs__brief">AR</span><span class="supported-langs__title">عربي</span></a></li><li class="supported-langs__item supported-langs__item_current"><a class="supported-langs__link" href="https://javascript.info/ninja-code"><span class="supported-langs__brief">EN</span><span class="supported-langs__title">English</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://es.javascript.info/ninja-code"><span class="supported-langs__brief">ES</span><span class="supported-langs__title">Español</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://fa.javascript.info/ninja-code"><span class="supported-langs__brief">FA</span><span class="supported-langs__title">فارسی</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://fr.javascript.info/ninja-code"><span class="supported-langs__brief">FR</span><span class="supported-langs__title">Français</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://id.javascript.info/ninja-code"><span class="supported-langs__brief">ID</span><span class="supported-langs__title">Indonesia</span></a></li></ul><ul class="supported-langs__list" style="height:200px"><li class="supported-langs__item"><a class="supported-langs__link" href="https://it.javascript.info/ninja-code"><span class="supported-langs__brief">IT</span><span class="supported-langs__title">Italiano</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://ja.javascript.info/ninja-code"><span class="supported-langs__brief">JA</span><span class="supported-langs__title">日本語</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://ko.javascript.info/ninja-code"><span class="supported-langs__brief">KO</span><span class="supported-langs__title">한국어</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://learn.javascript.ru/ninja-code"><span class="supported-langs__brief">RU</span><span class="supported-langs__title">Русский</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://tr.javascript.info/ninja-code"><span class="supported-langs__brief">TR</span><span class="supported-langs__title">Türkçe</span></a></li><li class="supported-langs__item"><a class="supported-langs__link" href="https://uk.javascript.info/ninja-code"><span class="supported-langs__brief">UK</span><span class="supported-langs__title">Українська</span></a></li></ul><ul class="supported-langs__list" style="height:20px"><li class="supported-langs__item"><a class="supported-langs__link" href="https://zh.javascript.info/ninja-code"><span class="supported-langs__brief">ZH</span><span class="supported-langs__title">简体中文</span></a></li></ul></div><div class="supported-langs__text"><p>We want to make this open-source project available for people all around the world.</p> <p><a href="https://javascript.info/translate">Help to translate</a> the content of this tutorial to your language!</p> </div></div></div></div></div></div><div class="sitetoolbar__logo-wrap"><a class="sitetoolbar__link sitetoolbar__link_logo" href="/"><img class="sitetoolbar__logo sitetoolbar__logo_normal" src="/img/sitetoolbar__logo_en.svg" width="200" alt="" role="presentation"/><img class="sitetoolbar__logo sitetoolbar__logo_normal sitetoolbar__logo_dark" src="/img/sitetoolbar__logo_en-white.svg" width="200" alt="" role="presentation"/><img class="sitetoolbar__logo sitetoolbar__logo_small" src="/img/sitetoolbar__logo_small_en.svg" width="70" alt="" role="presentation"/><img class="sitetoolbar__logo sitetoolbar__logo_small sitetoolbar__logo_dark" src="/img/sitetoolbar__logo_small_en-white.svg" width="70" alt="" role="presentation"/><script>Array.prototype.forEach.call(document.querySelectorAll("img.sitetoolbar__logo"),function(e){let t=document.createElement("object");t.type="image/svg+xml",t.className=e.className,t.style.cssText="left:0;top:0;position:absolute",t.onload=function(){t.onload=null,e.style.visibility="hidden"},t.data=e.src,e.parentNode.insertBefore(t,e)});</script></a></div><div class="sitetoolbar__nav-toggle-wrap"><button class="sitetoolbar__nav-toggle" type="button"></button></div><nav class="sitetoolbar__sections"><ul class="sitetoolbar__sections-list"></ul></nav><div class="sitetoolbar__right-button-wrap"><a class="sitetoolbar-right-button sitetoolbar-right-button_courses" href="/ebook"><span class="sitetoolbar-right-button__extra-text">Buy</span>EPUB/PDF</a></div><div class="sitetoolbar__login-wrap"><button class="sitetoolbar__login sitetoolbar__login_unready" data-action-login></button></div><div class="sitetoolbar__theme-switcher"><div class="theme-changer"><label class="theme-changer__label" for="theme-changer-input" data-tooltip="Change theme"><input class="theme-changer__input" type="checkbox" id="theme-changer-input" data-theme-changer="data-theme-changer"/><span class="theme-changer__icon theme-changer__icon_light-theme"></span><span class="theme-changer__icon theme-changer__icon_dark-theme"></span></label></div></div><div class="sitetoolbar__search-wrap"><div class="sitetoolbar__search-content"><button class="sitetoolbar__search-toggle" type="button"></button><form class="sitetoolbar__search" method="GET" action="/search"><div class="sitetoolbar__search-input"><div class="text-input"><input class="text-input__control" name="query" placeholder="Search on Javascript.info" required="required" type="text"/></div><button class="sitetoolbar__find" type="submit">Search</button></div></form></div></div></div><div class="tablet-menu"><div class="tablet-menu__line"><div class="tablet-menu__content"><form class="tablet-menu-search" action="/search/"><input class="tablet-menu-search__input" type="search" name="query" placeholder="Search in the tutorial" required="required"/><button class="tablet-menu-search__button" type="submit" name="type" value="articles">Search</button></form></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><a class="map" href="/tutorial/map" data-action="tutorial-map"><span class="map__text">Tutorial map</span></a></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><div class="theme-changer theme-changer_tablet-menu theme-changer_has-label"><label class="theme-changer__label" for="theme-changer-input-tablet" data-tooltip="Change theme"><input class="theme-changer__input" type="checkbox" id="theme-changer-input-tablet" data-theme-changer="data-theme-changer"/><span class="theme-changer__icon theme-changer__icon_light-theme"></span><span class="theme-changer__icon theme-changer__icon_dark-theme"></span><span class="theme-changer__label-text theme-changer__label-text_light-theme">Light theme</span><span class="theme-changer__label-text theme-changer__label-text_dark-theme">Dark theme</span></label></div></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><div class="share-icons"><span class="share-icons__title">Share</span><a class="share share_tw" href="https://twitter.com/share?url=https%3A%2F%2Fjavascript.info%2Fninja-code" rel="nofollow"></a><a class="share share_fb" href="https://www.facebook.com/sharer/sharer.php?s=100&p%5Burl%5D=https%3A%2F%2Fjavascript.info%2Fninja-code" rel="nofollow"></a></div></div></div><div class="tablet-menu__line"><div class="tablet-menu__content"><select class="tablet-menu__nav input-select input-select input-select_small" onchange="if(this.value) window.location.href=this.value"><option value="https://ar.javascript.info/ninja-code">عربي</option><option value="https://javascript.info/ninja-code" selected>English</option><option value="https://es.javascript.info/ninja-code">Español</option><option value="https://fa.javascript.info/ninja-code">فارسی</option><option value="https://fr.javascript.info/ninja-code">Français</option><option value="https://id.javascript.info/ninja-code">Indonesia</option><option value="https://it.javascript.info/ninja-code">Italiano</option><option value="https://ja.javascript.info/ninja-code">日本語</option><option value="https://ko.javascript.info/ninja-code">한국어</option><option value="https://learn.javascript.ru/ninja-code">Русский</option><option value="https://tr.javascript.info/ninja-code">Türkçe</option><option value="https://uk.javascript.info/ninja-code">Українська</option><option value="https://zh.javascript.info/ninja-code">简体中文</option></select></div></div></div><progress class="tutorial-progress" data-sticky value="26" max="94" data-tooltip="Lesson 26 of 94"></progress></div><div class="page page_sidebar_on page_inner_padding"><script>if(localStorage.noSidebar){document.querySelector(".page").classList.remove("page_sidebar_on");let e=document.querySelector(".page-wrapper");e&&e.classList.remove("page-wrapper_sidebar_on")}setTimeout(function(){document.querySelector(".page").classList.add("page_sidebar-animation-on")});</script><div class="page__inner"><main class="main main_width-limit"><header class="main__header"><div class="main__header-inner"><div class="main__header-group"><ol class="breadcrumbs"><li class="breadcrumbs__item breadcrumbs__item_home"><a class="breadcrumbs__link" href="/"><span class="breadcrumbs__hidden-text">Tutorial</span></a></li><li class="breadcrumbs__item" id="breadcrumb-1"><a class="breadcrumbs__link" href="/js"><span>The JavaScript language</span></a></li><li class="breadcrumbs__item" id="breadcrumb-2"><a class="breadcrumbs__link" href="/code-quality"><span>Code quality</span></a></li><script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Tutorial","item":"https://javascript.info/"},{"@type":"ListItem","position":2,"name":"The JavaScript language","item":"https://javascript.info/js"},{"@type":"ListItem","position":3,"name":"Code quality","item":"https://javascript.info/code-quality"}]}</script></ol><div class="updated-at" data-tooltip="Last updated on September 5, 2020"><div class="updated-at__content">September 5, 2020</div></div></div><h1 class="main__header-title">Ninja code</h1></div></header><div class="content"><article class="formatted" itemscope itemtype="http://schema.org/TechArticle"><meta itemprop="name" content="Ninja code"><div itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="email" content="iliakan@gmail.com"><meta itemprop="name" content="Ilya Kantor"></div><div itemprop="articleBody"><blockquote class="quote"><div class="quote__i"><div class="quote__text"><p>Learning without thought is labor lost; thought without learning is perilous.</p> </div></div><footer class="quote__footer"> <cite class="quote__author">Confucius (Analects)</cite> </footer></blockquote><p>Programmer ninjas of the past used these tricks to sharpen the mind of code maintainers.</p> <p>Code review gurus look for them in test tasks.</p> <p>Novice developers sometimes use them even better than programmer ninjas.</p> <p>Read them carefully and find out who you are – a ninja, a novice, or maybe a code reviewer?</p> <div class="important important_warn"> <div class="important__header"><span class="important__type">Irony detected</span></div> <div class="important__content"><p>Many try to follow ninja paths. Few succeed.</p> </div></div> <h2><a class="main__anchor" name="brevity-is-the-soul-of-wit" href="#brevity-is-the-soul-of-wit">Brevity is the soul of wit</a></h2><p>Make the code as short as possible. Show how smart you are.</p> <p>Let subtle language features guide you.</p> <p>For instance, take a look at this ternary operator <code>'?'</code>:</p> <div id="i6pjuy65h5" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>// taken from a well-known javascript library i = i ? i < 0 ? Math.max(0, len + i) : i : 0;</code></pre> </div> </div> </div><p>Cool, right? If you write like that, a developer who comes across this line and tries to understand what is the value of <code>i</code> is going to have a merry time. Then come to you, seeking for an answer.</p> <p>Tell them that shorter is always better. Initiate them into the paths of ninja.</p> <h2><a class="main__anchor" name="one-letter-variables" href="#one-letter-variables">One-letter variables</a></h2><blockquote class="quote"><div class="quote__i"><div class="quote__text"><p>The Dao hides in wordlessness. Only the Dao is well begun and well completed.</p> </div></div><footer class="quote__footer"> <cite class="quote__author">Laozi (Tao Te Ching)</cite> </footer></blockquote><p>Another way to code shorter is to use single-letter variable names everywhere. Like <code>a</code>, <code>b</code> or <code>c</code>.</p> <p>A short variable disappears in the code like a real ninja in the forest. No one will be able to find it using “search” of the editor. And even if someone does, they won’t be able to “decipher” what the name <code>a</code> or <code>b</code> means.</p> <p>…But there’s an exception. A real ninja will never use <code>i</code> as the counter in a <code>"for"</code> loop. Anywhere, but not here. Look around, there are many more exotic letters. For instance, <code>x</code> or <code>y</code>.</p> <p>An exotic variable as a loop counter is especially cool if the loop body takes 1-2 pages (make it longer if you can). Then if someone looks deep inside the loop, they won’t be able to quickly figure out that the variable named <code>x</code> is the loop counter.</p> <h2><a class="main__anchor" name="use-abbreviations" href="#use-abbreviations">Use abbreviations</a></h2><p>If the team rules forbid the use of one-letter and vague names – shorten them, make abbreviations.</p> <p>Like this:</p> <ul> <li><code>list</code> → <code>lst</code>.</li> <li><code>userAgent</code> → <code>ua</code>.</li> <li><code>browser</code> → <code>brsr</code>.</li> <li>…etc</li> </ul> <p>Only the one with truly good intuition will be able to understand such names. Try to shorten everything. Only a worthy person should be able to uphold the development of your code.</p> <h2><a class="main__anchor" name="soar-high-be-abstract" href="#soar-high-be-abstract">Soar high. Be abstract.</a></h2><blockquote class="quote"><div class="quote__i"><div class="quote__text"><p>The great square is cornerless<br> The great vessel is last complete,<br> The great note is rarified sound,<br> The great image has no form.</p> </div></div><footer class="quote__footer"> <cite class="quote__author">Laozi (Tao Te Ching)</cite> </footer></blockquote><p>While choosing a name try to use the most abstract word. Like <code>obj</code>, <code>data</code>, <code>value</code>, <code>item</code>, <code>elem</code> and so on.</p> <ul> <li> <p><strong>The ideal name for a variable is <code>data</code>.</strong> Use it everywhere you can. Indeed, every variable holds <em>data</em>, right?</p> <p>…But what to do if <code>data</code> is already taken? Try <code>value</code>, it’s also universal. After all, a variable eventually gets a <em>value</em>.</p> </li> <li> <p><strong>Name a variable by its type: <code>str</code>, <code>num</code>…</strong></p> <p>Give them a try. A young initiate may wonder – are such names really useful for a ninja? Indeed, they are!</p> <p>Sure, the variable name still means something. It says what’s inside the variable: a string, a number or something else. But when an outsider tries to understand the code, they’ll be surprised to see that there’s actually no information at all! And will ultimately fail to alter your well-thought code.</p> <p>The value type is easy to find out by debugging. But what’s the meaning of the variable? Which string/number does it store?</p> <p>There’s just no way to figure out without a good meditation!</p> </li> <li> <p><strong>…But what if there are no more such names?</strong> Just add a number: <code>data1, item2, elem5</code>…</p> </li> </ul> <h2><a class="main__anchor" name="attention-test" href="#attention-test">Attention test</a></h2><p>Only a truly attentive programmer should be able to understand your code. But how to check that?</p> <p><strong>One of the ways – use similar variable names, like <code>date</code> and <code>data</code>.</strong></p> <p>Mix them where you can.</p> <p>A quick read of such code becomes impossible. And when there’s a typo… Ummm… We’re stuck for long, time to drink tea.</p> <h2><a class="main__anchor" name="smart-synonyms" href="#smart-synonyms">Smart synonyms</a></h2><blockquote class="quote"><div class="quote__i"><div class="quote__text"><p>The Tao that can be told is not the eternal Tao. The name that can be named is not the eternal name.</p> </div></div><footer class="quote__footer"> <cite class="quote__author">Laozi (Tao Te Ching)</cite> </footer></blockquote><p>Using <em>similar</em> names for <em>same</em> things makes life more interesting and shows your creativity to the public.</p> <p>For instance, consider function prefixes. If a function shows a message on the screen – start it with <code>display…</code>, like <code>displayMessage</code>. And then if another function shows on the screen something else, like a user name, start it with <code>show…</code> (like <code>showName</code>).</p> <p>Insinuate that there’s a subtle difference between such functions, while there is none.</p> <p>Make a pact with fellow ninjas of the team: if John starts “showing” functions with <code>display...</code> in his code, then Peter could use <code>render..</code>, and Ann – <code>paint...</code>. Note how much more interesting and diverse the code became.</p> <p>…And now the hat trick!</p> <p>For two functions with important differences – use the same prefix!</p> <p>For instance, the function <code>printPage(page)</code> will use a printer. And the function <code>printText(text)</code> will put the text on-screen. Let an unfamiliar reader think well over similarly named function <code>printMessage</code>: “Where does it put the message? To a printer or on the screen?”. To make it really shine, <code>printMessage(message)</code> should output it in the new window!</p> <h2><a class="main__anchor" name="reuse-names" href="#reuse-names">Reuse names</a></h2><blockquote class="quote"><div class="quote__i"><div class="quote__text"><p>Once the whole is divided, the parts<br> need names.<br> There are already enough names.<br> One must know when to stop.</p> </div></div><footer class="quote__footer"> <cite class="quote__author">Laozi (Tao Te Ching)</cite> </footer></blockquote><p>Add a new variable only when absolutely necessary.</p> <p>Instead, reuse existing names. Just write new values into them.</p> <p>In a function try to use only variables passed as parameters.</p> <p>That would make it really hard to identify what’s exactly in the variable <em>now</em>. And also where it comes from. The purpose is to develop the intuition and memory of a person reading the code. A person with weak intuition would have to analyze the code line-by-line and track the changes through every code branch.</p> <p><strong>An advanced variant of the approach is to covertly (!) replace the value with something alike in the middle of a loop or a function.</strong></p> <p>For instance:</p> <div id="2k7hsxn2v7" data-trusted="1" class="code-example"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>function ninjaFunction(elem) { // 20 lines of code working with elem elem = clone(elem); // 20 more lines, now working with the clone of the elem! }</code></pre> </div> </div> </div><p>A fellow programmer who wants to work with <code>elem</code> in the second half of the function will be surprised… Only during the debugging, after examining the code they will find out that they’re working with a clone!</p> <p>Seen in code regularly. Deadly effective even against an experienced ninja.</p> <h2><a class="main__anchor" name="underscores-for-fun" href="#underscores-for-fun">Underscores for fun</a></h2><p>Put underscores <code>_</code> and <code>__</code> before variable names. Like <code>_name</code> or <code>__value</code>. It would be great if only you knew their meaning. Or, better, add them just for fun, without particular meaning at all. Or different meanings in different places.</p> <p>You kill two rabbits with one shot. First, the code becomes longer and less readable, and the second, a fellow developer may spend a long time trying to figure out what the underscores mean.</p> <p>A smart ninja puts underscores at one spot of code and evades them at other places. That makes the code even more fragile and increases the probability of future errors.</p> <h2><a class="main__anchor" name="show-your-love" href="#show-your-love">Show your love</a></h2><p>Let everyone see how magnificent your entities are! Names like <code>superElement</code>, <code>megaFrame</code> and <code>niceItem</code> will definitely enlighten a reader.</p> <p>Indeed, from one hand, something is written: <code>super..</code>, <code>mega..</code>, <code>nice..</code> But from the other hand – that brings no details. A reader may decide to look for a hidden meaning and meditate for an hour or two of their paid working time.</p> <h2><a class="main__anchor" name="overlap-outer-variables" href="#overlap-outer-variables">Overlap outer variables</a></h2><blockquote class="quote"><div class="quote__i"><div class="quote__text"><p>When in the light, can’t see anything in the darkness.<br> When in the darkness, can see everything in the light.</p> </div></div><footer class="quote__footer"> <cite class="quote__author">Guan Yin Zi</cite> </footer></blockquote><p>Use same names for variables inside and outside a function. As simple. No efforts to invent new names.</p> <div id="73iotptbpk" data-trusted="1" class="code-example" data-highlight="[{"start":3,"cols":[{"start":6,"end":10}]},{"start":0,"cols":[{"start":4,"end":8}]}]"> <div class="codebox code-example__codebox"> <div class="codebox__code" data-code="1"> <pre class="line-numbers language-javascript"><code>let user = authenticateUser(); function render() { let user = anotherValue(); ... ...many lines... ... ... // <-- a programmer wants to work with user here and... ... }</code></pre> </div> </div> </div><p>A programmer who jumps inside the <code>render</code> will probably fail to notice that there’s a local <code>user</code> shadowing the outer one.</p> <p>Then they’ll try to work with <code>user</code> assuming that it’s the external variable, the result of <code>authenticateUser()</code>… The trap is sprung! Hello, debugger…</p> <h2><a class="main__anchor" name="side-effects-everywhere" href="#side-effects-everywhere">Side-effects everywhere!</a></h2><p>There are functions that look like they don’t change anything. Like <code>isReady()</code>, <code>checkPermission()</code>, <code>findTags()</code>… They are assumed to carry out calculations, find and return the data, without changing anything outside of them. In other words, without “side-effects”.</p> <p><strong>A really beautiful trick is to add a “useful” action to them, besides the main task.</strong></p> <p>An expression of dazed surprise on the face of your colleague when they see a function named <code>is..</code>, <code>check..</code> or <code>find...</code> changing something – will definitely broaden your boundaries of reason.</p> <p><strong>Another way to surprise is to return a non-standard result.</strong></p> <p>Show your original thinking! Let the call of <code>checkPermission</code> return not <code>true/false</code>, but a complex object with the results of the check.</p> <p>Those developers who try to write <code>if (checkPermission(..))</code>, will wonder why it doesn’t work. Tell them: “Read the docs!”. And give this article.</p> <h2><a class="main__anchor" name="powerful-functions" href="#powerful-functions">Powerful functions!</a></h2><blockquote class="quote"><div class="quote__i"><div class="quote__text"><p>The great Tao flows everywhere,<br> both to the left and to the right.</p> </div></div><footer class="quote__footer"> <cite class="quote__author">Laozi (Tao Te Ching)</cite> </footer></blockquote><p>Don’t limit the function by what’s written in its name. Be broader.</p> <p>For instance, a function <code>validateEmail(email)</code> could (besides checking the email for correctness) show an error message and ask to re-enter the email.</p> <p>Additional actions should not be obvious from the function name. A true ninja coder will make them not obvious from the code as well.</p> <p><strong>Joining several actions into one protects your code from reuse.</strong></p> <p>Imagine, another developer wants only to check the email, and not output any message. Your function <code>validateEmail(email)</code> that does both will not suit them. So they won’t break your meditation by asking anything about it.</p> <h2><a class="main__anchor" name="summary" href="#summary">Summary</a></h2><p>All “pieces of advice” above are from the real code… Sometimes, written by experienced developers. Maybe even more experienced than you are ;)</p> <ul> <li>Follow some of them, and your code will become full of surprises.</li> <li>Follow many of them, and your code will become truly yours, no one would want to change it.</li> <li>Follow all, and your code will become a valuable lesson for young developers looking for enlightenment.</li> </ul> </div></article></div><div class="page__nav-wrap"><a class="page__nav page__nav_prev" href="/comments" data-tooltip="Comments"><span class="page__nav-text"><span class="page__nav-text-shortcut"></span></span><span class="page__nav-text-alternate">Previous lesson</span></a><a class="page__nav page__nav_next" href="/testing-mocha" data-tooltip="Automated testing with Mocha"><span class="page__nav-text"><span class="page__nav-text-shortcut"></span></span><span class="page__nav-text-alternate">Next lesson</span></a></div><div class="article-tablet-foot tablet-only"><div class="article-tablet-foot__layout"><div class="share-icons"><span class="share-icons__title">Share</span><a class="share share_tw" href="https://twitter.com/share?url=https%3A%2F%2Fjavascript.info%2Fninja-code" rel="nofollow"></a><a class="share share_fb" href="https://www.facebook.com/sharer/sharer.php?s=100&p%5Burl%5D=https%3A%2F%2Fjavascript.info%2Fninja-code" rel="nofollow"></a></div><div class="article-tablet-foot__map"><a class="map" href="/tutorial/map" data-action="tutorial-map"><span class="map__text">Tutorial map</span></a></div></div></div><div class="banner-bottom-carbon"><div id="javascriptinfo_iconbar"></div></div><script src="//m.servedby-buysellads.com/monetization.custom.js" id="javascriptinfo_script" async></script><script>document.getElementById("javascriptinfo_script").onload=function(){_bsa.init("custom","CKYDEK3U","placement:javascriptinfo_iconbar",{target:"#javascriptinfo_iconbar",template:'\n <div class="iconBarFlex">\n <a href="##statlink##" class="iconBarLink" rel="sponsored noopener" target="_blank" title="##company## — ##tagline##">\n <div class="iconBarImage" style="background-color: ##backgroundColor##;">\n <img height="30" width="30" src="##image##" alt="##company## logo">\n </div>\n <div class="iconBarText">\n <div class="iconBarTagline">##companyTagline##</div>\n <div class="iconBarDescription">##description##</div>\n </div>\n </a>\n <a href="##ad_via_link##" class="iconBarVia" rel="sponsored noopener" target="_blank">ads via BuySellAds</a>\n </div>\n '})};</script><div class="comments formatted" id="comments"><div class="comments__header"><h2 class="comments__header-title"><a href="#comments" name="comments">Comments</a></h2><div class="comments__read-before"><span class="comments__read-before-link">read this before commenting…</span><div class="comments__read-before-popup"><div class="comments__read-before-popup-i"><ul><li>If you have suggestions what to improve - please <a href="https://github.com/javascript-tutorial/en.javascript.info/issues/new">submit a GitHub issue</a> or a pull request instead of commenting.</li><li>If you can't understand something in the article – please elaborate.</li><li>To insert few words of code, use the <code><code></code> tag, for several lines – wrap them in <code><pre></code> tag, for more than 10 lines – use a sandbox (<a href='https://plnkr.co/edit/?p=preview'>plnkr</a>, <a href='https://jsbin.com'>jsbin</a>, <a href='http://codepen.io'>codepen</a>…)</li></ul></div></div></div></div><div id="disqus_thread"></div><script>var disqus_config = function() { if (!this.page) this.page = {}; Object.assign(this.page, {"url":"https:\/\/javascript.info\/ninja-code","identifier":"\/ninja-code"}); };</script><script>var disqus_shortname = "javascriptinfo";</script><script>var disqus_enabled = true;</script></div></script></main></div><div class="sidebar page__sidebar sidebar sidebar_sticky-footer"><button class="sidebar__toggle" data-sidebar-toggle></button><a class="map" href="/tutorial/map" data-action="tutorial-map" data-tooltip="Tutorial map"></a><div class="sidebar__inner"><div class="sidebar__content"><div class="sidebar__section"><h4 class="sidebar__section-title">Chapter</h4><nav class="sidebar__navigation"><ul class="sidebar__navigation-links"><li class="sidebar__navigation-link"><a class="sidebar__link" href="/code-quality">Code quality</a></li></ul></nav></div><div class="sidebar__section"><h4 class="sidebar__section-title">Lesson navigation</h4><nav class="sidebar__navigation"><ul class="sidebar__navigation-links"><li class="sidebar__navigation-link"><a class="sidebar__link" href="#brevity-is-the-soul-of-wit">Brevity is the soul of wit</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#one-letter-variables">One-letter variables</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#use-abbreviations">Use abbreviations</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#soar-high-be-abstract">Soar high. Be abstract.</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#attention-test">Attention test</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#smart-synonyms">Smart synonyms</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#reuse-names">Reuse names</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#underscores-for-fun">Underscores for fun</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#show-your-love">Show your love</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#overlap-outer-variables">Overlap outer variables</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#side-effects-everywhere">Side-effects everywhere!</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#powerful-functions">Powerful functions!</a></li><li class="sidebar__navigation-link"><a class="sidebar__link" href="#summary">Summary</a></li></ul></nav></div><div class="sidebar__section"><nav class="sidebar__navigation"><ul class="sidebar__navigation-links"><li class="sidebar__navigation-link"><a class="sidebar__link" href="#comments">Comments</a></li></ul></nav></div><div class="sidebar__section"><div class="sidebar__section-title">Share</div><a class="share share_tw sidebar__share" href="https://twitter.com/share?url=https%3A%2F%2Fjavascript.info%2Fninja-code" rel="nofollow"></a><a class="share share_fb sidebar__share" href="https://www.facebook.com/sharer/sharer.php?s=100&p[url]=https%3A%2F%2Fjavascript.info%2Fninja-code" rel="nofollow"></a></div><div class="sidebar__section"><a class="sidebar__link" href="https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/03-code-quality/04-ninja-code" rel="nofollow">Edit on GitHub</a></div><div class="sidebar__section" id="sponsorBar"><div class="sidebar__section-title" id="sponsorBarTitle"></div><div id="sponsorBarContent"></div></div><script>window.initSponsorBar()</script></div></div></div></div></div><div class="page-footer"><ul class="page-footer__list"><li class="page-footer__item page-footer__item_copy">© 2007—2025 Ilya Kantor</li><li class="page-footer__item page-footer__item_about"><a class="page-footer__link" href="/about">about the project</a></li><li class="page-footer__item page-footer__item_contact"><a class="page-footer__link" href="/about#contact-us">contact us</a></li><li class="page-footer__item page-footer__item_terms"><a class="page-footer__link" href="/terms">terms of usage</a></li><li class="page-footer__item page-footer__item_privacy"><a class="page-footer__link" href="/privacy">privacy policy</a></li></ul></div></body></html>