<?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 ridwanf on Medium]]></title>
        <description><![CDATA[Stories by ridwanf on Medium]]></description>
        <link>https://medium.com/@ridwanfansuri?source=rss-92efd285f2e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4BGl66iT7K2Gkq3t.</url>
            <title>Stories by ridwanf on Medium</title>
            <link>https://medium.com/@ridwanfansuri?source=rss-92efd285f2e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:54:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ridwanfansuri/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[To Log Or Not To Log]]></title>
            <link>https://medium.com/@ridwanfansuri/to-log-or-not-to-log-ae7892c2f5a4?source=rss-92efd285f2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae7892c2f5a4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[ridwanf]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 14:50:07 GMT</pubDate>
            <atom:updated>2026-04-07T14:50:07.241Z</atom:updated>
            <content:encoded><![CDATA[<p>As a software engineer, have you ever wondered how your program is actually running? When you encounter an error, how do you find the culprit? Some engineers debug the program, which works, but it takes too much time to run the program, set breakpoints, and step through the code. The fastest solution is logging. You add logs to your code to print the values you need without interrupting execution, and you can see them in the console. But how do you write logs that can be displayed in production? How much do you log? And what kind of logging is it? Let’s explore further.</p><p>Logging is mainly used to see what happened during a request to your web application because once your application is deployed, you can’t step through with the debugger. And there are pros &amp; cons of using log as you can see in the table below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*UO1OxB4eVHOlR7s5-g_UmA.png" /></figure><h3>Loging Levels</h3><p>In Python, you can log messages at different levels.</p><ul><li>CRITICAL</li></ul><p>The CRITICAL level is the errors that cause application failure, such as a crucial database being unavailable</p><ul><li>ERROR</li></ul><p>The ERROR levels. handling errors that affect the application’s operation, such as an HTTP 500 error, but allow the application to continue</p><ul><li>WARNING</li></ul><p>Non-critical issue that requires attention, such as deprecated code usage or low disk space</p><ul><li>INFO</li></ul><p>Information messages. This could be a user authentication message or version info</p><ul><li>DEBUG</li></ul><p>Debugging messages provide extra information for developers during development or testing.</p><h3>Tips &amp; Trick</h3><ul><li>Never display private information in the production log. Always check the log when deploying the app.</li><li>Format the logger so it can be read easily</li><li>If you use a log file, always check the log size.</li></ul><p>In the end, good logging is about balance: capture enough context to understand what happened, but not so much that your system becomes noisy, slow, or expensive to operate. Start with clear levels and consistent formatting, log around meaningful events (not every line), and treat logs as part of your production interface — secure, readable, and intentionally designed. With that mindset, logs become a reliable guide when things go wrong and a helpful narrative of how your application behaves in the real world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae7892c2f5a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Code Review with Bitbucket & N8N]]></title>
            <link>https://medium.com/@ridwanfansuri/ai-code-review-with-bitbucket-n8n-7454da42d643?source=rss-92efd285f2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7454da42d643</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[bitbucket]]></category>
            <category><![CDATA[n8n]]></category>
            <category><![CDATA[n8n-workflow-automation]]></category>
            <dc:creator><![CDATA[ridwanf]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 14:55:04 GMT</pubDate>
            <atom:updated>2026-02-12T14:55:04.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*lokhfWhcevFvhEvCYyt7fg.png" /></figure><p>Code review is a critical quality assurance process where developers evaluate each other’s code for bugs, logic errors, and adherence to standards before merging it into a repository. It improves code maintainability, security, and quality while enabling knowledge sharing among team members. However, code reviews are sometimes overlooked — developers may approve pull requests without thoroughly examining the code. For solo developers, conducting proper reviews is challenging without peers to collaborate with. But don’t worry. I’ll show you how to create an AI agent for code review using Bitbucket and N8N.</p><h3>Step 1. Create a workflow in N8N</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MeVEYvaAXQJjZbRG3cv5vQ.png" /></figure><p>Create a new workflow named bitbucket-pr and add a webhook node as the first node. Double-click the node and add the configuration below—this will be your webhook URL. There are two types of URLs: Test URL and Production URL. For the Test URL, click &quot;Listen for test event&quot; to activate the webhook node. The Production URL becomes active after you publish the workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7KFHyjpu-ZeKY88M1NBAA.png" /></figure><h3>Step 2. Create a webhook in Bitbucket</h3><p>Next, create a webhook in your project repository in Bitbucket. You’ll need admin access to do this and click the Add Webhook button at the top of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_gwsxpAi81uA7psKLG_QQ.png" /></figure><p>On the Add new webhook page, enter the webhook title, the URL from the N8N webhook node, and a password for authentication. Set the status to Active.</p><p><strong>Important</strong>: In the triggers section, check push, fork, and pull request: Created and Updated.</p><p>After filling in the fields, click the Save button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_Xr0siBMwsYNGVEPA4ayQ.png" /></figure><p>To test the webhook, click “Listen for test event” on the N8N webhook node and push new code to Bitbucket.</p><p>You can see the webhook response in the right panel of the N8N webhook node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0bGMfGygjAv6RNI9ypy1Q.png" /></figure><h3>Step 3. Securing your workflow</h3><p>Your workflow is now exposed to the internet, meaning anyone can access and trigger it via the URL. This becomes a problem if someone discovers the URL and exploits your workflow — it could be overwhelmed or taken down. To secure your workflow from unauthorized calls, add a code node in JavaScript or Python to extract data from the webhook and retrieve the token for authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*rB_Qlvg_bTNyxsz4m-Mimw.png" /></figure><p>Bitbucket sends the token in the response header. As you can see in the Step 2 screenshot, the webhook response has a header field containing x-hub-signature.</p><p>X-Hub-Signature (or sometimes X-Hub-Signature-256) is a <strong>security header</strong> used to verify that:</p><p>✅ The webhook request really comes from Bitbucket</p><p>✅ The payload was not modified</p><p>✅ The sender knows your shared secret</p><p>The x-hub-signature value contains the algorithm and signature in the format algorithm=signature. We&#39;ll use this key for authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*QJhcggMmUujUKHF9WeHj6w.png" /></figure><p>We’ll also need the response body value from the webhook for the code review process.</p><p>The image below shows the process of extracting webhook data and formatting it as JSON.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYxc0nbtnyuS2YqYeWpbdw.png" /></figure><p>This is the code inside the node</p><pre>// Access webhook data correctly<br>const webhookData = $input.first().json;<br>const headers = webhookData.headers;<br>const body = webhookData.body;console.log(&#39;📝 Event:&#39;, headers[&#39;x-event-key&#39;]);<br>console.log(&#39;🔐 Signature:&#39;, headers[&#39;x-hub-signature&#39;]);<br>// Get signature from headers<br>const signature = headers[&#39;x-hub-signature&#39;];<br>if (!signature) {<br>  console.error(&#39;❌ No signature header&#39;);<br>  <br>  return {<br>    json: {<br>      error: &#39;No signature provided&#39;,<br>      authenticated: false<br>    }<br>  };<br>}<br>// Parse signature (sha256=hash)<br>const [algorithm, receivedHash] = signature.split(&#39;=&#39;);<br>if (algorithm !== &#39;sha256&#39;) {<br>  console.error(&#39;❌ Unsupported algorithm:&#39;, algorithm);<br>  <br>  return {<br>    json: {<br>      error: &#39;Unsupported algorithm&#39;,<br>      authenticated: false<br>    }<br>  };<br>}<br>// Prepare the body for hashing<br>// IMPORTANT: Bitbucket signs the raw body as received<br>const bodyString = JSON.stringify(body);<br>return {<br>  json: {<br>    // Data to hash<br>    dataToHash: bodyString,<br>  <br>    // Hash to compare<br>    receivedHash: receivedHash,<br>    <br>    // Original webhook data<br>    webhookBody: body,<br>    headers: headers<br>  }<br>};</pre><p>Next, create a crypto node after the code node. This node will generate a signature from the webhook body. The generated signature must match the x-hub-signature from the webhook header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Y37f8KSA3ICRzIyhRJ6ZMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5qLIQ7ns89FSshQ8TRDJA.png" /></figure><p>As you can see from the image above. We will use</p><p>Action: HMAC</p><p>Type: SHA256</p><p>Value: {{ $json.dataToHash }} (the JSON string from response body)</p><p>Property Name: dataToHash (the output)</p><p>Secret: <em>your Bitbucket webhook secret</em></p><p>Encoding: HEX</p><p>When you click execute step, the workflow will compare the received signature and dataToHash. If they match, the request is verified and will proceed to the next step. If they don’t match, return an error.</p><p>Next step, we will add a code node to verify the signature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FF0_BjRuB4PlWo-_bwyrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnEr9WK3mkJMFcu6YrIF8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZteUZtZKlrmA5sm0KpI4lQ.png" /></figure><p>In this section, we’ll verify the signature. If it doesn’t match, we’ll return an error. Here’s the sample code:</p><pre>const data = $input.first().json;// Crypto node outputs the hash to &#39;data&#39; field<br>const expectedHash = data.dataToHash;<br>const receivedHash = data.receivedHash;<br>console.log(&#39;Expected hash:&#39;, expectedHash);<br>console.log(&#39;Received hash:&#39;, receivedHash);<br>console.log(&#39;Match:&#39;, expectedHash === receivedHash);<br>if (expectedHash !== receivedHash) {<br>  console.error(&#39;❌ Signature verification FAILED&#39;);<br>  console.error(&#39;Expected:&#39;, expectedHash);<br>  console.error(&#39;Received:&#39;, receivedHash);<br>  <br>  // Send alert to DingTalk<br>  return {<br>    json: {<br>      error: &#39;Invalid signature - authentication failed&#39;,<br>      authenticated: false,<br>      expectedHash: expectedHash,<br>      receivedHash: receivedHash<br>    }<br>  };<br>}<br>console.log(&#39;✅ Signature verified successfully!&#39;);<br>// Pass the webhook body forward<br>return {<br>  json: {<br>    ...data.webhookBody,<br>    _authenticated: true,<br>    _verifiedAt: new Date().toISOString(),<br>    _clientIP: data.headers[&#39;x-forwarded-for&#39;] || &#39;unknown&#39;<br>  }<br>};</pre><h3>Step 4: Parsing Webhook Data for AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*VI707rDKER3HYUBelajmIA.png" /></figure><p>Add a code node to parse the data and extract the diff. The diff shows what changed in the code commit. You’ll need the fields shown in the image below. The diffUrl will be sent to Bitbucket to get the diff data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYGryzyqjn65F_MXS21YLQ.png" /></figure><h3>Step 5: Get the diff Data from Bitbucket</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*ELTMXDgchHnADwjW54lahA.png" /></figure><p>We will add an HTTP Request node to get the diff data from Bitbucket. To get the diff data from Bitbucket, we need to create a token for authorization. We’ll create a new token from Repository Settings → Access Tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKnVnvt09Po6AROxRbLwsA.png" /></figure><p>You can configure your token settings to match the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVJH24nn9v2gmQohksZYVw.png" /></figure><p>After creating the token, save it in a secure place. In the HTTP Request node, configure the settings to match the image below. Add the access token that you just created to the Authorization header key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*5oZax6Yc7hPFzUdaHtjDtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*Nt3kNab5kYKhAsbmFinAiA.png" /></figure><h3>Step 6: Parsing data diff and prompt</h3><p>We’ll add another code node to N8N. In this node, we’ll parse the diff data, commit stats, commit info, and the prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*_9HtbvJtg5prbxVqaC7Vcw.png" /></figure><p>The Node code</p><pre>const diffResponse = $input.first().json;<br>const commitInfo =$(&quot;Parsing Webhook&quot;).first().json// Get the diff content from data.data<br>const diffContent = diffResponse.data;console.log(&#39;📄 Diff length:&#39;, diffContent.length);<br>console.log(&#39;📝 First 100 chars:&#39;, diffContent.substring(0, 100));<br>// Clean the diff (remove escaped newlines if any)<br>const cleanDiff = diffContent<br>  .replace(/\\\\n/g, &#39;\\n&#39;)<br>  .replace(/\\\\t/g, &#39;\\t&#39;)<br>  .trim();<br>// Parse file changes<br>const fileChanges = [];<br>const diffBlocks = cleanDiff.split(&#39;diff --git&#39;);<br>for (const block of diffBlocks) {<br>  if (block.trim()) {<br>    const fileMatch = block.match(/a\\/(.*?) b\\//);<br>    if (fileMatch) {<br>      const fileName = fileMatch[1];<br>      const additions = (block.match(/^\\+[^+]/gm) || []).length;<br>      const deletions = (block.match(/^-[^-]/gm) || []).length;<br>      <br>      fileChanges.push({<br>        name: fileName,<br>        additions,<br>        deletions<br>      });<br>    }<br>  }<br>}<br>const stats = {<br>  filesChanged: fileChanges.length,<br>  additions: fileChanges.reduce((sum, f) =&gt; sum + f.additions, 0),<br>  deletions: fileChanges.reduce((sum, f) =&gt; sum + f.deletions, 0),<br>  files: fileChanges<br>};<br>console.log(&#39;📊 Stats:&#39;, stats);<br>// Create AI prompt<br>const prompt = `Review this code change for security, quality, and bot detection platform impact.<br>**Repository:** ${commitInfo.repoFullName}$(&#39;Parsing Webhook&#39;).first().json.repoFullName<br>**Commit:** ${commitInfo.commitHash.substring(0, 7)}<br>**Author:** ${commitInfo.author}<br>**Branch:** ${commitInfo.branch}<br>**Message:** ${commitInfo.commitMessage}<br>**Statistics:**<br>- Files changed: ${stats.filesChanged}<br>- Lines added: +${stats.additions}<br>- Lines removed: -${stats.deletions}<br>**Files modified:**<br>${stats.files.map(f =&gt; `- ${f.name} (+${f.additions}/-${f.deletions})`).join(&#39;\\n&#39;)}<br>**Code Changes:**<br>\\`\\`\\`diff<br>${cleanDiff}<br>\\`\\`\\`<br>**Review Guidelines:**<br>1. Security issues - authentication, data validation, injection risks<br>2. Code quality - readability, maintainability, best practices  <br>3. Performance - potential bottlenecks or optimizations<br>4. Bot detection logic - impact on detection algorithms<br>5. Bugs - potential runtime errors or logic issues<br>Provide a concise summary at the end with action items (if any).`;<br>return {<br>  json: {<br>    diff: cleanDiff,<br>    stats: stats,<br>    commitInfo: commitInfo,<br>    prompt: prompt<br>  }<br>};</pre><h3>Step 7: Add AI Review</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*FccPKbLIdumgZgEYmSD_VA.png" /></figure><p>This is the most important part — we’ll add an AI Agent node. Don’t forget to also add a Chat Model node. You can use any model you like: OneAI, DeepSeek, Gemini, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*px2UQ6qDzfKpk3Mu_aeY7g.png" /></figure><p>For the system message, you can add your own prompt, or you can follow my prompt</p><pre>You are a senior Staff-level Software Engineer and Security Reviewer.<br>Your role is to perform professional pull request reviews across:<br>- Python (FastAPI, async, concurrency, clean architecture)<br>- JavaScript / TypeScript<br>- React applications<br>- API design<br>- Distributed systems<br>- Security best practices<br>- Performance optimization<br>- Bot detection &amp; abuse prevention<br>- Scalability &amp; maintainability<br>Review the provided code diff like a real senior reviewer in an enterprise environment.<br>Your review must:<br>1. Focus ONLY on modified or added code.<br>2. Identify:<br>   - Bugs<br>   - Edge cases<br>   - Security vulnerabilities<br>   - Performance issues<br>   - Concurrency risks<br>   - Clean architecture violations<br>   - Code smells<br>   - Missing validation<br>   - Breaking changes<br>3. Suggest concrete improvements with example code when helpful.<br>4. Classify issues by severity:<br>   - 🔴 Critical (must fix before merge)<br>   - 🟡 Major (should fix)<br>   - 🔵 Minor (optional improvement)<br>5. Mention positives if applicable.<br>6. Be concise but technically deep.<br>7. Do NOT repeat the code unless necessary.<br>8. Avoid generic comments. Every point must be actionable.<br>Format the response as:<br>## Summary<br>Short overall assessment.<br>## 🔴 Critical Issues<br>- ...<br>## 🟡 Major Issues<br>- ...<br>## 🔵 Minor Improvements<br>- ...<br>## ✅ Positive Notes<br>- ...<br>If no issues are found, clearly state:<br>&quot;No critical issues found. Code is production-ready with minor suggestions.&quot;</pre><p>You can try to execute the step to get the output review.</p><h3>Step 8: Parse and send the comments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GROqGqOVm6sNHGemAyX3cw.png" /></figure><p>The next step is to send the comment to Bitbucket, but first we need to clean up the AI review. Add a code node after the AI Agent Node and include the code below. This code also retrieves the commentUrl for the comment location.</p><pre>// Code Node - Format Review for Bitbucket<br>const aiReview = $input.first().json.output<br>const commitInfo = $(&#39;Parsing Response Diff&#39;).first().json.commitInfo<br>// Clean up escaped newlines<br>const cleanedReview = aiReview<br>  .replace(/\\\\n/g, &#39;\\n&#39;)<br>  .replace(/\\\\t/g, &#39;\\t&#39;)<br>  .trim();<br>// Create formatted comment<br>const commentMarkdown = `## 🤖 AI Code Review<br>**Repository:** ${commitInfo.repoFullName}  <br>**Commit:** [\\`${commitInfo.commitHash.substring(0, 7)}\\`](${commitInfo.commitUrl})  <br>**Author:** ${commitInfo.author}  <br>**Branch:** ${commitInfo.branch}<br>---<br>${cleanedReview}<br>---<br>*🤖 Automated review powered by AI*  <br>*Review generated: ${new Date().toLocaleString()}*`;<br>return {<br>  json: {<br>    commentUrl: `https://api.bitbucket.org/2.0/repositories/${commitInfo.repoFullName}/commit/${commitInfo.commitHash}/comments`,<br>  content: {<br>    raw: JSON.stringify(commentMarkdown),<br>    markup: &quot;markdown&quot;<br>  }<br>  }<br>};</pre><p>The final step is to add an HTTP Request node to send the comment to Bitbucket. Set the parameter value to match the image below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*dauP4MDkYq21Uk6I1fo9gQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*dAosKzSabQ4O1J8fu2Qx0Q.png" /></figure><p>Try to execute, and you can see the comment inside the commit page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7BNC22AiIhtfJZ-gtlRRQ.png" /></figure><p>You can add more steps to send notifications to your chat application, like WhatsApp, Telegram, or Slack. In the end, the real win was not just getting an AI to “review code,” but building a workflow that makes good engineering habits hard to skip. By connecting Bitbucket events to an N8N pipeline, verifying every webhook call, extracting the right context from diffs, and posting structured feedback back into the PR, you turn reviews into a consistent, repeatable system instead of a best-effort ritual. From here, you can iterate safely: refine the prompt, tune the severity rules, and add more checks as your codebase grows. The result is a review loop that is faster, more reliable, and still grounded in the same goal code reviews have always served: shipping better software with fewer surprises.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7454da42d643" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Web Vital]]></title>
            <link>https://medium.com/@ridwanfansuri/core-web-vital-44b19e844046?source=rss-92efd285f2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/44b19e844046</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[web-dev-101]]></category>
            <dc:creator><![CDATA[ridwanf]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 14:03:30 GMT</pubDate>
            <atom:updated>2024-06-12T14:03:30.145Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Story behind</strong></h3><p>On May 28, 2020, Google introduced a concept called web vitals, which they later integrated into their search page ranking algorithm. Consequently, everyone began implementing the core web vitals.</p><p>Core web vitals consist of three metrics: <strong>Loading, Interactivity, and Visual Stability.</strong> These are crucial for any website. A good website should load quickly, respond to input promptly, and ensure no layout shifts or unexpected movements occur when the site is open.</p><h3>Largest Contentful Paint (LCP)</h3><p>The Largest Contentful Paint (LCP) measures how quickly the largest element on your page loads. So how do we measure the LCP? We first identify the largest visible element within the user’s viewport. The time it takes for this element to load is considered the LCP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8UMiBGRDK_1ZgVN86_uUw.png" /></figure><p>If your Largest Contentful Paint (LCP) is less than 2.5 seconds, your LCP score is good. If it falls into the orange zone (2.5–4 seconds), you need to improve your LCP.</p><p>What elements should we consider?</p><ul><li>‘img’ elements</li><li>Image elements inside an ‘svg’</li><li>Videos in Chrome version 116 and above</li><li>Elements with a background image loaded via ‘url()’</li><li>Block-level text elements (like ‘H1’, ‘paragraph’, etc.)</li></ul><p>How to Improve LCP score:</p><ul><li>Start loading the LCP resource as soon as possible</li><li>Preload scanner</li><li>fetchpriority=”high” or loading=&quot;eager&quot;</li><li>Less complex DOM</li><li>Optimized, smaller resource</li><li>CDN optimisation</li><li>Inline critical styles</li><li>reduce initial CSS</li><li>Never Lazy-load LCP element</li></ul><h3>Interaction to Next Paint (it was FID, started in march 2024)</h3><p>If you know the FID, FID measures how much time it takes the browser to respond to input from the user. Like you on the web page and then you tap to an input box and start typing. The problem is FID only measures the first interaction and easy to make the first interaction happen. Google comes with a new metric called Interaction to Next Paint. It measures all the interactions and the latency of all interactions that the user makes on the page. If you have a lower score that means that you have a responsive web. And it measures interactions like clicking the mouse, typing, pressing the key, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E67dDMkeH_rMDo_5RG-7bw.png" /></figure><p>An interaction consists of three parts:</p><ul><li>Input delay: The user initiates the interaction, which ends when the event callback begins to run</li><li>Processing time: time for the event callback to run to completion</li><li>Presentation delay: the time it takes for the browser to show the next frame</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QyJfDv0IhZpKalfEQuNm6g.png" /></figure><p>from the image above an input delay occurs until event handlers start running. In the example, if you click the button and the button has an event callback, until the event callback runs it will be input delay. The second part is processing time, processing time is how much time the event callback takes to run to completion. The last is presentation delay, when it comes to an interaction you expect some change like the data to get displayed. The time taken when the browser shows the next frame after the event callback will be a presentation delay.</p><p>How to reduce input delay</p><ul><li>Avoid long tasks (see devtools → Performance for long tasks)</li><li>Avoid interaction overlap (use debounce, use AbortController</li></ul><p>How to optimize processing time</p><ul><li>Optimize event callbacks by yielding to the main thread often</li><li>setTimeout will add a function to the message queue, allowing other functions/events already residing on the message queue to executed</li><li>Use it in conjunction with isInputPending()</li></ul><p>Reduce Presentation delay:</p><ul><li>Avoid large, complex layout</li><li>avoid geometric properties if possible (width, heights, left, top)</li><li>Simplify the DOM structure. More complex DOM = more time for layout update</li><li>Avoid layout thrashing</li><li>Do not apply a series of consecutive reads and writes to DOM</li></ul><h3>Cumulative Layout Shift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRb_M53yph0egXdN63MIuQ.png" /></figure><ul><li>CLS measures the largest burst of layout shift, for every unexpected layout shift that happens during the entire lifespan of a page. Which is measures how much content on the page moves or shifts around.</li></ul><h4>To fix CLS:</h4><ul><li>Font Loading API (<a href="https://www.w3.org/TR/2023/WD-css-font-loading-3-20230406/">https://www.w3.org/TR/2023/WD-css-font-loading-3-20230406/</a>)</li><li>Add image dimensions</li><li>Avoid late-loading content (or use aspect-ration css property)</li><li>FOUT (flash of unstyled text) and FOIT (flash of invisible text)</li><li>font-display: optional</li><li>size-adjust</li><li>size adjust calculator: <a href="https://deploy-preview-15--upbeat-shirley-608546.netlify.app/perfect-ish-font-fallback/?font=Montserrat">https://deploy-preview-15--upbeat-shirley-608546.netlify.app/perfect-ish-font-fallback/?font=Montserrat</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44b19e844046" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Your Payment Card]]></title>
            <link>https://medium.com/dana-engineering/inside-your-payment-card-b3fc4de1272f?source=rss-92efd285f2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3fc4de1272f</guid>
            <category><![CDATA[payment-card-industry]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[ridwanf]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 08:05:31 GMT</pubDate>
            <atom:updated>2022-08-24T08:05:31.734Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvPdXFK2MmjF6xCs5bl_-g.png" /></figure><p>A long long time ago there was a big animal that lived in this world called dinosaurs. When they lived the earth was a very different place. But we’re not gonna talk about dinosaurs, we gonna talk about the payment card, yes. your payment card.</p><p>The payment card is a card for cashless payment at retailers, internet stores, or for cash withdrawals at ATMs. It was issued by the bank when you created the bank account. Everyone has their own card payment, like a debit card or credit card. But do they know how the payment card is working? But first I want to share the payment card history</p><h3><strong>Payment Cards History</strong></h3><p>In the late 1880s when the US author name’s Edward Bellamy wrote about the concept of credit cards in his novel Looking Backward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OClPNJvYM8utesL-DjavcQ.jpeg" /></figure><p>Then in the new century in 1914, Western Union provide some customers with a metal card, giving them deferred payment privileges. They call the card ‘metal money’ but it could only be used for purchase within the stores owned by the company. In the mid-1900’s a lot of financial institutes issued their own payment card like Diners Club, American Express. In 1966 Barclaycard issued the first all-purpose credit card. In 1987 the first debit card was launched in the UK and guess who is the first to issue the debit card? Barclays is the first financial institution that issued debit cards. Until now there are a lot of innovations like contactless cards etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*xCgz7Y69F3vI7w5f.jpg" /></figure><h3>Payment Card Adoption</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*LuUvkfRMzakqQha8EcJ0gg.png" /></figure><p>The image above is the survey result from VISA consumer Payments trends in Southeast Asia in 2015. From the image above we can see that more than half of the population in South East Asia prefer using cards over cash. Led by Singapore with 76%, followed by Indonesia with 69%.</p><p>The reason why people use cards instead of cash is mostly its convenience and security. And some people feel so hassle carrying notes and wish for others to count cash</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*afVeIl2rKYfuCfY3RWvpaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*_BcwHJ9-0Jg027Xq-IoxGQ.png" /></figure><p>Almost half of the people in southeast Asia have more than 1 payment card. The factor why people have more than one card is because every card/bank has a different facility, like transfer to a bank from another country: cost-free and many more.</p><h3>Inside Your Payment Card</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KWC8IJp-tWX9Tzwf.jpg" /></figure><p>Have you ever think what is actually inside your card payment? how can it do transactions in merchant? Actually, your payment card has the data inside it. Although all payment cards use different logos and colors, they have the same data element on them. Starting from the front.</p><h4>Card Issuer Name</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHuwk4cENBuiiLS-rznSCA.png" /></figure><p>There will always be the name of the card issuers like a bank or card scheme.</p><h4>EMV Chip</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kw_Li_9pvsuMc_6vDjvL4g.png" /></figure><p>If you look at the image above there will be a yellow chip called EMV chip, the EMV chips help make the transaction more secure.</p><h4>Primary Account Number</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-NwDfstTS3B4FbxBKfMrw.png" /></figure><p>Across the middle of the card and the bigger one, there will be a 15 or 16 digit card number, which the payment industry call, the <strong>primary account number</strong> (PAN). The first 6 digits are the bank identification number (BIN). The BIN is unique for every bank.</p><h4>Valid Thru Date</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UqU8CYXbNNNJ4TGh6NJblg.png" /></figure><p>Some cards will have a valid from and valid thru date or just valid thru date only.</p><h4>Card Holder Name</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTpnl3i3klSGKR0vbKQV5g.png" /></figure><p>There will be a cardholder name you can request from your bank which name you want to write on your card.</p><h4>Card Brand Logo</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJ4IVIR72D0j5jEheo1hPQ.png" /></figure><p>And the last is a logo from the card brand like master card, American Express, etc;</p><p>On the back of the card not much information as on the front. Only contain a magnetic stripe, a signature stripe, and the hologram.</p><h4>The Magnetic Stripe</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xXQGelaTXDCtttBi9sZmgQ.png" /></figure><p>The magnetic stripe contains all the data on the front of the card and more in the digital form that can be read by the merchant’s equipment known as a track. Usually, a magnetic card has 2 tracks inside it. Track one is 80 characters long, and contains the primary account number, card holder’s name, expiration date, service code, and CVV. Track 2 is much shorter than track 1. It will be 40 characters that contain the primary account number, expiration date, service code, and the CVV</p><h3>Card payment type</h3><p>How many payment cards do you have? actually, I have more than 5 cards, but only have 3 types of cards payment which is: <strong>Credit card</strong>, <strong>Debit Card</strong>, and <strong>prepaid card</strong>. Those are the type of cards that are commonly used in our life. So what is the difference between them, I will explain it.</p><h4>Credit Card</h4><p>A credit card allows you to make purchases with borrowed money from the bank. As you made a purchase with your credit card, there will be a balance that needs to be repaid at the end of the month.</p><h4>Debit Card</h4><p>On the other hand. When you use a debit card, it will deduct the amount from your bank account</p><h4>Prepaid Card</h4><p>If you want to use a prepaid card you need to fund it first. You can use it in the department store, highway, or on MRT.</p><h3>How Card Payment Card Works</h3><p>Basically, in a card payment transaction there will be 3 participants minimum. Which are: the <strong>cardholder</strong>, the <strong>merchant</strong>, and the <strong>bank</strong>. The cardholder will be using the card to make a transaction. The merchant will get paid after the transaction success, and the bank will check whether the transaction is fraudulent or not and then transfer the money to the merchant, and deduct the money from the cardholder balance. As simple as that. But inside that, the process of card payment transaction will divide into four steps which are: Authorization, Clearing, Settlement, and Undo (chargeback, and refund)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14cjYdQfJqr2dILykdiOBA.png" /></figure><h3>Authorization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4sMJ-e4UDeqHWGdCOVbC0w.png" /></figure><p>Authorization is the process of validating the data that send from the merchant and sending back the result of validation. In the payment card transaction process. The authorization happened when the merchant sends the card data from the cardholder’s card to the bank. How can the merchant read the card data? The merchant can read the card data by swiping the card through the point of sales system. Or with the EMV card reader if the card supports the EMV. Or maybe just tap to the card reader if the card supports the contactless transaction. After reading the card data the merchant will be using the data to make an authorization request. Which data are used in the authorization request? The authorization request will be using the data from track 1 plus merchant id, Merchant name, the amount, and possibly the encrypted value based on the pin.</p><p>The bank then checks the data and determines whether it’s a real or fraudulent transaction. And also check the balance if it was sufficient or not. The bank will send an authorization response to the merchant like accept or decline. For this process to happen, the merchant would have a relationship with every bank in the world that issued payment cards. But it will be so many banks to handle. So merchants will have a relationship with an acquiring bank (the bank that acquiring their payment card transaction). The acquiring bank will build relationships with every card issuing bank in the world. But it is also complicated. To build a relationship between acquiring bank and issuing bank. They need to make an agreement and contract that need a lawyer, and there is a hundred acquiring bank. To solve this problem, between acquiring a bank and issuing a bank there is a card scheme or card brands like VISA, master cards, and JCB. The card scheme connects all the acquiring banks with all the card-issuing banks.</p><h3>Clearing &amp; Settlement</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueUEhQ4vZj99T9FOayxAdw.png" /></figure><p>In clearing each merchant sends a summary of all their day’s transactions to their acquirer, containing the primary account numbers of the card that make the transaction, the authorization reference, and the amount. Every acquirer then splits every merchant’s transaction into each card scheme. The card scheme then sends all the transactions to issuing bank together. The issuing bank then determines how much money they owe to the card scheme. This process is called settlement. The card scheme then sends the money to the acquiring bank, which separates it and sends it to the merchant. Some merchants get the fund the next day or maybe wait a few days based on the agreement between the merchant and their acquiring bank.</p><h3>Undo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skGjFhmAxByNzAQWfpvnVw.png" /></figure><p>When a transaction goes wrong, like wrong card holder’s account, or wrong nominal, or the goods already sold. The cardholders must want to undo the transactions. There will be two-way transactions that can be undone. First, the merchant can refund the transaction</p><p>The merchant will send a similar message like an authorization request but doesn’t include sensitive information, just a PAN, cardholder name, expiration date along with the amount that is refunded. The issuer will send back a refund response to the merchant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VT6c1XtzYfZzna_1YxANww.png" /></figure><p>The second is the cardholder doing a chargeback. The transaction can be undone by the cardholder contacting their bank. Usually, they have to complete a form, The issuing bank sends a message via the card scheme to the merchant’s acquirer, requesting the money to be returned. The acquirer then contacts the merchant and asks them to prove the transaction was valid. If the merchant agrees to do the chargeback, the transaction is undone.</p><h3>The PCI Standards</h3><p>Have you ever wondered how can criminals turn stolen card data into cash? They did it in two ways, first, they took the stolen cardholder data to create clone cards to get cash out of ATMs. Or buying goods in shops or online shops with clone cards and selling those goods for cash. There are four types of criminals that are involved in turning card data into money. First, the criminals specialize in stealing card data from companies. The second is the data dealer who sells data. The third is the criminal who monetizes the data by creating a clone card. Last is the mule, the mule is the criminal who turns the cash into goods and then sells the goods to make money.</p><p>What type of data that the criminals need from the card? Basically, they need the entire content from track 1 of the magnetic stripe and the pin to make cash from the ATM. The PAN, expiration date, account name, and CVV2 to make transactions in e-commerce. Mostly they get the data when the payment is in an authorization state. When they get the data they can make the authorization request.</p><h3>How do we stop the criminals?</h3><p>we can stop the criminal from using our card data with the standard procedure that tells people how to protect their data. Every main card scheme like American Express, Discover, JCB, Mastercard, and VISA already has its own standard. But having five different sets of security standards was very confusing for the industry. So in 2006, the payment card industry security standards council was formed. It was formed by the five-card brands, American Express, Discover, JCB, Mastercard, and VISA. They make the PCI standards based on their standards There are basically five payment cards industry standards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJhZHSZl7Cs2ZH5A-uy0Kw.png" /></figure><p>The first is Data Security Standard (PCI DSS). The PCI DSS protects cardholder data in organizations that store, process or transmit cardholder data, including merchants and service providers.</p><p>The PCI DSS consists of 288 logical and physical security requirements that cover six main areas. Which is, building and maintaining a secure network, protecting cardholder data, maintaining a vulnerability management program, implementing strong access control measures, regularly monitoring and testing the network, and maintaining an information security policy. If the merchant buys software that’s been validated to PA-DSS they will find it much easier to meet the requirements of PCI DSS.</p><p>Next Payment Application Data Security Standard (PCI PA-DSS). The PCI PA-DSS is a software development standard designed for the vendor that produces commercial software that involves clearing the payment transaction.</p><p>PTS (PIN Transaction Security) Standards protect cardholder pins wherever they are processed. The PTS has 3 main areas. The first is the Point of Interaction (POI). The POI is concerned with the manufacture and cryptographic key management of POI. The second is PIN, which is concerned with how the organization looked after the cryptographic key used for PIN encryption and PIN decryption. The last is the hardware security module (HSW). The HSW is used to manage and secure the cryptography keys used to encrypt and decrypted PINs in banks and payment service providers.</p><p>The Point-to-point Encryption standard (PCI P2PPE) describes how to encrypt the primary account number in POI devices and decrypt it in a service provider (or acquirer). It specifies the physical and logical controls for key management, the security of the decryption environment, and how the POI devices should be managed. The P2PE standard was developed so that merchants could buy solutions from the service providers, and know the solution had been assessed to a high standard and the cardholder data wouldn’t be accessible in the merchant environment.</p><p>The last is the card production standard. It is a set of physical and logical standards about how cards are manufactured, personalize, and distribute payment cards. Also how to send PINs to consumers.</p><p>With a lot of card types that you have, your wallet will be bulky. But if you using DANA, no need to worry, you can save your debit or credit card inside DANA app for up to 10 cards and you can use all the cards to pay the transaction. So easy and safe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*1O7FhTcn0F0-wu0XUjpLpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ivkdzWdG_TsvHRmybk_d1A.png" /></figure><p><a href="https://www.mckinsey.com/~/media/mckinsey/industries/financial">https://www.mckinsey.com/~/media/mckinsey/industries/financial</a> services/our insights/accelerating winds of change in global payments/2020-mckinsey-global-payments-report-vf.pdf</p><p><a href="https://www.visa.co.id/dam/VCOM/regional/ap/indonesia/newsroom/documents/the-road-ahead-consumer-payment-trends-in-southeast-asia-id.pdf">https://www.visa.co.id/dam/VCOM/regional/ap/indonesia/newsroom/documents/the-road-ahead-consumer-payment-trends-in-southeast-asia-id.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3fc4de1272f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dana-engineering/inside-your-payment-card-b3fc4de1272f">Inside Your Payment Card</a> was originally published in <a href="https://medium.com/dana-engineering">DANA Product &amp; Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Scope]]></title>
            <link>https://medium.com/@ridwanfansuri/dynamic-scope-cb0cb1d02840?source=rss-92efd285f2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb0cb1d02840</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[ridwanf]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 05:39:11 GMT</pubDate>
            <atom:updated>2020-06-16T05:39:11.426Z</atom:updated>
            <content:encoded><![CDATA[<p>sumber: <a href="https://github.com/ridwanf/You-Dont-Know-JS/blob/master/scope%20%26%20closures/apA.md">https://github.com/ridwanf/You-Dont-Know-JS/blob/master/scope%20%26%20closures/apA.md</a></p><p>Pada tulisan <a href="https://medium.com/@ridwanfansuri/lexical-scope-765801059e07">https://medium.com/@ridwanfansuri/lexical-scope-765801059e07</a> kita membicarakan tentang “Dynamic Scope” sebagai “kebalikan” dari “Lexical Scope”, dilihat dari bagaimana <em>scope</em> bekerja pada javascript.</p><p>Kita akan mengulik secara singkat apa itu “dynamic scope”. Untuk memperjelas perbedaan dengan <em>lexical scope</em>. Tetapi hal yang lebih penting adalah sesungguhnya <em>dynamic scope</em> adalah “saudara dekat” dari suatu mekanisme lain yaitu ( this ) dalam javascript.</p><p>Seperti kita lihat pada tulisan <a href="https://medium.com/@ridwanfansuri/lexical-scope-765801059e07">lexical scope</a> , lexical scope adalah seperangkat aturan bagaimana <em>Engine</em> dapat mencari sebuah variable dan dimana menemukannya. Karakteristik penting dari lexical scope adalah lexical scope didefinisikan pada saat <strong>author-time</strong> yaitu pada saat code tersebut ditulis (dengan asumsi tidak menggunakan eval() atau with() ).</p><p><em>Dynamic scope </em>sepertinya bisa terlihat, dan untuk alasan yang baik, ada sebuah model dimana scope dapat ditentukan pada saat <em>runtime</em>, daripada hanya pada saat <em>author-time</em>. mari kita lihat contohnya pada code dibawah</p><pre>function foo() {<br>	console.log( a ); // 2<br>}<br><br>function bar() {<br>	var a = 3;<br>	foo();<br>}<br><br>var a = 2;<br><br>bar();</pre><p><em>Lexical scope </em>memegang RHS (right hand side) reference pada a di foo() yang akan di-<em>resolve</em> pada global variable a , dimana akan menghasilkan 2 sebagai <em>output</em>.</p><p>Kebalikannya, <em>dynamic scope</em> tidak mempersoalkan bagaimana dan dimana fungsi dan <em>scope</em> dideklarasikan, tetapi lebih mempersoalkan <strong>dimana mereka dipanggil</strong>. Dengan kata lain, <em>scope chain</em> berdasar pada <em>call-stack</em>, bukan pada <em>nesting</em> dari <em>scope</em> dalam code.</p><p>Jadi. kalau Javascript mempunyai <em>dynamic scope</em>, ketika foo() dieksekusi, secara teori code diatas akan menghasilkan 3 .</p><pre>function foo() {<br>	console.log( a ); // 3  (not 2!)<br>}<br><br>function bar() {<br>	var a = 3;<br>	foo();<br>}<br><br>var a = 2;<br><br>bar();</pre><p>Bagaimana hal ini bisa terjadi? karena ketika foo() tidak dapat menemukan <em>variable reference</em> dari a , daripada <em>stepping up</em> ke <em>nested</em> (<em>lexical</em>) <em>scope chain</em>, foo() akan menggerakan <em>call-stack</em>, untuk mencari dimana foo() dipanggil. Karena foo() dipanggil dari bar() , itu akan memeriksa variable dalam scope bar() , dan menemukan bahwa sebuah a memiliki value 3 .</p><p>Aneh? mungkin hal ini pertama kali terlintas dalam pikiran kita. tetapi itu karena kita hanya pernah bekerja pada code dengan <em>lexical scope</em>. jadi <em>dynamic scope</em> terlihat asing.</p><p>Agar semua jelas, faktanya javascript <strong>tidak</strong> memiliki dynamic scope. javascript memiliki lexical scope, plain dan simple. tetapi mekanisme this terlihat seperti dynamic scope.</p><p>kunci yang membedakan: lexical scope pada saat write-time, sedangkan dynamic scope pada saat runtime. Lexical scope memperhatikan dimana fungsi dideklarasikan, tetapi dynamic scope memperhatikan dimana fungsi tersebut dipanggil.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb0cb1d02840" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closures]]></title>
            <link>https://medium.com/@ridwanfansuri/closures-20fc10ef2a55?source=rss-92efd285f2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/20fc10ef2a55</guid>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[ridwanf]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 15:34:55 GMT</pubDate>
            <atom:updated>2020-06-25T14:07:53.537Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*7MTEj_TrCar2e-PL8iAJqw.png" /></figure><p>sumber: <a href="https://github.com/ridwanf/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md">https://github.com/ridwanf/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md</a></p><h4>Kata Pengantar</h4><p>Untuk kalian yang mungkin telah berpengalaman dalam dunia <em>javascript</em>, tetapi mungkin belum pernah mendengar konsep dari <em>closure</em>, <em>closure</em> seolah-olah menjadi hal yang sangat sulit sekali dan membutuhkan <em>effort</em> yang besar.</p><p>Tetapi sesungguhnya <strong><em>closure</em> ada dimana-mana di <em>code</em> yang kalian tulis, kita hanya perlu mengenalinya.</strong> <em>Closure</em> bukanlah sebuah <em>tool</em> yang spesial yang mengharuskan kita untuk belajar <em>syntax</em> baru.</p><p><em>Closure</em> muncul sebagai hasil penulisan code yang berasal dari penggunaan <strong><em>lexical scope</em></strong>. Hal ini terjadi begitu saja, kita tidak perlu membuat <em>closure</em> secara khusus dan kita bisa menggunakannya diseluruh <em>code</em> yang kita buat.</p><p>Tujuan dari tulisan ini adalah agar kita dapat melihat dan merasakan kalau kita telah membuat sebuah <em>closure</em>.</p><p>Mari kita lihat deskripsi dari closure yang kita dapat dari internet</p><blockquote>Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.</blockquote><p>sekarang kita lihat contoh dibawah</p><pre>function foo() {<br>    var a = 2;<br><br>    function bar() {<br>        console.log( a ); // 2<br>    }<br><br>    bar();<br>}<br><br>foo();</pre><p>pada <em>code</em> diatas, fungsi bar() punya akses kepada variable a pada <em>outer enclosing scope</em> karena <em>lexical-scope look-up rules</em>. Apakah ini yang dinamakan closure? technically…. mungkin, tetapi dari definisi <em>what-you-need-to-know</em> diatas tidak sepenuhnya benar. Cara yang paling benar untuk menjelaskan, bar() mereferensikan a melalui <em>lexical scope look-up rule</em>. dan rule tersebut merupakan satu-satunya bagian penting dari apa itu <em>closure</em>.</p><p>Dari sisi pendekatan akademis pada potongan <em>code</em> diatas, fungsi bar() memiliki <em>closure</em> pada scope dari foo() (tentu saja seluruh bagian dari <em>scope</em> tersebut mempunyai akses juga, seperti pada <em>global scope</em> pada kasus ini). Ada pendapat lain juga yang mengatakan bahwa bar() menutup <em>scope</em> dari foo(), kenapa begitu? karena bar() terletak didalam foo().</p><p>Tetapi, pendefinisian <em>closure</em> dengan cara diatas tidak sepenuhnya terlihat pada <em>code</em> diatas. Pada <em>code</em> diatas secara jelas kita melihat<em> lexical scope</em>, tetapi untuk <em>closure</em> masih menjadi misteri yang tersembunyi didalam <em>code</em>.</p><p>mari kita lihat <em>code</em> yang baru lagi</p><pre>function foo() {<br>    var a = 2;<br><br>    function bar() {<br>        console.log( a );<br>    }<br><br>    return bar;<br>}<br><br>var baz = foo();<br><br>baz(); // 2 -- Whoa, closure was just observed, man.</pre><p>Fungsi bar() memiliki <em>lexical scope access </em>ke<em> inner scope </em>dari foo(). Tetapi kemudian kita mengambil bar(), fungsinya sendiri dan mengirimnya sebagai sebuah <em>value</em>. dalam kasus diatas, kita me-<em>return</em> <em>function object</em> yang bar referensikan.</p><p>Setelah foo() dieksekusi, kita me-<em>assign</em> value tersebut kedalam <em>variable</em> bernama baz, dan ketika kita menjalankan baz(), secara langsung kita memanggil inner function bar(), hanya nama identifier nya saja yang berbeda.</p><p>bar() memamng dieksekusi, tetapi dia dieksekusi diluar tempat l<em>exical scopenya</em> berada.</p><p>Setelah foo() dieksekusi, normalnya ekspektasi kita adalah seluruh <em>inner scope </em>dari foo() akan hilang karena <em>garbage collector</em> akan bekerja dan membebaskan <em>memory</em> ketika tidak digunakan.</p><p>Tetapi karena adanya “<em>magic</em>” dari <em>closure</em> maka hal tersebut tidak terjadi. <em>Inner scope </em>foo() masih digunakan dan yang menggunakannya adalah fungsi <strong>bar() itu sendiri.</strong></p><p>Keutamaan dari dimana fungsi bar() dideklarasikan adalah bar() memiliki <em>lexical scope</em> didalam <em>inner scope </em>dari foo() yang menyebabkan <em>scope</em> tersebut tetap hidup untuk bar() sebagai <em>reference</em>.</p><p><strong>bar() tetap memiliki referensi pada <em>scope</em> tersebut, dan referensi itulah yang dinamakan <em>closure</em>.</strong></p><p>Jadi, sepersekian detik kemudian, ketika <em>variable</em> baz dipanggil (memanggil i<em>nner function</em> bernama bar), dan memiliki akses kepada <em>author-time scope</em>, jadi baz bisa meng-akses <em>variable</em> a seperti yang kita harapkan.</p><p>Fungsi tersebut dipanggil dengan baik dari luar <em>author-time lexical scope</em>. <strong><em>Closure</em></strong> mempersilahkan fungsi tersebut mengakses <em>lexical scope</em> yang telah didefinisikan pada saat<em> author-time</em>. Tentu saja berbagai macam cara memperlakukan fungsi sebagai <em>value</em> dan dipanggil ditempat lain merupakan cara dalam mengobservasi <em>closure</em>.</p><pre>function foo() {<br>    var a = 2;<br><br>    function baz() {<br>        console.log( a ); // 2<br>    }<br><br>    bar( baz );<br>}<br><br>function bar(fn) {<br>    fn(); // look ma, I saw closure!<br>}</pre><p>kita memberikan <em>inner function</em> baz melalui bar, dan memanggil<em> inner function </em>(sekarang diberi label fn ), dan ketika dijalankan, hal tersebut membuat <em>closure</em> pada <em>inner scope</em> dari foo() ketika di observasi dengan mengakses a.</p><p>contoh dari ‘<em>passing-around of function’</em> bisa juga secara tidak langsung</p><pre>var fn;<br><br>function foo() {<br>    var a = 2;<br><br>    function baz() {<br>        console.log( a );<br>    }<br><br>    fn = baz; // assign `baz` to global variable<br>}<br><br>function bar() {<br>    fn(); // look ma, I saw closure!<br>}<br><br>foo();<br><br>bar(); // 2</pre><p>cara apapun yang kita gunakan untuk mengirim sebuah <em>inner function</em> keluar <em>lexical scope</em>-nya, <em>inner function</em> tersebut akan tetap menjaga <em>scope reference</em> nya ke tempat dimana fungsi tersebut dideklarasikan, dan dimanapun kita mengeksekusi fungsi itu, <em>closurenya</em> akan dijalankan.</p><h3>Now I Can See</h3><p>Potongan <em>code</em> sebelum ini terlihat tidak alami atau sengaja dibuat untuk menggambarkan penggunaan <em>closure</em>. Contoh code dibawah merupakan potongan <em>code</em> yang biasa kita tulis</p><pre>function wait(message) {<br><br>    setTimeout( function timer(){<br>        console.log( message );<br>    }, 1000 );<br><br>}<br><br>wait( &quot;Hello, closure!&quot; );</pre><p>kita menggunakan sebuah <em>inner function</em> ( timer ) sebagai parameter pada setTimeOut(...) .Tetapi timer telah memiliki sebuah scope closure pada scope wait(...) , dan tentu saja menyimpan dan menggunakan sebuah <em>reference</em> pada variable message.</p><p>Beberapa ribu <em>milisecond</em> setelah wait(...) dieksekusi dan <em>inner scope</em>-nya seharusnya telah hilang, tetapi<em> inner function</em> timer masih memiliki closure pada <em>scope</em> tersebut.</p><p>Jauh kedalam <em>engine</em>, sebuah <em>built-in</em> <em>utility</em> setTimeout(...) memiliki referensi pada beberapa parameter, biasa disebut fn atau func atau apapun itu. <em>Engine</em> akan menjalankan fungsi tersebut yang juga akan menjalankan fungsi timer kita dan referensi <em>lexical scope</em> tetap terhubung.</p><p><strong>Closure</strong>.</p><pre>function setupBot(name,selector) {<br>    $( selector ).click( function activator(){<br>        console.log( &quot;Activating: &quot; + name );<br>    } );<br>}<br><br>setupBot( &quot;Closure Bot 1&quot;, &quot;#bot_1&quot; );<br>setupBot( &quot;Closure Bot 2&quot;, &quot;#bot_2&quot; );</pre><p>contoh diatas adalah jQuery (kalau kamu pernah mengalaminya, berarti kita semumuran). Pada dasarnya kapanpun dan dimanapun kamu memerlakukan fungsi-fungsi (yang memiliki akses kepada<em> lexical scope</em> fungsi tersebut) sebagai<em> first-class value</em> dan memberikan fungsi tersebut pada fungsi lainnya, kita akan dapat melihat bahwa fungsi tersebut menjalankan <em>closure</em>. Apakah itu <em>timer</em>, <em>event handler</em>, <em>Ajax request, cross-window messaging, web workers</em>, atau <em>asyncronous task</em> lainnya.</p><h3>Loops + Closure</h3><p>Contoh yang umum untuk menggambarkan closure adalah pada <strong>for-loop</strong> yang sederhana seperti dibawah</p><pre>for (var i=1; i&lt;=5; i++) {<br>    setTimeout( function timer(){<br>        console.log( i );<br>    }, i*1000 );<br>}</pre><p>kalian pasti menyangka kalau <em>code</em> diatas akan mem-<em>print</em> 1,2,..,5 satu persatu tiap detik. tetapi yang terjadi adalah <em>code</em> tersebut menghasilkan angka 6 sebanyak 5 kali tiap detik. Kenapa bisa begitu? mari kita bedah <em>code</em> diatas. Pertama-tama darimana angka 6 berasal. <em>Loop</em> diatas akan berhenti ketika i tidak &lt;=5. pertama kali hal itu terjadi adalah ketika i = 6, jadi <em>output</em> yang dihasilkan adalah nilai i setelah <em>loop</em> selesai.</p><p>Hal ini akan lebih jelas ketika kita melihat kembali <em>code</em> diatas. <em>Timeout</em> <em>function callback</em> akan berjalan setelah <em>loop</em> selesai. faktanya adalah setelah timeout selesai, meskipun waktunya 0 setTimeout(..,0) pada tiap iterasi, semua <em>callback</em> akan diekseskusi setelah <em>loop</em> selesai, dan akan menghasilkan 6 .</p><p>sebenarnya apa yang terlewat pada code diatas, yang terlewat pada code diatas adalah kita mengartikan bahwa setiap iterasi dari <em>loop</em> meng-‘<em>capture</em>’ duplikasi dari i mereka sendiri, pada waktu iterasi, tetapi cara <em>scope</em> bekerja adalah meskipun didefinisikan sebagai iterasi loop yang berbeda tetapi mereka <strong>berbagi global scope yang sama</strong>. Yang berarti hanya memiliki satu i didalamnya.</p><p>Mari kita coba contoh lainnya,</p><pre>for (var i=1; i&lt;=5; i++) {<br>    (function(){<br>        setTimeout( function timer(){<br>            console.log( i );<br>        }, i*1000 );<br>    })();<br>}</pre><p>contoh diatas akan memberikan hasil yang sama seperti contoh pertama, tetapi kita memiliki <em>lexical scope </em>lebih banyak dari pada contoh sebelumnya. Tidak cukup jika hanya memiliki sebuah <em>scope</em> apabila <em>scope</em> tersebut kosong. Bila kita lihat lebih dekat IIFE pada <em>code</em> hanya berupa <em>scope</em> kosong yang tidak melakukan apa-apa. Scope tersebut butuh variable sendiri, dengan menduplikasikan dari nilai i pada tiap iterasinya seperti pada contoh dibawah.</p><pre>for (var i=1; i&lt;=5; i++) {<br>    (function(){<br>        var j = i;<br>        setTimeout( function timer(){<br>            console.log( j );<br>        }, j*1000 );<br>    })();<br>}</pre><p>dan apabila kita menjalankan diatas, kita akan mendapatkan hasil 1,2,3,4,5. variasi lain dari <em>code</em> diatas seperti ini</p><pre>for (var i=1; i&lt;=5; i++) {<br>    (function(j){<br>        setTimeout( function timer(){<br>            console.log( j );<br>        }, j*1000 );<br>    })( i );<br>}</pre><p>Penggunaan sebuah IIFE didalam iterasi membuat sebuah <em>scope</em> pada tiap iterasi, yang akan memberikan callback fungsi timeout kesempatan untuk menutup scope baru pada tiap iterasi.</p><h3>Modules</h3><p>Ada <em>pattern</em> dari <em>code</em> yang lain yang memanfaatkan kekuatan dari <em>closure</em> tapi bukan <em>callback</em>. mari kita sama-sama bongkar <em>pattern</em> yang paling <em>powerfull</em>, sebuah <strong><em>module</em></strong>.</p><pre>function foo() {<br>	var something = &quot;cool&quot;;<br>	var another = [1, 2, 3];<br><br>	function doSomething() {<br>		console.log( something );<br>	}<br><br>	function doAnother() {<br>		console.log( another.join( &quot; ! &quot; ) );<br>	}<br>}</pre><p>seperti terlihat pada <em>code</em> diatas, tidak ada <em>observable</em> <em>closure</em> yang terjadi. Secara sederhana kita memiliki beberapa variable data <em>private</em> something dan doAnother() , yang keduanya memiliki <em>lexical scope </em>diatas <em>inner scope</em> dari foo().</p><p>tetapi mari kita lihat contoh lain:</p><pre>function CoolModule() {<br>	var something = &quot;cool&quot;;<br>	var another = [1, 2, 3];<br><br>	function doSomething() {<br>		console.log( something );<br>	}<br><br>	function doAnother() {<br>		console.log( another.join( &quot; ! &quot; ) );<br>	}<br><br>	return {<br>		doSomething: doSomething,<br>		doAnother: doAnother<br>	};<br>}<br><br>var foo = CoolModule();<br><br>foo.doSomething(); // cool<br>foo.doAnother(); // 1 ! 2 ! 3</pre><p>Pola diatas merupakan contoh sebuah <strong><em>module</em></strong><em>. </em>Cara paling umum untuk mengimplementasikan biasa disebut “<em>Revealing Module</em>”, dan variasi lain akan kita terangkan disini.</p><p>Mari kita periksa code diatas:</p><p>pertama-tama, CoolModule() hanyalah sebuah fungsi, tetapi harus dipanggil untuk membuat <em>instance</em> dari <em>module</em>. Tanpa eksekusi dari <em>outer</em> <em>function</em> pembuatan<em> inner function </em>dan <em>closure</em> tidak akan terjadi.</p><p>Kedua, fungsi CoolModule() mengembalikan sebuah <em>object</em>, ditunjukan dengan <em>object-literal syntax</em> { key: value, ...}. Object yang di-<em>return</em> memiliki referensi ke <em>inner</em> <em>function</em>, tetapi tidak ke<em> inner data variable</em>. Kita tetap menjadikan <em>variable</em> tersebut <em>private</em> dan tersembunyi, karena sangat penting untuk memikirkan data-data yang di-<em>return</em> hanya yang dibutuhkan saja, sebagai contoh pada <strong>open api</strong>.</p><p>Nilai dari <em>object</em> yang di-<em>return</em> pada akhirnya di-<em>assigned</em> ke <em>outer</em> <em>variable</em> foo dan kitapun dapat mengakses <em>property method</em> tersebut pada API, seperti foo.doSomething().</p><p><strong>Note: </strong>kita tidak perlu mengembalikan sebuah <em>actual object</em> dari <em>module</em> kita. Kita hanya perlu mengembalikan sebuah <em>inner function</em> secara langsung. jQuery merupakan contoh yang bagus.</p><p>fungsi doSomething()dan doAnother() memiliki <em>closure </em>diatas <em>inner scope </em>dari <em>instance</em> sebuah <em>module</em> (pada contoh diatas adalah CoolModule() ). Ketika kita memindahkan fungsi-fungsi tersebut keluar dari <em>lexical scope</em>, melalui <em>property reference</em> dari <em>object</em> yang di-<em>return</em>.</p><p>Secara sederhananya, ada 2 “<em>requirement</em>” sebuah pola <em>module</em> bisa dilakukan:</p><ol><li>Harus ada sebuah <em>outer enclosing function</em>, dan harus di <em>invoked</em> sedikitnya satu kali (setiap membuat sebuah <em>instance</em> baru dari <em>module</em>).</li><li>Sebuah <em>enclosing</em> <em>function</em> harus me-<em>return</em> setidaknya satu <em>inner function</em>, oleh karenia itu <em>inner function</em> tersebut memiliki <em>closure</em> diatas <em>private</em> <em>scope</em>, dan dapat diakses atau dimodifikasi <em>private state</em> tersebut.</li></ol><p>Sebuah <em>object</em> dengan hanya sebuah <em>function property</em> pada <em>object</em> tersebut bukanlah sebuah <em>module</em>. Sebuah <em>object</em> yang di-<em>return</em> dari sebuah fungsi yang dipanggil yang hanya memiliki <em>data properties</em> pada <em>object</em> tersebut dan tidak memiliki <em>closure</em> <em>function</em> bukanlah sebuah <em>module</em>.</p><p>Potongan code diatas memperlihatkan pembuatan <em>module</em> secara mandiri pada CoolModule() yang dapat dipanggil berkali-kali, dan setiap dipanggil akan membuat sebuah <em>module</em> <em>instance</em>. Variasi lain dari pola ini adalah ketika kita hanya butuh satu <em>instance</em> saja atau biasa disebut “<em>singleton</em>”:</p><pre>var foo = (function CoolModule() {<br>	var something = &quot;cool&quot;;<br>	var another = [1, 2, 3];<br><br>	function doSomething() {<br>		console.log( something );<br>	}<br><br>	function doAnother() {<br>		console.log( another.join( &quot; ! &quot; ) );<br>	}<br><br>	return {<br>		doSomething: doSomething,<br>		doAnother: doAnother<br>	};<br>})();<br><br>foo.doSomething(); // cool<br>foo.doAnother(); // 1 ! 2 ! 3</pre><p>pada contoh diatas kita merubah <em>module</em> <em>function</em> menjadi <strong>IIFE</strong>, dan kita memanggil fungsi tersebut langsung ketika fungsi tersebut dibuat dan diberikan <em>return</em> <em>value</em>-nya langsung ke <em>instance</em> <em>module</em> foo</p><p><em>Module</em> hanyalah sebuah fungsi, jadi mereka dapat menerima parameter</p><pre>function CoolModule(id) {<br>	function identify() {<br>		console.log( id );<br>	}<br><br>	return {<br>		identify: identify<br>	};<br>}<br><br>var foo1 = CoolModule( &quot;foo 1&quot; );<br>var foo2 = CoolModule( &quot;foo 2&quot; );<br><br>foo1.identify(); // &quot;foo 1&quot;<br>foo2.identify(); // &quot;foo 2&quot;</pre><p>contoh lain yang <em>powerfull</em> pada <em>module</em> <em>pattern</em> adalah dengan menamakan <em>object</em> yang di-<em>return</em> sama seperti public API:</p><pre>var foo = (function CoolModule(id) {<br>	function change() {<br>		// modifying the public API<br>		publicAPI.identify = identify2;<br>	}<br><br>	function identify1() {<br>		console.log( id );<br>	}<br><br>	function identify2() {<br>		console.log( id.toUpperCase() );<br>	}<br><br>	var publicAPI = {<br>		change: change,<br>		identify: identify1<br>	};<br><br>	return publicAPI;<br>})( &quot;foo module&quot; );<br><br>foo.identify(); // foo module<br>foo.change();<br>foo.identify(); // FOO MODULE</pre><p>dengan tetap memertahankan sebuah <em>inner reference </em>pada public API object didalam<em> instance module</em>, kita dapat memodifikasi <em>module</em> <em>instance</em> dari dalam, termasuk menambahkan dan menghapus <em>method</em>, <em>property</em> dan merubah nilai.</p><h4>Modern Modules</h4><p>bermacam module <em>dependency</em> <em>loader</em>/<em>manager</em> pada dasarnya membungkus <em>pattern</em> dari <em>module definition</em> kedalam sebuah API yang mudah dipahami/digunakan. Daripada membongkar sebuah <em>library</em> , kami akan berikan contoh yang sangat sederhana.</p><pre>var MyModules = (function Manager() {<br>	var modules = {};<br><br>	function define(name, deps, impl) {<br>		for (var i=0; i&lt;deps.length; i++) {<br>			deps[i] = modules[deps[i]];<br>		}<br>		modules[name] = impl.apply( impl, deps );<br>	}<br><br>	function get(name) {<br>		return modules[name];<br>	}<br><br>	return {<br>		define: define,<br>		get: get<br>	};<br>})();</pre><p>Bagian penting dari potongan <em>code</em> diatas adalah modules[name] = iml.apply(impl,deps). Code tersebut memanggil <em>fungsi definition wrapper</em> untuk sebuah <em>module</em>, dan menyimpan <em>return value</em>, yaitu <em>module</em> API, kedalam sebuah <em>internal list</em> dari <em>module</em> yang <em>ditracking</em> berdasarkan nama.</p><p>Dan potongan code dibawah adalah cara mendefinisikan suatu <em>module</em> yang biasa kami pakai:</p><pre>MyModules.define( &quot;bar&quot;, [], function(){<br>	function hello(who) {<br>		return &quot;Let me introduce: &quot; + who;<br>	}<br><br>	return {<br>		hello: hello<br>	};<br>} );<br><br>MyModules.define( &quot;foo&quot;, [&quot;bar&quot;], function(bar){<br>	var hungry = &quot;hippo&quot;;<br><br>	function awesome() {<br>		console.log( bar.hello( hungry ).toUpperCase() );<br>	}<br><br>	return {<br>		awesome: awesome<br>	};<br>} );<br><br>var bar = MyModules.get( &quot;bar&quot; );<br>var foo = MyModules.get( &quot;foo&quot; );<br><br>console.log(<br>	bar.hello( &quot;hippo&quot; )<br>); // Let me introduce: hippo<br><br>foo.awesome(); // LET ME INTRODUCE: HIPPO</pre><p>kedua module “<strong>foo</strong>” dan “<strong>bar</strong>” didefiniskan dengan sebuah fungsi yang me-<em>return</em> public API, “<strong>foo</strong>” bahkan menerima <em>instance</em> dari “<strong>bar</strong>” sebagai sebuah <em>dependency</em> <em>parameter</em> sehingga bisa dipakai secara langsung.</p><h4>Future Modules</h4><p>ES6 menambahkan <em>first-class-syntax support s</em>ebagai konsep dari <em>module</em>. ketika di-<em>load</em> melalui <em>module syste</em>m, ES6 memperlakukan sebuah file sebagai sebuah module terpisah. Setiap <em>module</em> tersebut dapat menambahkan <em>module</em> lain atau API member tertentu sama seperti saat kita menambahkan <em>public</em> API member.</p><p><strong>Note</strong>: <em>Function-base module</em> bukanlah sebuah pola yang static, jadi <em>semantic</em> API mereka tidak diperhatikan sampai <em>run-time </em>terjadi. itu saja. Anda bisa memodifikasi sebuah module API pada saat <em>run-time</em></p><p>sebaliknya, ES6 <em>module</em> API adalah <em>static</em> (API tidak berubah ketika <em>run-time</em>). Karena <em>compiler</em> tahu bahwa module API tersebut dapat di-<em>check</em> ketika <em>file</em> di <em>load</em> dan di-<em>compile</em> yg memeriksa <em>module-module </em>yang diimport. apabila <em>module-module</em> tersebut tidak ada, <em>compiler</em> akan mengeluarkan ‘<em>early</em>’ <em>error</em> pada saat <em>compile</em> dibanding harus menunggu seperti <em>dynamic run-time</em> terdahulu.</p><p>Module ES6 tidak memiliki “<em>inline</em>” format, mereka harus didefinisikan dalam <em>file</em> yang berbeda (satu <em>file</em> tiap <em>module</em>). <em>Browser engine</em> memiliki <em>default</em> “<em>module loader</em>” (yang dapat di ‘<em>overide</em>’) dan me-<em>load module</em> secara <em>synchronous</em> ketika di-<em>impor</em>.</p><p>Contoh:</p><p><strong>bar.js</strong></p><pre>function hello(who) {<br>	return &quot;Let me introduce: &quot; + who;<br>}<br><br>export hello;</pre><p><strong>foo.js</strong></p><pre>// import only `hello()` from the &quot;bar&quot; module<br>import hello from &quot;bar&quot;;<br><br>var hungry = &quot;hippo&quot;;<br><br>function awesome() {<br>	console.log(<br>		hello( hungry ).toUpperCase()<br>	);<br>}<br><br>export awesome;</pre><p>Import <strong>foo</strong> and <strong>bar</strong></p><pre>// import the entire &quot;foo&quot; and &quot;bar&quot; modules<br>module foo from &quot;foo&quot;;<br>module bar from &quot;bar&quot;;<br><br>console.log(<br>	bar.hello( &quot;rhino&quot; )<br>); // Let me introduce: rhino<br><br>foo.awesome(); // LET ME INTRODUCE: HIPPO</pre><p><strong>Note: </strong>dua file yang berbeda <strong>“foo.js” </strong>dan <strong>“bar.js” </strong>butuh untuk di-<em>created</em> didalam <em>content</em> seperti terlihat pada 2 potongan <em>code</em> pertama. Kemudian program kalian akan me-<em>load</em>/<em>import</em> <em>module-module</em> tersebut agar bisa digunakan seperti terlhat pada contoh ke 3.</p><p>import menambahkan satu atau lebih member dari sebuah <em>module</em> API kedalam suatu <em>scope</em> yang terikat atas <em>variable</em> ( hello dalam kasus diatas). module menambahkan seluruh module API untuk mengikat variable ( foo, bar dalam kasus diatas). export mengirimkan sebuah <em>indetifier</em> (<em>varible</em>, <em>function</em>) kedalam public API pada module tersebut. <em>Operator</em> ini dapat digunakan berulang kali didalam sebuah <em>module</em>.</p><p>Cukup sekian tulisan tentang module, sebuah topik yang cukup rumit, apabila kurang jelas mungkin bisa membaca versi bahasa inggris-nya pada link diatas.</p><h3>Bacaan lain :</h3><p><a href="https://www.w3schools.com/js/js_function_closures.asp">https://www.w3schools.com/js/js_function_closures.asp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20fc10ef2a55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function vs. Block Scope]]></title>
            <link>https://medium.com/@ridwanfansuri/function-vs-block-scope-86163331cee4?source=rss-92efd285f2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/86163331cee4</guid>
            <category><![CDATA[javascript-fundamental]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[ridwanf]]></dc:creator>
            <pubDate>Mon, 18 Nov 2019 03:47:34 GMT</pubDate>
            <atom:updated>2019-11-18T03:47:34.774Z</atom:updated>
            <content:encoded><![CDATA[<p>sumber <a href="https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md">https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md</a></p><p>seperti sudah dijelaskan pada post sebelumnya bahwa pada scope terdapat beberapa <em>‘bubbles’ </em>yang setiap <em>bubble </em>berperan sebagai container dimana ada <em>indetifers</em> (<em>variable, function</em>) dideklarasikan. <em>Bubble-bubble </em>ini saling berkaitan.</p><p>Tetapi apa yang sebenarnya membuat sebuah <em>bubble? </em>Apakah hanya fungsi? Apakah struktur javascript lain membuat <em>bubble</em>?</p><h3><strong>Scope From Functions</strong></h3><p>Jawaban paling umum dari pertanyaan diatas adalah, javascript mempunyai ‘Function-based’ scope. yaitu setiap fungsi yang dideklarasikan akan membuat <em>bubble </em>sendiri, tetapi tidak dengan struktur lain. Hal ini tidak sepenuhnya benar, untuk mengetahuinya mari kita lihat contoh dibawah.</p><pre>function foo(a) {<br>	var b = 2;<br><br>	// some code<br><br>	function bar() {<br>		// ...<br>	}<br><br>	// more code<br><br>	var c = 3;<br>}</pre><p>Pada <em>code</em> diatas, <em>scope bubble </em>untuk foo(..) terdapat <em>identifier </em>a,b,c dan bar. Tidak peduli di<em>scope</em> mana a dideklarasikan, variable dan fungsi dimiliki oleh <em>scope bubble </em>dimana mereka terdapat.</p><p>bar(..) mempunyai <em>scope bubble </em>sendiri, begitu juga dengan <em>global scope </em>yang hanya memiliki satu identifier didalamnya yaitu foo(..).</p><p>Dikarenakan a, b, c dan bar dimiliki oleh <em>scope bubble </em>dari foo(...) mereka tidak dapat diakses diluar dari foo(...), dan akan menghasilkan ReferenceError.</p><pre>bar(); // fails<br><br>console.log( a, b, c ); // all 3 fail</pre><p>Semua identifier ( a, b, c, foo, dan bar ) dapat diakses didalam foo(...) dan tentu saja dapat diakses juga didalam bar(...) ( diasumsikan tidak terdapat <em>shadowing</em> didalam bar(...) ).</p><p>Function scope mendorong ide bahwa semua variable dimiliki oleh fungsi, dan dapat digunakan kembali didalam fungsi tersebut ( dan dapat diakses oleh <em>nested scope</em>)</p><h3>Hiding In Plain Scope</h3><p>Cara berpikir tradisional tentang sebuah fungsi adalah: kita membuat sebuah fungsi dan memasukan code kita didalamnya. Tetapi ada cara lain yang sama <em>powerfull</em> yaitu: kita ambil beberapa bagian dari code kita dan membungkusnya kedalam fungsi. Hasil dari cara ini adalah code dalam fungsi tersebut akan `tersembunyi`, sehingga semua deklarasi (variable &amp; fungsi) didalam fungsi akan terikat didalamnya.</p><p>Kenapa harus di-<em>hide</em>? Banyak alasan yang mendasarinya, salah satunya adalah prinsip dari software design yaitu “<em>Principle of least privilege</em>” juga bisa disebut “<em>Least Authority</em>” atau “<em>Least Exposure</em>” yang berarti kita hanya akan meng-<em>expose </em>sedikit saja hal-hal yang penting dan “menyembunyikan” lainnya. Kenapa harus disembunyikan? Jika variable dan fungsi ada di global scope, mereka akan dapat diakses pada scope mana saja. Mari kita lihat contoh dibawah.</p><pre>function doSomething(a) {<br>	b = a + doSomethingElse( a * 2 );<br><br>	console.log( b * 3 );<br>}<br><br>function doSomethingElse(a) {<br>	return a - 1;<br>}<br><br>var b;<br><br>doSomething( 2 ); // 15</pre><p>pada contoh diatas, variable b dan fungsidoSomethingElse(...) seakan-akan merupakan suatu rahasia bagaimana fungsi doSemething(..) bekerja. Memberikan akses scope tertutup pada b dan doSomething(...) bukan hanya tidak penting tapi juga ’berbahaya’ , karena bisa saja mereka diperlakukan secara tidak benar dan melanggar ‘<em>pre-condoition assumption’ </em>dari doSomething(...) yaitu hasil dari doSomething(...) akan berubah ketika nilai b dan doSomethingElse(…) berubah.</p><p>cara lain yang lebih ‘<em>proper</em>’ bisa kita lihat pada contoh dibawah</p><pre>function doSomething(a) {<br>	function doSomethingElse(a) {<br>		return a - 1;<br>	}<br><br>	var b;<br><br>	b = a + doSomethingElse( a * 2 );<br><br>	console.log( b * 3 );<br>}<br><br>doSomething( 2 ); // 15</pre><p>sekarang b dan doSomethingElse(...) tidak dapat diakses dari luar dan hanya dapat di-control oleh doSomething(...). Fungsi dan hasil akhir tidak berubah tetapi secara design kita menyembunyikan hal-hal yang penting.</p><h3>Collision Avoidance</h3><p>Keunggulan lain dari ‘menyembunyikan’ variable dan fungsi kedalam sebuah scope adalah untuk menghindari ‘tabrakan’ yang tidak diinginkan antara 2 identifier yang berbeda dengan nama yang sama tetapi berbeda kegunaan. sebagai contoh:</p><pre>function foo() {<br>	function bar(a) {<br>		i = 3; // changing the `i` in the enclosing scope&#39;s for-loop<br>		console.log( a + i );<br>	}<br><br>	for (var i=0; i&lt;10; i++) {<br>		bar( i * 2 ); // oops, infinite loop ahead!<br>	}<br>}<br><br>foo();</pre><p><em>assignment</em> i = 3 didalam bar(...) akan di overwrite secara tidak terduga. Variable i yang telah dideklarasikan dalam foo(...) pada for-loop. Pada kasus ini akan menghasilkan infinite-loop, karena nilaii akan tetap 3 dan i akan selalu &lt;10.</p><p><em>Assignment</em> dalam bar(...) butuh dideklarasikan sebagai local variable agar dapat digunakan, apapun nama variable yang dipilih var i = 3 akan membetulkan masalah tersebut. Sebuah tambahan<em> </em>tetapi bukan pilihan alternatif yaitu memilih nama identifier yang berbeda seperti var j = 3. Tetapi bila dilihat dari pandangan software design akan memilih nama yang sama. Jadi ‘menyembunikan’ inner declaration akan menjadi pilihan terbaik.</p><p><strong>Global “Namespaces”<br></strong><em>Variable collision</em> biasanya terjadi pada <em>global scope.</em> Banyaknya library yang kita pakai dapat mengakibatkan colission antara satu dengan lainnya apabila library-library tersebut tidak menyembunyikan <em>internal/private</em> fungsi atau variable secara benar.</p><p>Biasanya sebuah library akan mendeklarasikan sebuah variable, atau object. Dikarenakan terbatasnya nama yang unik dalam global scope. Object ini kemudian digunakan sebaga sebuah ‘namespace’ untuk library tersebut. Untuk lebih jelasnya kita lihat pada contoh dibawah</p><pre>var MyReallyCoolLibrary = {<br>	awesome: &quot;stuff&quot;,<br>	doSomething: function() {<br>		// ...<br>	},<br>	doAnotherThing: function() {<br>		// ...<br>	}<br>};</pre><p><strong>Module Management<br></strong>Pilihan lain untuk menghindari collision menggunakan pendekatan yang lebih modern yaitu “module”, dengan menggunakan berbagai macam dependency manager. dengan menggunakan cara ini tidak ada library yang dimasukan kedalam global scope, tetapi dengan menyuruh library-library tersebut agar memiliki indentifiernya sendiri yang diimport ke <em>specific scope</em> yang lain secara explisit.</p><h3>Function As Scopes</h3><p>Kita telah melihat bahwa kita bisa mengambil bagian dari code dan membungkusnya didalam sebuah fungsi dan ‘menyembunyikannya’ dari outside scope. contohnya</p><pre>var a = 2;<br><br>function foo() { // &lt;-- insert this<br><br>	var a = 3;<br>	console.log( a ); // 3<br><br>} // &lt;-- and this<br>foo(); // &lt;-- and this<br><br>console.log( a ); // 2</pre><p>meskipun fungsi diatas bekerja, tapi tidak terlalu ideal, ada beberapa masalah didalamnya. Pertama, kita perlu mendeklarasikan sebuah fungsi bernama foo(). yang berarti nama identifier foo mengotori scope (global dalam kasus ini). Kita juga perlu memanggil fungsi tersebut seperti ( foo() ).</p><p>Akan lebih ideal kalau fungsi tersebut tidak membutuhkan nama agar tidak mengotori global scope.</p><p>untungnya javascript memlikik solusinya</p><pre>var a = 2;<br><br>(function foo(){ // &lt;-- insert this<br><br>	var a = 3;<br>	console.log( a ); // 3<br><br>})(); // &lt;-- and this<br><br>console.log( a ); // 2</pre><p>mari kita bongkar satu-persatu code diatas.</p><p>Pertama, perhatikan fungsi diatas dimulai dengan (function... yang berbeda dengan function... Hal ini terlihat sebagai sesuatu yang minor, tetapi sebenarnya ini merupakan hal yang Major. Dibanding memperlakukan fungsi sebagai sebuah deklarasi yang biasa. Fungsi tersebut kita perlakukan sebagai sebuah function-expression.</p><p><strong>Note: </strong>cara mudah untuk membedakan declaration vs expression adalah dengan melihat posisi dari kata “function” dalam statement (bukan hanya satu baris tetapi sebuah statement). Apabila kata “function” merupakan kata pertama, maka itu merupakan <em>function declaration</em>, selainnya merupakan <em>function expression</em>.</p><h4>Anonymous vs. Named</h4><p>Kita mungkin familiar dengan function expression sebagai callback parameter seperti contoh dibawah:</p><pre>setTimeout( function(){<br>	console.log(&quot;I waited 1 second!&quot;);<br>}, 1000 );</pre><p>hal ini disebut sebagai <em>‘anonymous function expression</em>’, karena function()... tidak memiliki nama identifier didalamnya. Function expression bisa berbentuk anonymous, tetapi function declaration harus memiliki nama. karena apabila tidak akan menjadi grammar JS yang ilegal.</p><p>Anonymous function sangat mudah dan cepat ditulis. tetapi ada beberapa hal yang perlu diperhatikan ketika menggunakannya.</p><ol><li>Anonymous function tidak memiliki nama untuk dilihat pada stack traces. sehingga memnbuat proses debug menjadi sulit.</li><li>Tanpa sebuah nama. ketika sebuah fungsi butuh untuk merefer dirinya sendiri contohnya untuk proses recursif. Proses tersebut membutuhkan fungsi arguments.callee yang sayang sekali sudah <strong>deprecated</strong>.</li><li>Fungsi yang memiliki nama akan lebih mudah untuk didokumentasikan.</li></ol><h4>Invoking Function Expressions Immediately</h4><pre>var a = 2;<br><br>(function foo(){<br><br>	var a = 3;<br>	console.log( a ); // 3<br><br>})();<br><br>console.log( a ); // 2</pre><p>Pada contoh diatas terdapata sebuah fungsi <em>as an expression</em> dengan membungkusnya didalam a ( ). Kita dapat mengeksekusi fungsi tersebut dengan menambahkan sepasang kurung () pada akhir fungsi tersebut, seperti (function foo() { ... })(). Kurung pertama membuat sebuah fungsi menjadi expression, dan yang kedua mengeksekusi fungsi tersebut.</p><p>Pola ini adalah hal yang umum dilakukan, sejarahnya terjadi beberapa tahun lalu ketika komunitas javascript setuju untuk menamakan pola ini sebagai <strong>IIFE</strong> yang berarti <strong>I</strong>mmediately <strong>I</strong>nvoke <strong>F</strong>unction <strong>E</strong>xpression.</p><p>Tentu saja IIFE tidak membutuhkan nama. bentuk IIFE yang paling umum adalah pada <em>anonymous function expression</em>. Tetapi sesungguhnya memberi nama pada IIFE memberikan keuntungan dibandingkan anonymous function seperti diatas. Dibawah ini adalah contoh IIFE yang mempunyai nama</p><pre>var a = 2;<br><br>(function IIFE(){<br><br>	var a = 3;<br>	console.log( a ); // 3<br><br>})();<br><br>console.log( a ); // 2</pre><p>fungsi diatas merupakan bentuk yang berbeda dari IIFE sebelumnya, tetapi proses yang terjadi identik. Bentuk lain dari IIFE bisa dilihat pada contoh dibawah</p><pre>var a = 2;<br><br>(function IIFE( global ){<br><br>	var a = 3;<br>	console.log( a ); // 3<br>	console.log( global.a ); // 2<br><br>})( window );<br><br>console.log( a ); // 2</pre><p>kita memberikan window object reference tetapi kita memberi nama kepada parameter global , sehingga kita punya gambaran yang jelas antara global dan non-global reference. Masih banyak contoh-contoh IIFE lainnya, bisa kita lihat pada link di awal.</p><h3>Blocks As Scopes</h3><p>Meskipun kamu mungkin belum pernah menulis block-scoped secara langsung, tapi mungkin kita familiar dengan dengan code dibawah ini</p><pre>for (var i=0; i&lt;10; i++) {<br> console.log( i );<br>}</pre><p>pada code diatas kita mendeklarasikan variable i secara langsung didalam for-loop head, karena kita hanya menggunakan i pada for-loop saja, tanpa sadar bahwa variable tersebut membuat scope sendiri. Hal tersebut merupakan contoh <strong><em>block-scoping</em></strong><em> </em>dimana kita mendeklarasikan variable sedekat mungkin pada tempat dimana mereka digunakan. Contoh lain bisa dilihat dibawah ini.</p><pre>var foo = true;<br><br>if (foo) {<br>	var bar = foo * 2;<br>	bar = something( bar );<br>	console.log( bar );<br>}</pre><p>pada code diatas kita menggunakan variablebar hanya didalam<strong> if-statement context</strong>. Hal itu membuat kita merasa bahwa kita telah mendeklarasikan variable tersebut didalam if-block. Tetapi, letak kita mendeklarasikan variable tidak akan relevant ketika menggunakan var, karena variable tersebut akan selalu dimiliki oleh<em> </em><strong><em>global scope</em></strong>. Hal ini dinamakan <strong>“<em>fake</em>” <em>block-scoping</em></strong></p><p>Berdasarkan contoh code for-loop diatas, kenapa kita harus mengotori scope dari fungsi dengan variable i yang hanya digunakan didalam for-loop? Hal lain yang penting adalah developer harus memeriksa apakah variable tersebut tidak sengaja digunakan ditempat lain yang mengakibatkan error.</p><h4>with</h4><p>Kita telah mempelajari with pada chapter 2. with merupakan salah satu contoh dari<strong><em> block-scope</em></strong> karena scope pada with terbentuk dari object yang exist pada with statement bukan pada enclosing scope.</p><h4>try/catch</h4><p>Hanya sedikit yang tahu kalau dalam Javascript pada ES3 telah membuat deklarasi variable pada klausacatch dari try/catch untuk menjadi block-scope pada catch block. sebagai contoh</p><pre>try {<br>	undefined(); // illegal operation to force an exception!<br>}<br>catch (err) {<br>	console.log( err ); // works!<br>}<br><br>console.log( err ); // ReferenceError: `err` not found</pre><p>seperti yang bisa kita lihat pada contoh diatas. err hanya exists pada klausa catch saja, dan akan menghasilkan <em>error</em> ketika kita mencoba mereferensikan ditempat lain.</p><h4>let</h4><p>Pada ES6 terdapat salah satu cara untuk mendeklarasikan variable, yaitu dengan let, letakan mengikat sebuah variable pada scope didalam block variable tersebut dideklarasikan biasanya didalam {...} . Dengan kata lain let secara implisit ‘membajak’ sebuah block scope untuk variable tersebut.</p><pre>var foo = true;<br><br>if (foo) {<br>	let bar = foo * 2;<br>	bar = something( bar );<br>	console.log( bar );<br>}<br><br>console.log( bar ); // ReferenceError</pre><p>menggunakan let untuk menggunakan variable dengan nama yang sama pada block yang berbeda akan membuat bingung. karena kita harus memberikan perhatian lebih pada variable tersebut, block mana variable tersebut terdapat dana nilai didalamnya</p><h4>Garbage Collection</h4><p>Manfaat block-scoping antara lain berhubungan dengan <strong><em>closures</em></strong> dan <strong><em>garbage collection</em></strong> dalam hal menggunakan memory.</p><pre>function process(data) {<br>	// do something interesting<br>}<br><br>var someReallyBigData = { .. };<br><br>process( someReallyBigData );<br><br>var btn = document.getElementById( &quot;my_button&quot; );<br><br>btn.addEventListener( &quot;click&quot;, function click(evt){<br>	console.log(&quot;button clicked&quot;);<br>}, /*capturingPhase=*/false );</pre><p>pada contoh diatas fungsi click tidak butuh variable someReallyBigData sama sekali. Artinya secara teori, setelah proses process berjalan, data besar yang membutuhkan memory yang besar juga dapat dihapus (garbage collected). Dibawah adalah contoh menggunakan block-scope dalam meng-handle someReallyBigData</p><pre>function process(data) {<br>	// do something interesting<br>}<br><br>// anything declared inside this block can go away after!<br>{<br>	let someReallyBigData = { .. };<br><br>	process( someReallyBigData );<br>}<br><br>var btn = document.getElementById( &quot;my_button&quot; );<br><br>btn.addEventListener( &quot;click&quot;, function click(evt){<br>	console.log(&quot;button clicked&quot;);<br>}, /*capturingPhase=*/false );</pre><p>pada contoh diatas kita menggunakan block-scope untuk memastikan agar engine tidak menyimpan someReallyBigData .</p><h4>let Loops</h4><p>Salah satu contoh dimana let ‘bersinar’ adalah dalam for-loop, serperti dibawah</p><pre>for (let i=0; i&lt;10; i++) {<br>	console.log( i );<br>}<br><br>console.log( i ); // ReferenceError</pre><p>contoh diatas bukan sekedar melakukan let didalam for-loop header pada variable i untuk for-loop body, tetapi juga <strong>re-bind</strong> variable i pada tiap iterasi dari loop tersebut, memastikan untuk me<strong><em> re-assign </em></strong>nilai dari akhir iterasi sebelumnya. Mari kita lihat contoh lainnya</p><pre>{<br>    let j;<br>    for (j=0; j&lt;10; j++) {<br>        let i = j; // re-bound for each iteration!<br>        console.log( i );<br>    }<br>}</pre><h4>const</h4><p>Sebagai tambahan untuk let ,ES6 memperkenalkan const yang merupakan block-scoped variable tetapi nilainya fixed. Apabila kita mencoba merubah nilainya makan akan mengakibatkan error.</p><pre>var foo = true;<br><br>if (foo) {<br>    var a = 2;<br>    const b = 3; // block-scoped to the containing `if`<br><br>    a = 3; // just fine!<br>    b = 4; // error!<br>}<br><br>console.log( a ); // 3<br>console.log( b ); // ReferenceError!</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86163331cee4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lexical Scope]]></title>
            <link>https://medium.com/@ridwanfansuri/lexical-scope-765801059e07?source=rss-92efd285f2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/765801059e07</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-fundamental]]></category>
            <dc:creator><![CDATA[ridwanf]]></dc:creator>
            <pubDate>Wed, 21 Aug 2019 02:45:24 GMT</pubDate>
            <atom:updated>2019-08-21T02:45:24.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_C45PcaRYrqn3rUs2p8mw.jpeg" /></figure><p>Sumber: <a href="https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch2.md">https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch2.md</a></p><p>Pada post <a href="https://medium.com/@ridwanfansuri/javascript-scope-what-is-scope-c16ea0c45d11">sebelumnya </a>telah dijelaskan apa itu <em>‘Scope’. </em>Ada 2 macam model <em>scope </em>yang sering digunakan. Yang pertama dana yang paling sering digunakan adalah <strong><em>Lexical Scope </em></strong>dan yang kedua adalah <strong><em>Dynamic Scope. </em></strong>Pada kali ini kita akan membahas tentang <em>Lexical Scope.ime</em></p><h3><strong>Lex-time</strong></h3><p>Seperti yang telah kita pelajari pada post sebelum ini, Fase awal pada <em>compiler </em>standar disebuat <em>lexing</em> (tokenisasi). Ketika dipanggil, prosess <em>lexing </em>memecah sebuah string dari code kedalam kumpulan token yang memiliki arti sebagai hasilnya. Konsep ini akan kita gunakan sebagai dasar untuk mengerti apa itu <em>lexical scrope </em>dan darimana nama tersebut berasal.</p><p>Arti <em>lexical scope </em>dari sisi lain adalah <em>scope </em>yang didefinisikan pada saat <em>lexical time</em>. Dengan kata lain, <em>lexical scope </em>berasal pada saat dimana variabel dan blok dari scope dibuat.</p><p>mari kita lihat code dibawah</p><pre>function foo(a) {<br><br>	var b = a * 2;<br><br>	function bar(c) {<br>		console.log( a, b, c );<br>	}<br><br>	bar(b * 3);<br>}<br><br>foo( 2 ); // 2 4 12</pre><p>ada tiga <em>nested scope </em>yang saling berkaitan pada code diatas, untuk lebih jelasnya bisa dilihat pada gambar dibawah.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*l3o2TvDSiEgcpvF9vJIVcQ.png" /></figure><p><strong>Bubble 1</strong> merupakan <em>global scope, </em>dan hanya memiliki 1 <em>identifier </em>didalamnya <strong>foo<br>Bubble 2 </strong>merupakan scope dari <strong>foo. </strong>yang didalamnya memiliki 3 <em>identifier </em>yaitu <strong>a, bar, </strong>dan <strong>b.<br>Bubble 3 </strong>merupakan <em>scope </em>dari <strong>bar, </strong>dan memilik 1 <em>identifier </em><strong>c.</strong></p><h3>Look-ups</h3><p>Pada contoh diatas, <em>Engine </em>mengeksekusi <em>statement </em><strong>console.log(..) </strong>dan kemudian mencari 3 reverensi variabel yaitu <strong>a,b, </strong>dan <strong>c</strong>. Eksekusi contoh diatas dimulai dari <em>scope bubble </em>terdalam, <em>scope </em>dari <strong>bar(..)</strong>. Didalam scope tersebut tidak terdapat variabel <strong>a</strong>, jadi <em>engine </em>akan naik satu level keluar <em>scope </em><strong>bar(..) </strong>mencari <em>scope bubble</em> terdekat yaitu <em>scope </em>dari <strong><em>foo(..)</em></strong><em>. Engine </em>menemukan variabel <strong>a </strong>dan menggunakannya. Hal sama terjadi pada variabel <strong>b</strong>. Untuk variabel <strong>c</strong>, variabel ditemukan didalam <em>scope </em><strong>bar(…)</strong>.</p><p><strong><em>Scope look-up</em> berhenti ketika mendapatkan apa yang dicari</strong>. Identifier dengan nama yang sama dapat ditulis kembali pada bermacam <em>layer </em>dari <em>nested scope</em>, hal ini disebut <em>shadowing</em></p><p>Global variable secara otomatis merupakan property dari global object (dalam hal ini <strong>window</strong>), jadi memungkinkan untuk mereferensikan sebuah <em>global variable </em>tidak secara langsung dengan nama <em>lexical </em>nya, tetapi hanya dengan referensi property dari <em>global object.</em></p><pre>window.a</pre><p>Teknik ini memberikan akses pada <em>global variable </em>yang biasanya tidak dapat diakses ketika terkena <em>shadowing.</em></p><p>Tak peduli dimana sebuah fungsi dipanggil atau bagaimana fungsi tersebut dipanggil, <em>lexcical scope </em>dari fungsi tersebut hanya akan didefinisikan dimana fungsi tersebut dideklarasikan.</p><h3>Cheating Lexical</h3><p>Jika <em>lexical scope </em>hanya didefiniskan pada saat fungsi tersebut dideklarasikan. Dapatkah kita memodifikasi sebuah <em>lexical scope </em>pada saat <em>run-time</em> ? Javascript mempunyai 2 buah mekanisme untuk memodifikasi <em>lexical scope</em>. Tetapi perlu diketahui bahwa 2 mekanisme ini merupakan <em>bad practice</em> pada code anda. Karena akan membuat <em>performance </em>code kita menjadi buruk. Adapun metode yang digunakan adalah <strong>eval </strong>dan <strong>with</strong>.</p><p><strong>eval<br></strong>Fungsi <strong>eval(…) </strong>javascript membutuhkan sebuah <em>string </em>sebagai sebuah argument dan memerlakukan string tersebut sebagai sebuah <em>code</em>. Mari kita lihat contoh code dibawah</p><pre>function foo(str, a) {<br>	eval( str ); // cheating!<br>	console.log( a, b );<br>}<br><br>var b = 2;<br><br>foo( &quot;var b = 3;&quot;, 1 ); // 1 3</pre><p>String var b = 3 diperlakukan sebagai sebuah <em>code </em>oleh eval(..). Karena code tersebut maka dideklarasikannlah variabel baru b. Hal tersebut merubah lexical scope yang sudah ada dari foo(..). Tetapi apabila kita lihat <em>code </em>diatas membuat variabel b didalam foo(..) yang merupaka <em>shadow</em> dari variable b yang dideklarasikan pada scope luar (global).</p><p>Ketika console.log(..) dipanggil, terdapat variabel a dan b didalam scope foo(..) sehingga tidak mencari di scope luar sehingga akan menampilkan “1 3” dibanding “1 2”.</p><p><strong>with<br></strong>Cara lain untuk merubah <em>lexical scope</em> adalah dengan <em>keyword </em><em>with</em>(<em>deprecated</em>). with merupakan cara cepat untuk membuat beberapa <em>property references </em>dari sebuah object <strong>tanpa </strong>mengulangi mereferensikan object tersebut. sebagai contoh</p><pre>var obj = {<br>	a: 1,<br>	b: 2,<br>	c: 3<br>};<br><br>// more &quot;tedious&quot; to repeat &quot;obj&quot;<br>obj.a = 2;<br>obj.b = 3;<br>obj.c = 4;<br><br>// &quot;easier&quot; short-hand<br>with (obj) {<br>	a = 3;<br>	b = 4;<br>	c = 5;<br>}</pre><p>contoh lain</p><pre>function foo(obj) {<br>	with (obj) {<br>		a = 2;<br>	}<br>}<br><br>var o1 = {<br>	a: 3<br>};<br><br>var o2 = {<br>	b: 3<br>};<br><br>foo( o1 );<br>console.log( o1.a ); // 2<br><br>foo( o2 );<br>console.log( o2.a ); // undefined<br>console.log( a ); // 2 -- Oops, leaked global!</pre><p>Pada contoh diatas terdapat dua object o1 dan o2. satu mempunyai property a, dan satu lagi tidak. Fungsi foo(..) mempunyai sebuah <em>object reference</em> obj sebagai sebuah argument, dan memanggil<em>with (obj) {..}. </em>Didalam block with kita meng-<em>assign </em>a = 2.</p><p>Ketika kita <em>pass </em>o1, <em>assignment </em><em>a=2 </em>menemukan property o1.a dan <em>assign </em>nilai 2. Tetapi ketika kita <em>pass </em>o2 kita tidak menemukan property o2.a sehingga akan menghasilkan undefined.</p><p>Tetapi ada satu hal yang aneh, ketika console.log(a) akan menghasilkan 2. Kenapa ini bisa terjadi. with <em>statement </em>memerlukan sebuah <em>object</em> yang mempunyai properties sebanyak nol atau lebih, dan memperlakukan object tersebut sebagai sebuah <em>lexical scope </em>yang berbeda dan properties dari object tersebut akan diperlakukan sebagai <em>lexical identifier</em> pada <em>scope </em>tersebut. Jadi ketika a = 2 dieksekusi akan menghasilkan variabel a pada global scope.</p><p><strong>performance<br></strong>Kedua metode eval(..) dan with mengubah <em>lexical scope</em> yang ada dengan membuat <em>lexical scope </em>baru pada saat <em>runtime</em>.<br>Jadi apa masalahnya? bukankah itu membuat <em>code </em>kita menjadi lebih <em>flexibel</em>. Jawabannya adalah <strong>tidak</strong>.<br>Javascript <em>engine</em> memiliki banyak <em>performance optimizations</em> yang terjadi ketika fase <em>compilation</em>. Namun ketika <em>engine</em> menemukan eval(..) atau with dalam code, <em>engine </em>akan mengasumsikan bahwa location <em>identifier </em>tersebut <strong>invalid</strong>, karena <em>engine</em> tidak mengetahui code apa yang kita berikan kepada eval(..) pada saat <em>lexing time </em>untuk merubah <em>lexical scope. </em>Dengan kata lain banyak optimisasi javascript yang tidak terjadi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=765801059e07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Scope (What is Scope?)]]></title>
            <link>https://medium.com/@ridwanfansuri/javascript-scope-what-is-scope-c16ea0c45d11?source=rss-92efd285f2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c16ea0c45d11</guid>
            <category><![CDATA[javascript-fundamental]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[ridwanf]]></dc:creator>
            <pubDate>Wed, 03 Jul 2019 13:50:45 GMT</pubDate>
            <atom:updated>2019-07-03T13:50:45.590Z</atom:updated>
            <content:encoded><![CDATA[<p>Sumber <a href="https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch1.md">https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch1.md</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6a6LKrd0tc-QugCOucvKw.png" /></figure><h3><strong>Apa itu Scope?</strong></h3><p>Salah satu hal yang paling mendasar dari banyak bahasa pemrograman adalah kemampuan menyimpan value dalam variable, lalu megambil atau merubah value tersebut. Kemampuan untuk menyimpan value atau -mengambil value biasa disebut dengan <em>state</em>. Ada banyak pertanyaan tentang dimana variable-variable tersebut hidup atau dimana mereka disimpan. Dan yang terpenting bagaimana program menemukan mereka ketika dibutuhkan. Pertanyaan tersebut ada karena dibutuhkannya <em>well-defined rules </em>untuk menyimpan variable di beberapa lokasi, dan menemukannya ketika dibutuhkan. Aturan-aturan tersebut disebut dengan <em>Scope. </em>Tetapi dimana dan bagaimana aturan-aturan dalam Scope dibuat?</p><h3><strong>Compiler Theory</strong></h3><p>Banyak orang menyangka bahwa Javascript adalah <em>dynamic </em>atau <em>interpreted language</em>, tetapi faktanya javascript merupakan <em>compiled </em>language, memang tidak seperti <em>traditional compiled language </em>lainnya. Tetapi javascript <em>engine </em>menampilkan langkah-langkah yang sama seperti <em>compiled language </em>yang tradisional.</p><p>Pada proses <em>compiled-language</em> yang tradisional, suatu bagian dari <em>source code </em>akan melewati tiga langkah sebelum <em>code </em>tersebut dieksekusi atau biasa disebut “<em>compilation</em>”, yaitu:</p><ol><li><strong>Tokenizing/Lexing</strong>: memecah suatu string kedalam bagian-bagian yang disebut dengan <strong>token</strong>. Sebagai contoh pada <em>code</em> <strong>var a = 2</strong> akan dipecah menjadi <strong>var</strong>, <strong>a</strong>, <strong>=,</strong> <strong>2 </strong>dan<strong> ;. </strong>Spasi tidak dihitung.</li><li><strong>Parsing: </strong>memroses sebuah kumpulan <em>token</em> dan merubahnya kedalam elemen <em>nested tree </em>yang menggambarkan struktur dari program. <em>Tree </em>ini disebut dengan “AST” ( <em>Abstract Syntax Tree</em>) (<a href="https://medium.com/basecs/leveling-up-ones-parsing-game-with-asts-d7a6fc2400ff">tulisan tentang AST</a>.)<br> <em>Tree</em> untuk <strong>var a =2</strong> dimulai dari <em>top-level node </em>yang disebut <strong><em>VariableDeclaration, </em></strong>dengan <em>child node </em>yang disebut <strong><em>Identifier </em></strong>(dimana <em>value</em> nya adalah <strong>a</strong>), dan <em>child node</em> lain yang disebut <strong><em>AssignmentExpression </em></strong>dan mempunyai <em>child node </em>nya sendiri yang disebut <strong><em>NumericLiteral </em></strong>(yang <em>value-</em>nya adalah 2).</li><li><strong>Code-Generation: </strong>Proses merubah AST menjadi <em>executable code. </em>Bagian ini sangat bergantung pada bahasa pemrograman dan <em>platform </em>yang digunakan.</li></ol><h3><strong>Understanding Scope</strong></h3><p>Cara untuk mempelajari scope dengan membayangkan proses tersebut sebagai sebuah percakapan. tetapi siapakah yang melakukan percakapan ini?</p><h3><strong>The Cast</strong></h3><p>Mari kita bertemu dengan pelaku yang memroses program <strong>var a = 2</strong>, jadi kita akan mengerti percakapan yang terjadi:</p><ol><li><em>Engine</em>: bertanggung jawab pada saat mulai hingga selesai proses compile dan eksekusi dari program javascript yang kita buat.</li><li><em>Compiler</em>: salah satu teman dari <em>Engine, </em>melakukan semua pekerjaan kotor seperti <em>parsing</em> dana <em>code-generation.</em></li><li><em>Scope</em>: teman lain dari <em>Engine</em>: mengumpulkan dan me-<em>maintain </em>kumpulan dari semua <em>variable </em>yang dideklarasikan dan menerapkan aturan-aturan .</li></ol><h3><strong>Back &amp; Forth</strong></h3><p>Ketika kita melihat program <strong>var a = 2; </strong>kita seringkali berpikir bahwa itu adalah satu <em>statement. </em>Tetapi temen baru kita yang bernama <em>Engine</em> tidak meilhatnya seperti itu. <em>Engine </em>meliatnya sebagai 2 buah <em>statement </em>yang berbeda, satu ketika <em>Compiler </em>akan meng-<em>handle </em>saat <em>compilation</em>, dan satu lagi ketika <em>Engine </em>men-<em>handle </em>saat eksekusi.</p><p>Jadi mari kita uraikan bagaimana <em>Engine </em>dan kawan-kawan memroses program <strong>var a = 2;</strong></p><p>Hal pertama yang <em>Compiler </em>lakukan pada program ini adalah melakukan <em>lexing </em>untuk menguraikan program tersebut menjadi token-token, yang kemudian akan dirubah menjadi sebuah <em>tree</em>. Tetapi ketika <em>Compiler </em>mendapatkan sebuah <em>code </em>yang telah digenerate,Terkadang <em>Compiler </em>akan memperlakukan program tersebut berbeda dari apa yang telah diasumsikan</p><p>Asumsi yang masuk akal adalah <em>Compiler </em>akan membuat <em>code </em>berdasarkan dari <em>pseudo-code </em>ini: “Mengalokasikan <em>memory </em>untuk sebuah <em>variable </em>dan beri nama <em>a</em>. Kemudian memasukan nilai 2 kedalam <em>variable </em>tersebut. Tetapi sayang sekali hal ini tidak seluruhnya akurat.</p><p><em>Compiler </em>akan melakukan proses seperti ini:</p><ol><li>Ketika mendapatkan <strong>var a</strong>, <em>Compiler </em>akan bertanya pada <em>Scope </em>apakah terdapat <em>variable </em><strong>a </strong>didalam <em>scope </em>tesebut. Apabila ada <em>compiler </em>akan mengabaikan declarasi tersebut dan melanjutkan proses. Apabila tidak ada <em>compiler </em>akan meminta <em>scope </em>untuk membuat sebuat variable baru bernama <strong>a </strong>didalam <em>scope </em>tersebut.</li><li>Kemudian <em>compiler </em>akan membuat <em>code </em>untuk dieksekusi oleh <em>engine </em>untuk meng-<em>handle proses </em><strong>a = 2</strong>.<strong> </strong>Ketika proses dimulai <em>code </em>pada <em>engine </em>akan bertanya pada <em>scope </em>apakah ada variable <strong>a </strong>yang bisa diakses pada <em>scope </em>tersebut. Apabila ada, <em>Engine </em>akan menggunakan <em>variable </em>tersebut. Apabila tidak, <em>Engine </em>akan mencari ditempat lain. Apabila <em>engine </em>menemukan <em>variable </em>tersebut, <em>engine akan </em>meng-<em>assign </em>nilai 2 pada <em>variable tersebut. </em>Apabila tidak menemukan <em>engine </em>akan mengeluarkan <em>error.</em></li></ol><h3><strong>Nested Scope</strong></h3><p>Seperti yang kita bilang, <em>Scope </em>adalah aturan-aturan dalam mencari <em>variable </em>berdasarkan nama <em>identifier-</em>nya. Sama seperti <em>block </em>atau fungsi yang bisa terdapat dalam <em>block, scope </em>juga bisa ada didalam <em>scope </em>lainnya. Jadi, ketika sebuah <em>variable </em>tidak bisa ditemukan didalam sebuah <em>scope</em>. <em>Engine </em>akan berkonsultasi kepada <em>scope </em>selanjutnya diluar dari <em>scope </em>sebelumnya hingga ke <em>scope </em>terluar (<em>global scope</em>) atau sampai <em>variable </em>itu ditemukan.</p><pre>function foo(a) {<br>	console.log( a + b );<br>}<br><br>var b = 2;<br><br>foo( 2 ); // 4</pre><p>pada contoh diatas sebuah RHS (<em>right hand side</em>) untuk <strong>b </strong>tidak ditemukan didalam fungsi <strong>foo</strong>. Tetapi variable tersebut dapat ditemukan di scope yang mengelilinganya dalam contoh diatas berupa <em>global scope</em>. Penjelasan sederhananya adalah <em>Engine </em>mulai pada <em>current excecuting scope </em>mencari variable disana, apabila tidak ada, <em>engine </em>akan mencari scope diatasnya hingga ke global <em>scope.</em></p><h3>Kesimpulan</h3><p>Scope adalah kumpulan aturan-aturan yang menetukan dimana dan bagaimana sebuah variable bisa ditemukan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c16ea0c45d11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Fundamental (part 2)]]></title>
            <link>https://medium.com/@ridwanfansuri/javascript-fundamental-part-2-ec177eb8977f?source=rss-92efd285f2e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec177eb8977f</guid>
            <category><![CDATA[javascript-fundamental]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[ridwanf]]></dc:creator>
            <pubDate>Wed, 12 Jun 2019 14:34:46 GMT</pubDate>
            <atom:updated>2019-06-12T14:36:54.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*A9FEV2lIDUDo7WqJ9x1FPA.png" /></figure><p>Part 1: <a href="https://medium.com/@ridwanfansuri/javascript-fundamental-a3e129e0928c">https://medium.com/@ridwanfansuri/javascript-fundamental-a3e129e0928c</a></p><p>Oke mari kita lanjutkan tulisan tentang javascriptnya. Setelah di blog pertama telah dijabarkan statement, operator &amp; type kita akan melanjutkan pembahasan tentang javascript fundamental.</p><p><strong>Coercion<br></strong>Apa itu coercion. coercion adalah merubah suatu type dari sebuah value kedalam type lainnya seperti dari <strong>string </strong>menjadi <strong>number </strong>atau biasa disebut dengan <strong>convertion</strong>. <strong>Coercion </strong>dibagi menjadi 2, yaitu <strong>explicit </strong>dan <strong>implicit</strong>. Explicit coercion adalah dimana kita bisa melihat dengan jelas dalam code proses konversi dari satu type ke type lainnya. Sedangkan dalam implicit coercion kita tidak melihat atau menyadari bahwa terjadi konversi type pada suatu code.</p><pre>// contoh explicit coercion<br>var a = &quot;42&quot;;<br><br>var b = Number( a );<br><br>a;				// &quot;42&quot;<br>b;				// 42 -- the number!</pre><pre>// contoh implicit coercion<br>var a = &quot;42&quot;;<br><br>var b = a * 1;	// &quot;42&quot; implicitly coerced to 42 here<br><br>a;				// &quot;42&quot;<br>b;				// 42 -- the number!</pre><p><strong>Truthy &amp; Falsy<br></strong>Truthy &amp; Falsy terjadi ketika no-boolean value mengalami coercion ke boolean. <br>Contoh untuk “falsy” sebagai berikut:<br>- “” (empty string)<br>- 0, -0, NaN (invalid number)<br>- null, undefined<br>- false<br>Semua value yang tidak masuk dalam “falsy” merupakan “truthy”. Contoh untuk “truthy” sebagai berikut:<br>- “hello”<br>- 42<br>- true<br>- [], [1, “2”, 3] (array)<br>- {}, {a: 42} (object)<br>- function foo() {…} (functions)</p><p><strong>Equality<br></strong>Ada 4 equality operator dalam javascript yaitu <strong>==</strong>, <strong>===</strong>, <strong>!=</strong> dan <strong>!==. </strong>Perbedaan antara == dan === ya kita ketahui adalah bahwa == membandingkan value saja, sedangkan === membandingkan value dan type nya. Ini tidak sepenuhnya benar. == membandingkan value dengan coercion sedangkan === membanding value tanpa coercion biasa disebut “<em>strict equality”</em> . contoh dari equality</p><pre>var a = &quot;42&quot;;<br>var b = 42;<br><br>a == b;			// true<br>a === b;		// false</pre><p>Pada perbandingan <strong>a == b, </strong>JS melihat bahwa type kedua variable tidak sama, kemudian variable tersebut akan mengalami konversi hingga mempunyai type yg sama. Lalu karena mengalami konversi manakah yg benar pada a==b, 42==42 ataukah “42”==”42&quot; ? yang benar adalah “42” menjadi 42 sehingga perbandingannya menjadi 42==42. Untuk lebih jelas tentang comparison dua type yang berbeda bisa dibaca disini <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3">http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3</a></p><p>Pada a===b menghasilkan false, karena tidak diperkenankan melakukan coercion.</p><p><strong>Inequality</strong><br>Operator &lt;, &gt;, &lt;= dan &gt;= digunakan untuk inequality. Biasanya inequality digunakan pada number seperti 3 &lt; 4, tetapi pada javascript string pun dapat kita lakukan proses inequality menggunakan aturan alphabetic contohnya: <strong>“bar” &lt; “foo”</strong>. Lalu bagaimana dengan coercion pada inequality? pada inequality mempunya aturan yang sama seperti “==” tetapi tidak terdapat <strong>strinct inequality</strong>. Sebagai contoh</p><pre><strong>Contoh 1</strong><br>var a = 41;<br>var b = &quot;42&quot;;<br>var c = &quot;43&quot;;<br><br>a &lt; b;		// true<br>b &lt; c;		// true</pre><pre><strong>Contoh 2</strong><br>var a = 42;<br>var b = &quot;foo&quot;;<br><br>a &lt; b;		// false<br>a &gt; b;		// false<br>a == b;		// false</pre><p>Pada contoh 1 diatas pada a&lt;b, value b akan di convert menjadi number, sedangkan pada b&lt;c karena type kedua value sama yaitu string maka yang terjadi adalah alphabetical comparation. Sedangkan pada contoh ke 2 nilai b akan di convert menjadi number, tetapi hasil dari conversi tersebut adalah NaN sehingga hasil dari comparation nya menjadi false semua.</p><p><strong>Strict Mode<br></strong>Pada ES5 terdapat “strict mode” yang menambahkan aturan yang ketat pada code. Hal ini bertujuan agar code yang kita buat menjadi lebih aman dan lebih mengikuti aturan-aturan yang dipakai. Kita dapat menggunakan strict mode pada sebuah fungsi atau keselurhan file javascript, seperti contoh dibawah.</p><p>Strict mode pada sebuah fungsi</p><pre>function foo() {<br>	&quot;use strict&quot;;<br><br>	// this code is strict mode<br><br>	function bar() {<br>		// this code is strict mode<br>	}<br>}<br><br>// this code is not strict mode</pre><p>Strict mode pada file</p><pre>&quot;use strict&quot;;<br><br>function foo() {<br>	// this code is strict mode<br><br>	function bar() {<br>		// this code is strict mode<br>	}<br>}<br><br>// this code is strict mode</pre><p>Ketika kita menggunakan strict mode dan mendapatkan error maka program yang kita buat tidak akan berjalan, hal ini kadang menjengkelkan tetapi sangat bermanfaat karena code yang kita buat akan lebih bersih.</p><p><strong>Function As Values<br></strong>Pada javascript kita bisa memperlakukan function sebagai sebuah value, jadi kita bisa assign sebuah function ke sebuah variable seperti contoh dibawah</p><pre>var x = function bar(){<br>	// ..<br>};</pre><p><strong>Immediately Invoked Function Expressions (IIFEs)<br></strong>Pada contoh-contoh diatas untuk mengeksekusi sebuah function yang kita menuliskan foo() atau x() pada code kita. Ada cara lain dalam eksekusi sebuah function yaitu dengan IIFE. Contoh IIFE</p><pre>(function IIFE(){<br>	console.log( &quot;Hello!&quot; );<br>})();<br>// &quot;Hello!&quot;</pre><p>Pada contoh diatas terdapat satu pasang kurung setelah function IIFE <strong>(), </strong>sepasang kurung inilah yang mengeksekusi fungsi IIFE sebelumnya. Mungkin masih terasa asing bagi kita semua. Untuk lebih jelas bisa dilihat pada contoh dibawah</p><pre>function foo() { .. }<br><br>// `foo` function reference expression,<br>// then `()` executes it<br>foo();<br><br>// `IIFE` function expression,<br>// then `()` executes it<br>(function IIFE(){ .. })();</pre><p>pada contoh diatas fungsi pertama merupaan penjabaran dari fungsi kedua, kita membuat fungsi foo dan langsung mengeksekusinya.</p><p><strong>Closure</strong><br>Closure adalah fungsi yang me-return fungsi. Sebagai contoh</p><pre>function makeAdder(x) {<br>	// parameter `x` is an inner variable<br><br>	// inner function `add()` uses `x`, so<br>	// it has a &quot;closure&quot; over it<br>	function add(y) {<br>		return y + x;<br>	};<br><br>	return add;<br>}</pre><pre>// `plusOne` gets a reference to the inner `add(..)`<br>// function with closure over the `x` parameter of<br>// the outer `makeAdder(..)`<br>var plusOne = makeAdder( 1 );<br><br>// `plusTen` gets a reference to the inner `add(..)`<br>// function with closure over the `x` parameter of<br>// the outer `makeAdder(..)`<br>var plusTen = makeAdder( 10 );<br><br>plusOne( 3 );		// 4  &lt;-- 1 + 3<br>plusOne( 41 );		// 42 &lt;-- 1 + 41<br><br>plusTen( 13 );		// 23 &lt;-- 10 + 13</pre><p><strong>Modules<br></strong>Biasanya closure digunakan pada module pattern. Pada modules kita dapat mendefinisikan private implementasi seperti variable atau function yang kita sembunyikan dari dunia luar. Seperti</p><pre>function User(){<br>	var username, password;<br><br>	function doLogin(user,pw) {<br>		username = user;<br>		password = pw;<br><br>		// do the rest of the login work<br>	}<br><br>	var publicAPI = {<br>		login: doLogin<br>	};<br><br>	return publicAPI;<br>}<br><br>// create a `User` module instance<br>var fred = User();<br><br>fred.login( &quot;fred&quot;, &quot;12Battery34!&quot; );</pre><p>Fungsi User dipakai sebagai outer scope yang memiliki variable username dan password, lalu terdapat fungsi doLogin() yang tidak dapat diakses dari dunia luar.</p><p><strong><em>this</em> Indentifier<br></strong>Banyak yang mengira bahwa keyword <strong><em>this </em></strong>pada javascript mengacu pada object-oriented pattern. Ini merupakan sebuah kesalahpahama konsep, pada javascript penggunaan <strong><em>this</em></strong> berbeda dengan <strong><em>this</em></strong> pada OOP. Apabila sebuah fungsi mempunyai keyword <strong><em>this, </em></strong>itu merujuk pada sebuah object. Tetapi object mana yang dimaksud tergantung bagiamana fungsi tersebut dipanggil. Hal yang penting untuk diketahui adalah <strong><em>this</em></strong> tidak merujuk pada fungsi tersebut. Sebagai contoh</p><pre>function foo() {<br>	console.log( this.bar );<br>}<br><br>var bar = &quot;global&quot;;<br><br>var obj1 = {<br>	bar: &quot;obj1&quot;,<br>	foo: foo<br>};<br><br>var obj2 = {<br>	bar: &quot;obj2&quot;<br>};<br><br>// --------<br><br>foo();				// &quot;global&quot;<br>obj1.foo();			// &quot;obj1&quot;<br>foo.call( obj2 );		// &quot;obj2&quot;<br>new foo();			// undefined</pre><p>ada 4 aturan bagaimana <strong><em>this </em></strong>diperlakukan, dan hal tersebut ditampilkan pada 4 baris terakhir pada contoh diatas<br>1. <strong>foo()</strong> pada non-strict mode akan merujuk pada global object, sedangkan di strict mode akan menghasilkan <strong>undefined </strong>karena <strong><em>this </em></strong>didalam <strong>foo </strong>merujuk kepada object didalam function <strong>foo()<br></strong>2.<strong> obj1.foo() </strong>set <strong><em>this</em></strong> pada object <strong>obj1<br></strong>3. <strong>foo.call(obj2) </strong>set <strong><em>this</em></strong> pada object <strong>obj2 , </strong><a href="https://www.w3schools.com/js/js_function_call.asp">https://www.w3schools.com/js/js_function_call.asp</a><br>4. <strong>new foo()</strong> set <strong><em>this</em></strong> pada<strong> new empty object</strong> sehingga menghasilkan undefined</p><p>Mungkin cukup sekian untuk blog part ke 2. nantikan lanjutannya.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec177eb8977f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>