<?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[Stories by John C. Lokman on Medium]]></title>
        <description><![CDATA[Stories by John C. Lokman on Medium]]></description>
        <link>https://medium.com/@clokman?source=rss-3394f32ed92f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*34HJr7XCiaXQApkcibLqpQ.png</url>
            <title>Stories by John C. Lokman on Medium</title>
            <link>https://medium.com/@clokman?source=rss-3394f32ed92f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:29:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@clokman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simple Pandoc Layout Guide: Columns, Page Margins, and More in Markdown with One-Liners]]></title>
            <link>https://levelup.gitconnected.com/use-columns-adjust-margins-and-do-more-in-markdown-with-these-simple-pandoc-commands-adb4c19f9f35?source=rss-3394f32ed92f------2</link>
            <guid isPermaLink="false">https://medium.com/p/adb4c19f9f35</guid>
            <category><![CDATA[pandoc]]></category>
            <category><![CDATA[publishing]]></category>
            <category><![CDATA[markdown]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[latex]]></category>
            <dc:creator><![CDATA[John C. Lokman]]></dc:creator>
            <pubDate>Wed, 12 Jan 2022 15:33:54 GMT</pubDate>
            <atom:updated>2023-09-28T17:18:59.187Z</atom:updated>
            <content:encoded><![CDATA[<h4>DOCUMENT PROGRAMMING</h4><p><em>You can use these minimalistic techniques to configure the layout of your PDF, HTML, and Docx output without fiddling with LaTeX templates.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMeJ2aOT_zNJqPx14dEISg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@brunus?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Bruno Martins</a> on <a href="https://unsplash.com/collections/1uHpKFLQuvQ/layout/58e21bfb5d22579f2e86fde2abba45c0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>The Gist / TL;DR</h3><p>If you write this in <strong>Markdown</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XD6f6tOePZ5NTSgkPG81uA.png" /></figure><p>You can parse it with the help of the <a href="https://pandoc.org/installing.html"><strong>Pandoc</strong></a> LUA filter, ‘<a href="https://github.com/jdutant/columns">Columns</a>’, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pys0sPDxJlpMSSSTsPFbAw.png" /></figure><p>And get this PDF as a result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_hzU0NS3DHx7SBzxYVQKg@2x.png" /></figure><p>If you want to adjust your page margins as well (and thus, column widths and heights), you can do this by adding a statement like this to the beginning of your Markdown file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyYVtzdaf7jyQwyqdjujKQ.png" /><figcaption>YAML environment at the start of the Markdown file.</figcaption></figure><p>Here is a preview of some of the things you can do with these layout parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*rROwHp5_JfKiXVH6xuYDJw@2x.png" /></figure><p>These techniques work for PDF and HTML files. For Docx files, you can use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bvzy4SsZonb1odmrAZbFGQ.png" /><figcaption>Docx layout is set differently than PDF and HTML.</figcaption></figure><p>Read on for details!</p><h3>Setup</h3><p>You need an LUA filter (i.e., a script written in LUA language) ‘<a href="https://github.com/jdutant/columns">Columns</a>’ by Julien Dutant to enable multi-column support in Pandoc. Here’s how to get and set it up:</p><ol><li>If you don’t already have it, <a href="https://pandoc.org/installing.html">install Pandoc</a>.</li><li>Download or clone the ‘<a href="https://github.com/jdutant/columns">Columns</a>’ repository. If you downloaded it as a zip file, unpack it.</li><li>You only need one file from the repository: Copy the file <strong>columns.lua</strong> to a directory in your project. For this guide, I use the following directory structure and put the <strong>columns.lua</strong> in my <strong>filters</strong> directory:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCZMgvAePAD5GTZo19BbNA.png" /><figcaption>Project structure after adding columns.lua.</figcaption></figure><h3>Usage in Pandoc</h3><p>Once you have the <strong>columns.lua</strong> filter in your project folder, you can include it in the Pandoc command that parses your Markdown file into a <strong>PDF</strong> or <strong>HTML</strong>. (For brevity, I go with PDF in this guide). Here is how to include the LUA filter in the parsing operation:</p><ol><li>Open a terminal and navigate to your project directory (e.g., <strong>cd /Users/myName/MyProject</strong> ).</li><li>Call pandoc with <strong>--lua-filter=./filters/columns.lua</strong> parameter:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HsXA13WeU5WqUaTldxVj4w.png" /></figure><p><strong>Note</strong>: Do you need to use columns or make layout changes in a <strong>Docx</strong> file? Then you need a different approach, and this is covered in a later section.</p><h3>Usage in Markdown</h3><p>Here are some examples.</p><h4>Layout Basics</h4><p><strong><em>Display some text as columns</em></strong></p><p>You can display all or only some sections of your text by wrapping the relevant parts between <strong>:::columns</strong> and <strong>:::</strong> statements.</p><p><strong>:::columns</strong> tells the parser that what follows is a statement that involves the ‘Columns’ package (the number of colon symbols here has nothing to do with how many columns your text will have).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_wF91Ytq4j4mOA0WQXI-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_hzU0NS3DHx7SBzxYVQKg@2x.png" /></figure><p><strong><em>Show a black line between columns</em></strong></p><p>If you would like to specify column properties further, you can do so by writing another one-liner that works pretty much like the <strong>:::columns</strong>, but a bit less pretty because of the curly brackets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AiPkyFwdPEm2GOtC_1CWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehVgVc6Cnf61n6BWYawwtQ@2x.png" /></figure><p><strong><em>Display as three columns with a thick, orange line in-between</em></strong></p><p>The same trick, but this time use <strong>.threecolumns </strong>instead of <strong>.columns</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eueKyZafeSPj4llXAdGSXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yl95FpceK81KKuhnHESReA@2x.png" /></figure><h4>Display Your Entire Document in Column Layout</h4><p>The methods above display a short text in two columns. There is no limit to how much text should be displayed in columns, though. So you can put your entire document (or large parts of it) between <strong>:::column</strong> and <strong>:::</strong> keywords:</p><pre><strong># Abstract </strong><br>This part is displayed as a single block of text.<br>​<br>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Cras pulvinar mattis nunc sed blandit. Nunc vel risus commodo viverra maecenas. Eget magna fermentum iaculis eu. Vehicula ipsum a arcu cursus vitae congue mauris rhoncus. Nunc eget lorem dolor sed viverra ipsum.<br>​<br>​<br><strong># Introduction </strong><br>::: columns<br>​<br>This part is displayed as two columns.<br>​<br>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Cras pulvinar mattis nunc sed blandit. Nunc vel risus commodo viverra maecenas. Eget magna fermentum iaculis eu. Vehicula ipsum a arcu cursus vitae congue mauris rhoncus. Nunc eget lorem dolor sed viverra ipsum.<br>​<br>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Cras pulvinar mattis nunc sed blandit. Nunc vel risus commodo viverra maecenas. Eget magna fermentum iaculis eu. Vehicula ipsum a arcu cursus vitae congue mauris rhoncus. Nunc eget lorem dolor sed viverra ipsum.<br>​<br>​<br>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Cras pulvinar mattis nunc sed blandit. Nunc vel risus commodo viverra maecenas. Eget magna fermentum iaculis eu. Vehicula ipsum a arcu cursus vitae congue mauris rhoncus. Nunc eget lorem dolor sed viverra ipsum.<br>​<br>:::</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*hXtExkMRvQmKndn7o7T0yQ@2x.png" /><figcaption>Mixed layout: Abstract section is displayed as a single block while the Introduction section is in two columns.</figcaption></figure><h4>Add Full-Width Content</h4><p>Sometimes, you will want a specific element in a column environment (e.g., a picture or heading) to take the entire width of your document and then everything to go back to the column layout.</p><p>To start, let’s add an <strong>images</strong> subdirectory to the project and put an image file in it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m0LFYtcJjuJy2Tu7lpfDuA.png" /><figcaption>Project structure after adding an images folder and an image.</figcaption></figure><p>To make a part of your text (or an element such as an image) span the full width of your document, you can wrap that part between <strong>::::: column-span</strong> and <strong>:::::</strong> tags. The many colons (:) here denote the level of indentation, as this expression takes place within another environment that has already been started, namely the <strong>::: column</strong> environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOZKBMuKQQrqbi1XuuifOQ.png" /><figcaption>An image that spans the full width of the document is placed in the column environment. The <strong>{ width=100% }</strong> part in the end is an extra measure for ensuring your image takes the entire width of the page regardless of the actual size of the image.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*eaEJGbrEy5CL2VTaR9eXDQ@2x.png" /><figcaption>Displaying a full-width element. (Photo by <a href="https://unsplash.com/@ariel_pilotto?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ariel Pilotto</a> on <a href="https://unsplash.com/s/photos/columns?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.)</figcaption></figure><p><strong>Note</strong>: An alternative to using the <strong>column-span</strong> keyword would be to close the <strong>::: columns</strong> environment, put the full-width image, and then open another <strong>`::: columns</strong> environment, making the image between the column environments full-width. This is a less minimalistic solution, though.</p><h4>Specify Column Widths and Page Margins</h4><p>You do not need the Columns LUA filter to set document margins, but the margins affect the width of your columns. For instance, if you want to make your columns wider, you can reduce the space reserved for left and right document margins to create more space for the text content, and thus, for your columns.</p><p>You can specify the page margins by adding a statement such as this one to the beginning of your Markdown file (regardless of whether you are using the <strong>columns.lua</strong> or not):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1rZBb80zYiXnL1ZKHqDCA.png" /><figcaption>YAML specification. The three hyphens here start and end a YAML environment — a section you can add to the beginning of a Markdown document. These parameters are passed to Pandoc during parsing to customize its behavior.</figcaption></figure><h3>Layout for Docx Files</h3><p>At the time of writing, the methods above work for PDF and HTML output. If you wish to change the layout for Pandoc’s Docx output, you can do this with a reference document instead. Here’s how:</p><p>1. Navigate to your project directory in shell and then (optionally) into your Docx templates subdirectory if you want to have one. In this example, I indeed use a separate subdirectory for templates, so if I have multiple Docx templates, they are tidily in one place. After creating the <strong>templates</strong> subdirectory in my project, this is how my project directory looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K88W_C545YnclqNtzv_u3A.png" /><figcaption>(Prospective) project structure after adding a templates folder.</figcaption></figure><p>2. Retrieve the default reference document Pandoc uses (i.e.‘reference.docx’) and save it as a file (i.e., ‘myReference.docx’ in this example) in your templates directory. You can also use any Word file with style information in it, but using Pandoc’s reference document ensures that it is compatible with Pandoc when read back in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QEnP5WHqjpjxoogDPTRvEQ.png" /><figcaption>Copy the default reference document of Pandoc to the project directory.</figcaption></figure><p>3. Open ‘myReference.docx’ in your word processor (only tested for Word), edit the text styles, margins, and layout (e.g., display text as two columns) in this file and save it.</p><p>4. Navigate back to the root of your project directory, and then tell Pandoc to use your new reference file when parsing your Markdown file. This way, it will extract style and layout information from myReference.docx and use these when creating a new Docx file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_FvZOCzWuVE8ghrTEw1qw.png" /></figure><h3>In Conclusion</h3><p>You may want to have a multi-column layout and specify basic parameters such as page margins while parsing your Markdown text into various formats. If you don’t want to fiddle with feeding LaTeX templates to Pandoc, you can use an LUA filter (for columns) and a YAML statement (for margins) instead. This approach works for parsing your Markdown file into a PDF or HTML (in newer browsers). For parsing into Docx, you would need a reference document instead.</p><p>I hope you found this helpful and enjoyed reading.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adb4c19f9f35" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/use-columns-adjust-margins-and-do-more-in-markdown-with-these-simple-pandoc-commands-adb4c19f9f35">Simple Pandoc Layout Guide: Columns, Page Margins, and More in Markdown with One-Liners</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use this One-Liner to Make any Node.js Module Run in a Web Browser]]></title>
            <link>https://levelup.gitconnected.com/use-this-one-liner-to-make-any-node-js-module-run-in-a-web-browser-e25c74652530?source=rss-3394f32ed92f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e25c74652530</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[browserify]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[John C. Lokman]]></dc:creator>
            <pubDate>Mon, 16 Aug 2021 03:52:22 GMT</pubDate>
            <atom:updated>2022-03-14T22:51:13.416Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software Engineering</h4><h4>With this zero-config method, you can convert any Node.js module to a .js file that you can include in your HTML file</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZJLqRY0RSZc2-lWW7_chw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rubavi78?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rubén Bagüés</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>TL;DR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_yDacgJqxEn20MkTLFkHw.png" /></figure><p>Using Browserify — and a zero-config procedure — you can convert any node.js module to a .js file which you can use in a browser. You can also routinely include Node.js’s <strong>require</strong> statements in your .js files and let them work in both Node.js and web browsers. Here&#39;s how.</p><h3>Install Browserify</h3><p>First, install Browserify:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtm0XzINpSEHwrTcSKD8HA.png" /></figure><h3>Convert a Node Module to a JS File You can Include in Your HTML File</h3><p>Browserify <em>allows</em> you to use Node.js’s <strong>require</strong> keyword in web browsers (next section). But, sometimes, you may want to keep your JS files <em>vanilla</em> and not mix any <strong>require</strong> statements in them. Instead of complicating your workflow, you might want to merely convert a node module (e.g., from NPM) to a .js file you can use in your browser and not have anything to do with Browserify after you&#39;re done with the conversion.</p><p>You can convert a node module to its web-browser-compatible version with this single <em>shell</em> command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_yDacgJqxEn20MkTLFkHw.png" /></figure><p>(Of course, you need to have <strong>myNodeModule</strong> already installed).</p><p>Then you can include it in your HTML file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHD3rKO4RlJ2JhZVy8cuew.png" /></figure><p>This works on multi-file modules, by the way. So, if you noticed that the node module you want to convert has multiple JS files in it, you don’t need to worry about it — Browserify includes them all.</p><p>There may come a time where you no longer can stay with <em>vanilla</em> JS and need to include <strong>require</strong> statements in your own .js files. Those files need to work in both node.js and web browsers. Browserify can help there and do it more efficiently than this one-liner method. Read on if you would like to know <em>how</em>.</p><h3>Make Your Scripts Run in a Browser</h3><p>Assume you have a js file in which there is a Node module required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FfCNKqmijcKfuUYS3NCYLw.png" /></figure><p>If you try to run this file in your web browser, you’ll get an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gM-3xRUof1tzxw9_UG9AFQ.png" /></figure><p>That’s exactly where Browserify comes in. It makes Node’s <strong>require</strong> function work with browsers. It achieves this by converting <strong>require</strong> to something that browsers can work with.</p><p>(More specifically, Browserify copy-pastes the contents of the modules you <em>require</em>d in <strong>myFile.js</strong> into<strong>myBundle.js</strong>, along with the original content of <strong>myFile.js</strong>. That&#39;s why it&#39;s apt to call the resulting file a <em>bundle</em>.)</p><p>You can convert your .js file to one that is compatible with a web browser by using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAzo2hC5Nv4QNLH1I3CKLg.png" /></figure><p>Then you can run the resulting <strong>myBundle.js</strong> in your browser by adding this into your HTML file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtwpbYUyuiWphMG2z0SImQ.png" /></figure><p>(Above, <strong>./</strong> stands for &#39;current folder&#39;. You can also use an absolute path.)</p><h3>Automate the Process</h3><p>Repeat it enough times, and even the smallest effort can become cumbersome. Although what we learned is useful, it’s not fun if you have to convert your files with Browserify each time you make a change to them. This is why, as a next step, you might want to use <a href="https://www.npmjs.com/package/watchify">watchify</a> to auto-run Browserify when your code changes. If you’d like to take it one step further, you can also refresh your browser automatically on changes using <a href="https://www.npmjs.com/package/beefy">beefy</a>, and achieve live-reload.</p><h3>In Conclusion</h3><p>Using Browserify, you can now convert a node module to run in a web browser and not look back. You can also include .js files in your workflow that can run in both Node and web browsers. If you do the latter, automation will likely increase your quality of life considerably, so you may want to invest some of your time to set it up by checking the links above.</p><p>I hope you enjoyed reading and found this useful.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e25c74652530" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/use-this-one-liner-to-make-any-node-js-module-run-in-a-web-browser-e25c74652530">Use this One-Liner to Make any Node.js Module Run in a Web Browser</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Callbacks Explained via Examples]]></title>
            <link>https://javascript.plainenglish.io/callbacks-in-js-explained-via-examples-9839eedad662?source=rss-3394f32ed92f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9839eedad662</guid>
            <category><![CDATA[callback-function]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[John C. Lokman]]></dc:creator>
            <pubDate>Sat, 14 Aug 2021 04:18:21 GMT</pubDate>
            <atom:updated>2023-09-28T17:21:32.364Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software Engineering</h4><h4>Write elegant functions, inject one function into another, and achieve recursive behavior by using callbacks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROhjU6v6KLM5df4SdByhMw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@eduardoequis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Eduardo Sánchez</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>👁‍🗨 Use a Callback to Expose Interim Results While Calling a Function</h3><p>Have you ever wondered where do the <em>magical</em> parameters such as element or (value, key) in a .forEach loop come from?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_MEFYTZTx48wTfwAhsfhQ.png" /></figure><p>By the time you reach the end of this section, you will understand it.</p><p>Assume you have a function called halfAlgebra. It takes in a number as its first parameter, divides it in half, then allows you to use the result in another function you may provide as the second parameter of halfAlgrebra.</p><p>Here’s how you can write such a function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OT1vQv2dY14vcp3WlNyvOg.png" /></figure><p>Above, in the end, anotherFunction( half ) is executed. This makes the variable half accessible for any callback functions that you may enter as the second parameter of halfAlgebra function. Here&#39;s how:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhHhMdpFMRfTsWrjjufuZw.png" /></figure><p>Here, providing addOne as a callback parameter causes that function to be executed implicitly AND use half as its parameter. So, it is effectively executed as addOne( half ).</p><p>You can also enter functions directly as a callback parameter (i.e., as an anonymous function). Anonymous callback functions also have access to the half variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M_r-8hbVNRlUkQL7rAS4YA.png" /></figure><p>By the way, you do not have to call the variable half. You can refer to it any way you like (what matters is parameter positions, not names):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M0LJFIlSRKXDb1nyDLZj3Q.png" /></figure><p>So, when you see callback variables in JavaScript, such as in the element or (value, key) in a .forEach method, now you know how they are made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfUmLQDzxXcC0fu5a2zzUg.png" /></figure><h3>🔗 Use a Callback to Make a Function Run as Part of Another</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qMr8z2WAKtO1E5wW3lUMQQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pcjw412?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Craig Washington</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Imagine you have a function that can stitch two words together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XvrIioSAY9b7_vvFj-rpQ.png" /></figure><p>And let’s say you want to modify the output of this function further after the words are stitched together, but you’re not sure how. You want to make sure that such modification is possible but leave the specifics open-ended.</p><p>You can do this by adding a callback parameter, which refers to a callback function that runs just before stitch finishes running:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FS7mzjPKg4Yxz6tUe1sGHQ.png" /></figure><p>Here, the callback parameter has a default anonymous function. A default callback function ensures that the stitch runs normally if no callback parameter is entered when the function is called.</p><p>Imagine that you have another function that makes everything sound excited:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMafrr5lsdAD3QsmEVE-1A.png" /></figure><p>You can now add the excited function as a callback parameter of the <strong>stitch</strong> function, modifying its output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9TFas0L4syH1WIIN-6wtw.png" /></figure><p>You can think of excited this as a <em>plugin</em> to stitch.</p><p>You can also add an anonymous function as the callback parameter to make a custom modification to the output on the go:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9T4qmOUes-Qg2I0c5isHJg.png" /></figure><h3>📚 Use Callbacks in a Method</h3><p>Of course, you can also use callbacks in methods. Here is how via an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PkCPqaFOyFXHAIoI5mlNyQ.png" /></figure><h3>In Conclusion</h3><p>You can use callbacks to get interim results from a function and use those results in the next parts of your function call.</p><p>You can also use a callback to inject a function into another.</p><p>I hope you enjoyed reading!</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9839eedad662" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/callbacks-in-js-explained-via-examples-9839eedad662">JavaScript Callbacks Explained via Examples</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jest Spies and Mocks in Explained via Examples]]></title>
            <link>https://javascript.plainenglish.io/jest-spies-and-mocks-in-explained-via-examples-71229077277f?source=rss-3394f32ed92f------2</link>
            <guid isPermaLink="false">https://medium.com/p/71229077277f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[John C. Lokman]]></dc:creator>
            <pubDate>Fri, 13 Aug 2021 23:34:25 GMT</pubDate>
            <atom:updated>2024-07-24T05:35:50.532Z</atom:updated>
            <content:encoded><![CDATA[<h4>Testing</h4><h3>Jest Spies and Mocks Explained via Examples</h3><h4>Make your JavaScript tests deeper, leaner, and faster with these two Jest methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhKLjQZrj_cQPrloA35jRA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pheiskan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Petri Heiskanen</a> on <a href="https://unsplash.com/s/photos/eye?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ms_dxMuy3rg_taorztILzA.png" /><figcaption>TL;DR</figcaption></figure><h3>👁 Spying</h3><p>jest.spyOn( PROTOTYPE_OR_CLASS, METHOD_NAME )</p><p>Spying is to observe calls made to a method without changing the method itself.</p><h4>Spy on a Method</h4><p>Let’s say you have a class in a module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mobcVlxqYl_RdPhC3_3P2Q.png" /></figure><p>This is how you can spy on <strong>instance</strong> and <strong>static</strong> methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pnonw9n2K5LobPwrLX7jCA.png" /></figure><p>If the <strong>spy is assigned to a variable</strong>, you can also access it via a variable (instead of via the method being spied on):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHXHJ1o8_TwuVTul06AH9w.png" /></figure><p>Here are some of the <strong>Jest matchers</strong> you can use with spyOn:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2LK5jJ_-v6odE1GOvK9TA.png" /></figure><blockquote><em>💡 </em>Speed up your blog creation with <a href="https://differ.blog/differ-ai"><strong><em>DifferAI</em></strong></a>.</blockquote><blockquote>Available for <strong><em>free</em> </strong>exclusively on the <strong><em>free and open blogging platform, </em></strong><a href="https://differ.blog/"><strong><em>Differ</em></strong></a><strong>.</strong></blockquote><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><h4>Spy on a Built-in Method</h4><p>Built-in methods are not safe from spies either. You can spy on them like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OoQAPwK8AhbEbQSvh1jxOw.png" /></figure><h4>Change the Implementation of a Method Being Spied on</h4><p>This is called ‘mocking’, as we can fake the behavior of a method this way, thereby ‘mocking’ the method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tF5bRoav-5ZFM2HmpE7loA.png" /></figure><p>You can replace the contents of a method also by using jest.fn()</p><h3>👻 Mocking</h3><p>METHOD = fn( () =&gt; {...} )</p><p>You can temporarily replace the contents of a method with Jest mocks.</p><h4>Mock a Method</h4><p>Let’s say you have a class in a module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CddX8idF-oMLrJ8u0Ut2Gg.png" /></figure><p>You can replace the contents of its methods this way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CPFIWd5LQUQqIxWZhl3_Q.png" /></figure><h4>Mock a Built-In Method</h4><p>Replace .addEventListener method with a mock one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbjKfE75ltyT8pdg6AFyUw.png" /></figure><h3>In Conclusion</h3><p>We have seen two approaches to keeping tabs on the methods in our code. You can use <strong>jest.spyOn</strong> for a non-intrusive way to record calls. Alternatively, you can use <strong>jest.fn</strong> to replace a method entirely with a fake version of it, which is called ‘mocking’.</p><p>Happy coding!</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71229077277f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/jest-spies-and-mocks-in-explained-via-examples-71229077277f">Jest Spies and Mocks in Explained via Examples</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>