<?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 Riva Yudha on Medium]]></title>
        <description><![CDATA[Stories by Riva Yudha on Medium]]></description>
        <link>https://medium.com/@rvyw?source=rss-faac47880b00------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PTkD2KwinOot0USof5RcsQ.png</url>
            <title>Stories by Riva Yudha on Medium</title>
            <link>https://medium.com/@rvyw?source=rss-faac47880b00------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:14:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rvyw/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[Psychological Masterclass on Instagram Story’s 24-hour Illusion]]></title>
            <link>https://medium.com/@rvyw/psychological-masterclass-on-instagram-storys-24-hour-illusion-f459fd73e367?source=rss-faac47880b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/f459fd73e367</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[instagram]]></category>
            <dc:creator><![CDATA[Riva Yudha]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 03:03:10 GMT</pubDate>
            <atom:updated>2026-01-29T03:05:38.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghbRCW3ZloFfjeOxW8rolw@2x.jpeg" /><figcaption>STORAGE by <a href="https://www.instagram.com/aronyigin/?hl=de">Aron Yigin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You’re tapping through Instagram Stories and you start wondering about the sheer scale of it all. At first glance, the logic seems obvious: Instagram deletes Stories after 24 hours to save on bandwidth and storage costs. It feels like an automated “garbage collection” cycle designed to keep the servers from drowning in a sheer amount of daily video uploads.</p><p>But then, you realize that’s not how it works theoritically. You realize that if you save a Story to your Highlights, it stays there forever. If you check your Archive, every “disappeared” moment from three years ago is still preserved.</p><p>Suddenly, the realization hits: storage isn’t the constraint. Meta—the tech giant—definitely has the resources to keep every single video you’ve ever uploaded. So, if they aren’t deleting them to save space, why build a “disappearing” feature at all?</p><p>From a software engineering and product architecture perspective, the 24-hour timer is a masterclass in psychological design disguised as a technical limitation.</p><h4>Soft vs Hard Delete</h4><p>In a standard database, when you delete something, it’s a hard delete, the row is gone. However, Instagram uses a soft delete logic driven by a Visibility State.</p><p>When the 24-hour timer expires, the server doesn’t run a DELETE command. Instead, it updates a status flag in the metadata.</p><ul><li><strong>The Public Feed</strong>: The API only queries for stories where createdAt &gt; 24h</li><li><strong>Private Archive</strong>: The content remains indexed and searchable, but only for the owner’s User ID.</li></ul><p>The “disappearance” is purely an access-control layer. By promising that the content will go away, they lower the “social capital” cost of posting, encouraging users to upload raw, unedited content they would never put on their permanent Grid.</p><h4>Tiered Storage Architecture</h4><p>Even though storage is “cheap” for a giant like Meta, it isn’t free. The 24-hour limit allows them to implement an efficient Tiered Storage Strategy:</p><ul><li><strong>Hot Storage (First 24 Hours)</strong>: When a Story is live, it’s stored on high-performance SSDs and cached across global Content Delivery Networks (CDNs). This ensures that when you tap a friend’s bubble, the video plays instantly with zero latency.</li><li><strong>Cold Storage (Post-24 Hours)</strong>: Once the Story “expires,” the traffic to that file drops by 99%. The system automatically migrates the file to “Cold Storage” — slower and cheaper disk arrays.</li></ul><p>They don’t need to delete your data; they just need to move it to the “basement” where it doesn’t cost them a premium space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hk80QsgmXRc8g_psfkdWw.png" /><figcaption>The journey of the Story’s data</figcaption></figure><h4>The Goldmine</h4><p>From a systems design standpoint, the 24-hour window is a Product Requirement that dictates the user behavior.</p><p>If content is permanent, there’s no rush to check the app. If content is ephemeral, the user is conditioned to open the app at least once a day to “catch up.” This creates a consistent, predictable load on their servers, and — more importantly — a daily habit for the user.</p><p>From a data engineering perspective, a Story is more than just a video file; it’s a goldmine of interaction signals. Even if a Story “disappears” for your followers, Instagram keeps the data on:</p><ul><li>Who watched it and for how long?</li><li>At what point did people tap away?</li><li>Who did you “Close Friend” it to?</li></ul><p>This data is permanent. It’s used to train the recommendation algorithms that decide what you see on your Explore page. Deleting the actual video file would be a waste of the context needed to understand those interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*_UMtMEafiukFjIK4.jpg" /><figcaption>Instagram Story</figcaption></figure><p>The Instagram Story is a brilliant bit of social engineering. They convinced us to provide more data by promising that the data would “go away,” all while simply moving that data from an expensive server to a cheaper one.</p><p>The 24-hour timer isn’t a solution for a lack of storage — it’s a solution for a lack of user engagement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f459fd73e367" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What You Need to Know About WebGL and WebGPU as a Frontend Engineer]]></title>
            <link>https://medium.com/@rvyw/what-you-need-to-know-about-webgl-and-webgpu-as-a-frontend-engineer-fff345e8cbd9?source=rss-faac47880b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/fff345e8cbd9</guid>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[webgpu]]></category>
            <category><![CDATA[webgl]]></category>
            <dc:creator><![CDATA[Riva Yudha]]></dc:creator>
            <pubDate>Fri, 09 Jan 2026 08:56:31 GMT</pubDate>
            <atom:updated>2026-01-09T08:56:31.697Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wGXcxqZI1dQ_ntFM" /><figcaption>Photo by <a href="https://unsplash.com/@faded_gallery?utm_source=medium&amp;utm_medium=referral">Faded_Gallery</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re a frontend engineer getting into 3D on the web — perhaps tinkering with <strong>React Three Fiber (R3F)</strong> or <strong>Spline</strong> — you’ve likely felt a shift. You’re no longer just shifting divs around using CSS transform; you&#39;re wrestling with meshes, materials, lights, and cameras.</p><p>Suddenly, terms like “draw calls,” “vertices,” and “shaders” start appearing in documentation. And hanging over all of it is the ominous, magical concept of the <strong>GPU</strong>.</p><p>When you build a standard React app, you rarely think about the hardware it runs on. The browser abstracts it away. But in the 3D world, that abstraction gets thinner. Understanding the dance between the <strong>CPU</strong> and the <strong>GPU</strong> is the difference between a buttery-smooth 60fps experience and a janky, battery-draining disaster.</p><p>Let’s demystify what’s happening under the hood of R3F, WebGL, and the upcoming WebGPU.</p><p>To understand why 3D requires a different approach, we need to understand the two pieces of silicon running your computer.</p><h3>1. The CPU (Central Processing Unit)</h3><p>The CPU is the brain of your computer. It’s incredibly smart, flexible, and fast at handling complex, sequential logic.</p><p>As a frontend dev, this is your home turf. When your React code runs diffing algorithms, processes API data, or handles complex form validation, the CPU is doing the heavy lifting.</p><p><strong>The Problem with the CPU:</strong> It only has a few hands (cores) — usually between 4 and 16. If you ask it to calculate the color and position of 2 million pixels for a 3D model, it has to process them roughly one by one. It will choke, and your site will freeze.</p><h3>2. The GPU (Graphics Processing Unit)</h3><p>The GPU is a different beast entirely. It is not smart. It cannot run your operating system or handle complex if/elseJavaScript logic efficiently.</p><p>But what it lacks in intelligence, it makes up for in raw, brute-force parallelism. A modern GPU has <strong>thousands</strong> of tiny cores.</p><p>When it’s time to render a 3D frame, the GPU doesn’t do it pixel-by-pixel. It assigns every single pixel on the screen to one of its thousands of tiny cores and says, <em>“Everyone, calculate your color right now.”</em></p><p>They all finish simultaneously, instantly.</p><figure><img alt="CPU vs GPU" src="https://cdn-images-1.medium.com/max/457/1*eJyZeK9BT0lWRBgh5foV_Q.png" /></figure><h3>VRAM</h3><p>There is a third critical player that often gets overlooked: <strong>Video RAM (VRAM)</strong>.</p><p>Your computer has regular RAM, which the CPU uses. The GPU has its <em>own</em> dedicated, ultra-fast memory sitting right next to it — that’s VRAM.</p><p>When you load a .glb model in R3F, the following happens:</p><ol><li>Your browser downloads the file.</li><li>The CPU unpacks the geometry (shapes) and textures (images).</li><li>The CPU ships all that data across the motherboard and parks it in the <strong>VRAM</strong>.</li></ol><p>Once that data is in VRAM, the GPU can access it instantly without bothering the CPU. This separation is vital. If the GPU had to constantly ask the CPU for data from regular RAM every frame, the bottleneck would be enormous.</p><h3>How R3F (Three.js), WebGL, and WebGPU Fit In</h3><p>So, you’re writing React code. How does that end up talking to a graphics card?</p><p>Think of <strong>WebGL</strong> (and its successor, <strong>WebGPU</strong>) as the translators. They are standardized APIs that allow JavaScript to send specific commands to the graphics hardware.</p><p><strong>React Three Fiber (R3F)</strong> is the brilliant manager that handles the translation for you.</p><p>Let’s say you have a 3D cube in R3F that rotates when the user scrolls.</p><p>When the component mounts, R3F takes your &lt;mesh&gt; and &lt;boxGeometry&gt;, translates them into WebGL buffers, and uploads that data to the <strong>VRAM</strong>. The cube is now &quot;living&quot; on the graphics card.</p><ol><li><strong>CPU (JavaScript Main Thread):</strong> The browser detects a scroll event. Your R3F useFrame loop runs. It calculates a single number: the new rotation angle (e.g., rotation.y = 1.57).</li><li><strong>The Command:</strong> The CPU sends a tiny message via WebGL to the GPU: “Hey, remember that cube object? Update its Y-rotation matrix to 1.57.”</li><li><strong>GPU (The Heavy Lifting):</strong> The GPU takes that one instruction and instantly recalculates the positions of the thousands of vertices that make up the cube and redraws the millions of pixels needed to show it in its new orientation.</li></ol><h3>Why This Matters to You</h3><p>Understanding this architecture isn’t just academic trivia; it changes how you build.</p><figure><img alt="GPU acceleration" src="https://cdn-images-1.medium.com/max/1024/1*m8mbnFymUoOzK3V-ScI1Nw.jpeg" /></figure><h3>1. Unblocking the Main Thread</h3><p>This is the biggest benefit. Because the GPU is busy drawing the millions of pixels of your cool 3D hero section, the <strong>CPU’s main thread is free</strong>.</p><p>In a standard HTML/CSS animation, complex visual effects can hog the CPU, causing jank when the user tries to click a button or type in an input field. In a GPU-accelerated R3F site, your inputs remain snappy even while complex 3D is spinning in the background.</p><h3>2. The “Draw Call” Bottleneck</h3><p>Knowing that the CPU and GPU have to “chat” helps you avoid common pitfalls. Every time the CPU has to tell the GPU to draw something different, it’s called a “Draw Call.”</p><p>If your designer gives you a robot model made of 5,000 separate tiny mesh pieces, your CPU has to send 5,000 separate commands every single frame. The GPU spends more time listening to instructions than actually drawing.</p><p><strong>The fix:</strong> Knowing this, you ask your 3D artist to “merge” those meshes into one object, resulting in 1 draw call instead of 5,000.</p><h3>3. WebGPU: The Future is Now</h3><p>You asked about WebGPU. WebGL is based on older technology (OpenGL). It works well, but there is still a fair amount of “overhead” chatter between CPU and GPU.</p><p><strong>WebGPU</strong> is a modern redesign of that communication layer designed to match how modern GPUs (Vulkan, Metal, DirectX 12) actually work. It drastically reduces the CPU’s workload in talking to the GPU, allowing for many more objects and more complex simulations (like particles) than WebGL ever could.</p><p>Because the GPU handles the math, you can have a website with a massive 3D hero element that <strong>doesn’t slow down the rest of the page.</strong> While the GPU is busy spinning the 3D model, the CPU is completely free to handle your text animations, form validations, and API calls.</p><figure><img alt="WebGPU architechture" src="https://cdn-images-1.medium.com/max/800/0*_A2Mrar0gOXkx6bS" /></figure><h3>Conclusion</h3><p>Stepping into 3D on the web means stepping into a world where hardware dictates performance. By understanding that the CPU is your logical manager and the GPU is your parallel powerhouse, you can structure your R3F applications to let each do what it does best — resulting in experiences that feel impossibly smooth on the web.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fff345e8cbd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Catching Error: A Better Way to Handle JavaScript Failures]]></title>
            <link>https://medium.com/@rvyw/stop-catching-error-a-better-way-to-handle-javascript-failures-0accc50357ff?source=rss-faac47880b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/0accc50357ff</guid>
            <category><![CDATA[error-boundaries]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Riva Yudha]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 15:24:14 GMT</pubDate>
            <atom:updated>2026-01-01T15:24:14.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zayxs2zeyWhwzCRs" /><figcaption>Photo by <a href="https://unsplash.com/@etiennegirardet?utm_source=medium&amp;utm_medium=referral">Etienne Girardet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s be honest. When you are rushing to meet a deadline, error handling is often the first thing thrown overboard. We wrap a volatile block of code in a try/catch, log the error to the console, whisper a quick prayer to the server gods, and push it to production.</p><p>Then comes the dreaded 2 AM alert: “White Screen of Death reported by users.” You look at your logs and see 5,000 entries of Error: Cannot read property &#39;x&#39; of undefined. Helpful.</p><p>Robust applications aren’t applications that <em>never</em> crash; they are applications that fail gracefully, inform the user, and provide actionable logs for developers.</p><p>In this post, we are going to move past the basic try/catch block. We will explore architecting errors with purpose, avoiding rookie mistakes, handling failures in React, and leveraging TypeScript to make stability a compile-time feature.</p><h3>The Philosophy: Not All Errors Are Created Equal</h3><p>Before we write code, we need to understand what we are dealing with. In JavaScript application development, errors generally fall into two categories:</p><ol><li><strong>Operational Errors (Expected):</strong> These are run-of-the-mill things that happen in a real system. The network is down, the user input is invalid, the API sent back a 404. These aren’t “bugs”; they are states your app must handle gracefully.</li><li><strong>Programmer Errors (Bugs):</strong> You tried to read a property of null, you mistyped a variable name, you have infinite recursion. The best way to handle these is to let them crash locally so you can fix them, or catch them at the highest level in production so the whole app doesn&#39;t white-screen.</li></ol><p>Our primary focus for robust error handling is managing <strong>Operational Errors</strong> intelligently.</p><h3>Differentiating Errors: The Power of Custom Classes</h3><p>A common beginner habit is relying on the generic Error object for everything.</p><pre>// The beginner way<br>async function getUser(id) {<br>  const response = await fetch(`/api/users/${id}`);<br>  if (response.status === 404) {<br>    throw new Error(&quot;User not found&quot;);<br>  }<br>  if (response.status === 500) {<br>    throw new Error(&quot;Server down&quot;);<br>  }<br>  // ...<br>}<br><br>try {<br>  await getUser(123);<br>} catch (e) {<br>  // Now what? We have to parse the string message. Fragile!<br>  if (e.message.includes(&quot;not found&quot;)) {<br>     // show 404 state<br>  }<br>}</pre><p>Relying on string comparison to determine what went wrong is brittle. If you change the error message later, your handling logic breaks.</p><h4>Best Practice: Extend the Error Class</h4><p>Instead of string messages, use JavaScript’s class inheritance to create semantically meaningful errors. This allows you to differentiate errors using instanceof.</p><pre>// Define custom error types<br>class DatabaseError extends Error {<br>  constructor(message) {<br>    super(message);<br>    this.name = &quot;DatabaseError&quot;;<br>  }<br>}<br><br>class NetworkError extends Error {<br>  constructor(message, statusCode) {<br>    super(message);<br>    this.name = &quot;NetworkError&quot;;<br>    this.statusCode = statusCode; // We can attach custom data!<br>  }<br>}<br><br>class ValidationError extends Error {<br>  constructor(message, invalidFields) {<br>    super(message);<br>    this.name = &quot;ValidationError&quot;;<br>    this.invalidFields = invalidFields;<br>  }<br>}</pre><p>Now, your usage becomes cleaner and far more robust:</p><pre>async function robustGetUser(id) {<br>  // Imagine some validation logic...<br>  if (id &lt; 0) {<br>    throw new ValidationError(&quot;ID cannot be negative&quot;, { id: &quot;Must be positive&quot; });<br>  }<br><br>  try {<br>    const response = await fetch(`/api/users/${id}`);<br>    if (!response.ok) {<br>      // Pass custom data along with the error type<br>      throw new NetworkError(&quot;API request failed&quot;, response.status);<br>    }<br>  } catch (e) {<br>    // Rethrow custom errors, maybe wrap low-level fetch errors in DatabaseError<br>    if (e instanceof NetworkError || e instanceof ValidationError) {<br>        throw e;<br>    }<br>    // If fetch itself throws (offline), convert it<br>    throw new DatabaseError(&quot;Could not connect to user data source.&quot;);<br>  }<br>}</pre><h4>Handling the Differentiated Errors</h4><p>When you finally catch these errors up the chain (perhaps in a UI component controller), you know exactly what to do without guessing:</p><pre>try {<br>  await robustGetUser(-5);<br>} catch (error) {<br>  if (error instanceof ValidationError) {<br>    console.warn(&quot;User bad input:&quot;, error.invalidFields);<br>    // Show inline form validation messages<br>  } else if (error instanceof NetworkError) {<br>    if (error.statusCode === 401) {<br>      // Redirect to login<br>    } else {<br>      // Show generic &quot;service temporarily unavailable&quot; toast<br>    }<br>  } else if (error instanceof DatabaseError) {<br>    // Log critical failure to monitoring service (e.g., Sentry/Datadog)<br>    logToMonitoring(error);<br>    // Show &quot;Oops something went wrong&quot; screen<br>  } else {<br>    // The catch-all for unknown programmer errors<br>    console.error(&quot;CRITICAL UNKNOWN ERROR&quot;, error);<br>    // Let it crash or show fatal error boundary<br>  }<br>}</pre><h3>Common Pitfalls Beginners Fall Into</h3><h4>1. The “Silent Killer” (Swallowing Errors)</h4><pre>try {<br>  someCriticalOperation();<br>} catch (e) {<br>  console.log(&quot;It failed.&quot;);<br>  // Proceed as if nothing happened...<br>}</pre><p><strong>Why it’s bad:</strong> Your application is now in an inconsistent state. Data might be corrupted, but the UI thinks everything is fine. The user will eventually run into a weirder bug down the road that is impossible to debug. <strong>Never catch an error unless you plan to handle it or re-throw it.</strong></p><h4>Instead of “Swallowing Errors” → Use Graceful Degradation</h4><p>When an error occurs, the goal isn’t just to “not crash”; it’s to provide a functional alternative.</p><ul><li><strong>The Pro-Pattern:</strong> If a non-critical feature fails (like a “Recommended Products” widget), catch the error and return an empty array or a cached version of the data.</li><li><strong>Why it works:</strong> The user can still complete their primary goal (buying the main product) even if the secondary feature is down.</li></ul><pre>async function getRecommendedProducts() {<br>  try {<br>    return await api.fetch(&#39;/recommendations&#39;);<br>  } catch (error) {<br>    console.error(&quot;Recommendations failed:&quot;, error);<br>    return []; // Return a safe &quot;fallback&quot; value so the UI doesn&#39;t break<br>  }<br>}</pre><h4>2. Throwing Strings</h4><pre>if (!data) {<br>  throw &quot;Data is missing!&quot;; // DON&#39;T DO THIS<br>}</pre><p><strong>Why it’s bad:</strong> Strings are not Error objects. They do not have stack traces. When this lands in your logging system, you will have absolutely no idea <em>where</em> in your code this happened. Always throw new Error() or a custom subclass.</p><h4>Instead of “Throwing Strings” → Use Error Factories or Enums</h4><p>Beginners throw strings because it’s fast. Pros use structured objects because they are searchable and consistent.</p><ul><li><strong>The Pro-Pattern:</strong> Create an ErrorCode enum and an Error Factory.</li><li><strong>Why it works:</strong> It prevents typos in error handling. If you use ErrorCode.NOT_FOUND, your IDE will autocomplete it, and TypeScript will catch it if you misspell it.</li></ul><pre>enum ErrorCode {<br>  NOT_FOUND = &#39;ENTITY_NOT_FOUND&#39;,<br>  UNAUTHORIZED = &#39;USER_UNAUTHORIZED&#39;,<br>  VALIDATION_FAILED = &#39;VALIDATION_FAILED&#39;<br>}<br><br>class AppError extends Error {<br>  constructor(public code: ErrorCode, message: string) {<br>    super(message);<br>  }<br>}<br><br>// Usage<br>throw new AppError(ErrorCode.NOT_FOUND, &quot;User profile missing&quot;);</pre><h4>3. Overusing try/catch</h4><pre>// Function 1<br>async function getProductData(id) {<br>  try {<br>    return await api.fetch(`/products/${id}`);<br>  } catch (err) {<br>    console.error(&quot;Fetch failed&quot;, err);<br>    throw err; // Why catch it just to throw it again?<br>  }<br>}<br><br>// Function 2<br>async function formatPrice(id) {<br>  try {<br>    const product = await getProductData(id);<br>    return `$${product.price.toFixed(2)}`;<br>  } catch (err) {<br>    console.error(&quot;Formatting failed&quot;, err);<br>    throw err; // Still just passing the hot potato<br>  }<br>}<br><br>// Function 3 (The UI Component)<br>async function ProductDisplay({ id }) {<br>  try {<br>    const price = await formatPrice(id);<br>    render(price);<br>  } catch (err) {<br>    showErrorMessage(&quot;Something went wrong&quot;); // FINALLY, we do something.<br>  }<br>}</pre><p>Wrapping every single 3-line function in try/catch makes code unreadable and slow. Only use try/catch in places where you can actually perform a recovery action or need to transform a lower-level error into a higher-level custom error (as seen in the robustGetUser example above).</p><h4>Instead of “Overusing Try/Catch” → Use The “Top-Level Wrapper” Pattern</h4><p>Wrapping every line in try/catch creates &quot;Pyramid of Doom&quot; code.</p><ul><li><strong>The Pro-Pattern:</strong> Let errors bubble up. Handle them at a strategic “choke point” — like a global middleware in Express or a single high-level controller in a frontend app.</li><li><strong>Why it works:</strong> Your business logic remains clean and readable. You only handle the error once at the level where you can actually <em>do</em> something about it (like showing a specific UI).</li></ul><pre>// 1. Lower-level: Pure logic, no try/catch.<br>// If it fails, it fails. That&#39;s okay!<br>async function getProductData(id) {<br>  const response = await api.fetch(`/products/${id}`);<br>  if (!response.ok) throw new NetworkError(&quot;Product not found&quot;, 404);<br>  return response.json();<br>}<br><br>// 2. Mid-level: Still pure logic.<br>// This function stays clean and readable.<br>async function formatPrice(id) {<br>  const product = await getProductData(id);<br>  return `$${product.price.toFixed(2)}`;<br>}<br><br>// 3. Top-level (The &quot;Choke Point&quot;).<br>// This is the ONLY place that needs to handle the fallout.<br>async function ProductPage({ id }) {<br>  try {<br>    const price = await formatPrice(id);<br>    setPrice(price);<br>  } catch (error) {<br>    // We handle EVERY error from the functions above right here.<br>    if (error instanceof NetworkError &amp;&amp; error.statusCode === 404) {<br>      setUiState(&quot;show_not_found_illustration&quot;);<br>    } else {<br>      setUiState(&quot;show_generic_error_toast&quot;);<br>      logToSentry(error); // Critical tracking happens here<br>    }<br>  }<br>}</pre><h3>Error Handling in React Apps</h3><p>React introduces a different paradigm because rendering happens synchronously, but data fetching is asynchronous.</p><h4>1. The Error Boundary (For Rendering Errors)</h4><p>If your JavaScript crashes during the rendering phase (e.g., accessing user.address.street when user is null), React unmounts the whole component tree, resulting in the White Screen of Death.</p><p>Error Boundaries are class components designed to catch errors in their child component tree and display a fallback UI.</p><p><em>Note: As of React 19, there is still no Hooks equivalent for Error Boundaries; you must use a class component.</em></p><pre>class ErrorBoundary extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { hasError: false };<br>  }<br><br>  static getDerivedStateFromError(error) {<br>    // Update state so the next render will show the fallback UI.<br>    return { hasError: true };<br>  }<br><br>  componentDidCatch(error, errorInfo) {<br>    // Log the error to an error reporting service<br>    logErrorToService(error, errorInfo);<br>  }<br><br>  render() {<br>    if (this.state.hasError) {<br>      return &lt;h1&gt;Something went wrong. Please refresh.&lt;/h1&gt;;<br>    }<br><br>    return this.props.children;<br>  }<br>}<br><br>// Usage in App.js<br>&lt;ErrorBoundary&gt;<br>  &lt;MyDangerousWidget /&gt;<br>&lt;/ErrorBoundary&gt;</pre><h4>2. Async Errors in React (Hooks)</h4><p>Error Boundaries <strong>do not</strong> catch errors inside event handlers (like an onClick) or asynchronous code (like fetch inside useEffect).</p><p>For these, you still need standard try/catch blocks that update React state to reflect the failure.</p><pre>function UserProfile({ userId }) {<br>  const [user, setUser] = useState(null);<br>  const [errorState, setErrorState] = useState({ hasError: false, message: &#39;&#39; });<br><br>  useEffect(() =&gt; {<br>    async function fetchData() {<br>      try {<br>        // Reset error state before new fetch<br>        setErrorState({ hasError: false, message: &#39;&#39; });<br>        const data = await fetchUser(userId); // Assume this throws our Custom Errors<br>        setUser(data);<br>      } catch (e) {<br>        // Handle specific error types to determine UI message<br>        if (e instanceof NetworkError &amp;&amp; e.statusCode === 404) {<br>           setErrorState({ hasError: true, message: &#39;User not found.&#39; });<br>        } else {<br>           setErrorState({ hasError: true, message: &#39;Sorry, could not load profile.&#39; });<br>        }<br>      }<br>    }<br>    fetchData();<br>  }, [userId]);<br><br>  if (errorState.hasError) {<br>    return &lt;div className=&quot;error-banner&quot;&gt;{errorState.message}&lt;/div&gt;;<br>  }<br>  // ... render user ...<br>}</pre><h3>Enter TypeScript: Making Failures Manageable</h3><p>If you aren’t using TypeScript yet, error handling is one of the best arguments for adopting it.</p><p>In standard JavaScript, a catch(e) block receives e as an any type. You have no guarantees about what it is.</p><h4>TypeScript’s unknown Error Type</h4><p>Modern TypeScript treats caught error objects as unknown by default (if you have useUnknownInCatchVariables enabled in tsconfig, which you should). This forces you to verify the type before accessing properties like .message.</p><p>This pairs perfectly with our Custom Error classes using <strong>Type Guards</strong>.</p><pre>// Define our custom error again in TS<br>class NetworkError extends Error {<br>  readonly name = &quot;NetworkError&quot;; // &#39;readonly&#39; aids type narrowing<br>  constructor(public message: string, public statusCode: number) {<br>    super(message);<br>  }<br>}<br><br>async function doRiskyThing(): Promise&lt;string&gt; {<br>    // Imagine this throws a NetworkError<br>    throw new NetworkError(&quot;Gateway timeout&quot;, 504);<br>}<br><br>async function main() {<br>  try {<br>    const result = await doRiskyThing();<br>    console.log(result);<br>  } catch (error: unknown) { // TypeScript forces this to be unknown<br>    // Compiler error! &#39;error&#39; is of type &#39;unknown&#39;.<br>    // console.log(error.message); <br><br>    // We must use a type guard to narrow it down<br>    if (error instanceof NetworkError) {<br>      // TypeScript now knows &#39;error&#39; is NetworkError<br>      console.error(`Network Failure ${error.statusCode}: ${error.message}`);<br>    } else if (error instanceof Error) {<br>      // TypeScript knows it&#39;s at least a standard Error<br>      console.error(&quot;General error:&quot;, error.message);<br>    } else {<br>      // It could be a string, a number, or null (someone threw badly)<br>      console.error(&quot;An unexpected non-error object was thrown:&quot;, error);<br>    }<br>  }<br>}</pre><p>By combining TypeScript’s unknown constraint with instanceof checks on your custom error classes, you create a system where you cannot accidentally mishandle an error object. The compiler forces you to deal with the possibilities explicitly.</p><h3>Conclusion</h3><p>Moving from “console.logging errors” to having an error handling strategy is a major step toward engineering maturity.</p><p>Don’t just catch errors to stop the crashing. Catch errors to categorize them using Custom Error classes. Handle known operational errors gracefully in the UI, and let genuine bugs trigger global handlers that alert your team.</p><p>Your users might not notice when your error handling is good, but they will certainly notice when it isn’t.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0accc50357ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Closures? Apaan, tuh? — Alasan Kamu Benci Javascript]]></title>
            <link>https://medium.com/@rvyw/closures-apaan-tuh-alasan-kamu-benci-javascript-8484a3437a40?source=rss-faac47880b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/8484a3437a40</guid>
            <category><![CDATA[bahasa-indonesia]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Riva Yudha]]></dc:creator>
            <pubDate>Thu, 15 Mar 2018 20:25:21 GMT</pubDate>
            <atom:updated>2018-03-17T07:19:44.886Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4co4Y746HGdpl6bl." /><figcaption>Layer di dalam layer di dalam layer di dalam layer — by <a href="https://unsplash.com/@jsclick?utm_source=medium&amp;utm_medium=referral">Jamie Saw</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Beberapa tahun lalu, pas saya (akhirnya) dipanggil untuk <em>interview </em>di sebuah perusahaan teknologi lumayan ternama di Jakarta, saya seneng bukan kepalang. Apalagi, kali ini adalah <em>interview </em>untuk posisi <em>front-end developer </em>— posisi yang emang merupakan <em>passion </em>saya dari pertama kali kenal <em>web development</em> dan dunia <em>programming</em>.</p><p>Malam hari nya, saya berkutat dengan beberapa latihan tentang bagaimana cara membangun <em>interface </em>dinamis dengan Javascript, manipulasi DOM, cara nge-<em>get value form</em>, dan beberapa hal keren lainnya. Semua saya lakuin supaya saya lebih ngerasa akrab lagi dengan Javascript, dan berharap bisa melalui proses <em>interview </em>keesokan harinya dengan lempeng.</p><p><em>Well</em>, hari itu pun tiba. Saya nyampe di kantor nya, duduk dengan tenang, dan masuk ke ruangan <em>interview </em>ketika nama saya dipanggil. Ada 3 orang yang duduk di depan saya. Mereka tersenyum ramah ke saya, bikin saya jadi tambah rileks. Tapi, saya agak kaget ketika saya diberitau nggak perlu ngeluarin <em>laptop</em>. Karena saya pikir saya akan dites untuk membuat <em>website </em>atau bahkan <em>mini-app</em> di situ. Ternyata dugaan saya salah besar. Saya disuruh maju ke depan, di mana di situ ada papan tulis kosong. Saya disuruh ambil spidol, dan mendengarkan 1 buah pertanyaan mereka, yang di mana jawaban yang akan saya lontarkan (dan yang saya tuliskan) kemudian, akan menentukan apakah saya diterima apa nggak, di kantor mereka. Dan pertanyaan mereka adalah:</p><blockquote>Jelaskan apa itu <strong>closures </strong>dalam Javascript. Dan tulis salah satu sample working code tentang bagaimana <strong>closures </strong>bekerja.</blockquote><p>Dunia langsung serasa berputar. Nggak tau kenapa, kayaknya hari itu, detik itu, Jakarta gempa lagi. Tapi, saya juga nggak terlalu pasti. <em>Damn</em>! Pertanyaan mereka terdengar <em>simple</em>. Dan bahkan cara mereka ngomong juga terdengar enteng. Tapi, kenapa kok saya berasa kayak lagi diterpa badai Katrina di tengah-tengah lapangan <em>baseball</em>, di mana saya diharuskan tetap kokoh berdiri.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3rgizw2rXU4HJwL7BL%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3rgizw2rXU4HJwL7BL%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3rgizw2rXU4HJwL7BL%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d9aa835e1eef363f555470ef3157335/href">https://medium.com/media/3d9aa835e1eef363f555470ef3157335/href</a></iframe><p>Faktanya, saya memang harus tetap kuat berdiri, meskipun saya nggak bisa — atau nggak tau — sama sekali apa yang mereka tanyain.</p><p><em>Closures</em>? Ini <em>interview </em>Javascript kan?</p><p>Setau saya, Javascript itu kan cuma masalah <em>if else statement. </em>Atau paling juga <em>toggle element visible-invisible. </em>Atau<em> </em>paling klik <em>element </em>ini, mainin <em>event </em>ini. Klik <em>element </em>itu, mainin <em>event </em>itu. Atau paling banter juga <em>form submit</em> — bikin <em>form</em>, trus simpen data nya di <em>local storage</em>. Atau bahkan paling bikin <em>modal </em>pake Bootstrap sama jQuery — diduetin biar kayak penyanyi dangdut. Paling cuma itu aja, kan? Saya tadi malem udah belajar cara ngebangun <em>web-app </em>yang keren dengan cepat, loh! Saya tadi malem udah belajar cara bikin <em>accordion </em>pake jQuery dengan cuma 7 baris kode, loh! Kenapa nggak kalian tanya itu aja, coba?</p><p>Tapi, <em>closures</em>? Saya bener-bener nggak tau apaan itu. Bahkan baru tau ada istilah itu setelah denger langsung dari mulut para <em>interviewers</em> itu. Akhirnya, singkat cerita, saya melenggang meninggalkan ruangan itu — dan papan tulis nya — dengan lemas. Dan seperti yang bisa ditebak selanjutnya, saya dibiarin begitu aja dengan teganya menunggu dering hape atau notif <em>email </em>di <em>inbox </em>yang tak kunjung datang.</p><p>Ya, saya gagal. Hanya karena satu pertanyaan, saya gagal. Oh, bahkan mungkin kalo mau dirinci, saya gagal hanya karena satu kata — <em>closures</em>.</p><h3>Fundamental Javascript</h3><p>Oke, karena pengalaman berharga (sekaligus ngenes) itu, saya langsung berniat memperdalam segala fundamental dalam Javascript. Saya lupain semua <em>hype </em>tentang kehebatan dan kecanggihan React, <em>simple </em>nya Vue, atau ribet-tapi-keren nya Webpack, saya lupain semua. Saya kembali ke <em>basic</em>. Saya perdalam Javascript mulai dari akar-akar nya, mulai dari dasar lagi.</p><p>Dan pada akhirnya pun saya nyadar, bahwa emang seperti itu lah seorang <em>programmer </em>(terutama <em>programmer </em>Javascript) seharusnya bertindak. Faktanya, banyak <em>programmer</em> yang ngeluh betapa susah nya React, betapa ribet nya Angular, atau betapa <em>non-sense</em> nya Webpack, semata-mata karena mereka langsung “nekat” terjun ke sana, tanpa melewati <em>basic understanding</em> dari Javascript — yang mana (<em>as you might guess</em>) merupakan inti dari semua itu. <em>Simple</em>, kan?</p><p>React, Angular, Vue, dan kawan-kawan itu <em>tentative</em>. Hari ini mereka dipuji, dipake, dan dielu-eluin, tapi apa kamu yakin 2020 atau 2022 mereka masih bakal bersinar? Jangan lupain kasus nya jQuery akhir-akhir ini.</p><p>Tapi di lain sisi, Javascript akan selalu ada — dan akan selalu eksis.</p><p>Tau darimana lu, Va, Javascript bakal selalu eksis? Sotoy lu.</p><p><em>Well</em>, memang nggak ada yang pasti di dunia ini. Tapi, jangan lupain bahwa Javascript adalah <em>mother language</em> nya dunia <em>world wide web</em>. Selama <em>web</em> masih ada di dunia ini, kamu bakal selalu berurusan dengan Javascript. Mau nggak mau. Suka nggak suka. Terima nggak terima. <em>That’s the fact.</em></p><p>Dan dengan kamu kuasain Javascript sepenuhnya, kemungkinan besar kamu bakal bisa hidup di mana aja — dan kapan aja, karena ibaratnya, kamu udah megang<em> swiss knife</em> nya. <em>Please do take a note.</em></p><p>Maka dari itu lah, tulisan-tulisan yang saya tulis selama ini di sini, kebanyakan adalah tentang <em>basic </em>dari Javascript itu sendiri. Ini berguna buat kamu yang memang lagi mulai belajar atau sedang memperdalam Javascript sebagai bahasa pemrograman pegangan kamu. Semua konsep-konsep dasar bahasa pemrograman yang terkenal aneh ini, akan saya jabarin satu-satu sedetail mungkin yang saya mampu. Termasuk untuk konsep yang satu ini, <em>closures</em>.</p><h3>Apaan, tuh?</h3><p>Secara definisi, <em>closures </em>adalah <em>inner function</em> yang punya hak akses ke <em>scope </em>di dalam <em>function </em>di mana dia bernaung, dan <em>scope-scope</em> di <em>function </em>luar lain nya.</p><p>Oke, gampangnya untuk sekarang, mari kita <em>refer closures</em> sebagai <em>function </em>yang didefinisiin di dalam <em>function </em>lainnya. Meskipun, kompleks nya nggak sepenuhnya begitu, tapi karena udah hampir sepenuhnya benar, untuk sekarang kita anggap aja seperti itu, ya. Biar nggak keribetan.</p><p>Nah, <em>closures </em>ini<em> </em>bisa ngakses ke variabel-variabel yang ada di dalam <em>scope </em>yang berbeda:</p><ul><li>Variabel <strong>yang ada di dalam <em>scope </em>nya sendiri</strong> (ini udah jelas bisa lah ya);</li><li>Variabel <strong>yang ada di dalam <em>scope global</em></strong>;</li><li>Dan variabel <strong>yang ada di dalam <em>scope function</em> di luar nya</strong> / <em>parent function </em>nya.</li></ul><p>Dan hebatnya lagi, <em>closures </em>itu juga bisa ngakses ke:</p><ul><li>Parameter <strong>yang dia punya</strong> (ini udah jelas bisa lah, ya);</li><li>Parameter <strong>yang ada di dalam <em>function </em>di luar nya</strong> / <em>parent function</em> nya.</li></ul><p>Udah, udah! Terlalu teori. Males! Kita liat contoh nya aja langsung, yak. 😙</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJ5G9wGLmvfiOa4hb57Ctw.png" /><figcaption>Ini function ngeri yang bisa nebak umur yang selalu kamu sembunyi-sembunyikan</figcaption></figure><p>Di atas, ada <em>function </em>namanya yourUmur(), dan kalo diliat di dalemnya lagi, ada <em>function </em>lagi tuh yang namanya printUmur(). Nah, printUmur() ini lah yang disebut <em>closures</em>. Dan dia nggak cuma sekedar sebagai <em>inner function </em>aja. Kayak yang saya sebutin di atas, dia bisa ngakses variabel dan parameter-parameter di mana-mana aja.</p><p>Dan, untuk contoh ini, kalo kamu <em>run code</em> ini, maka bakal keluar <em>output </em>— seperti yang kamu tebak — 76. Ini karena <em>statement </em>console.log nya si printUmur() berhasil ngakses variabel yang ada di <em>outer scope</em> nya — atau <em>scope </em>yang berada di luar lingkup nya.</p><p>Dan ini adalah konsep dasar dari <em>closures</em>. Doi bakal berhak ngakses variabel maupun <em>parameter </em>yang tersedia, bahkan yang ada di luar dari <em>scope </em>dia sendiri.</p><p>Oke oke, iya tau, contoh <em>code </em>di atas nggak ngebantu banget dalam memahami <em>closures</em>.</p><p>Yaudah, sekarang liat <em>code </em>yang ini.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_cPC2eDKoT99X6zJaqECQ.png" /><figcaption>Gak usah bingung. Ini cuma console.log-console.log aja kok kerjanya.</figcaption></figure><p>Pada <em>code</em> di atas, kita bikin variabel global, trus kita bikin <em>function</em> utama / function luar yang punya satu <em>parameter</em>. Di dalam <em>function</em> itu, ada variabel1, dan kemudian ada <em>inner function</em> bernama functionInner() dengan satu <em>parameter</em> di dalamnya. Nah, <em>inner function</em> ini lah yang dinamakan <em>closure</em>. Dan dalam kasus ini, kita kasih doi banyak tugas — meskipun cuma sekedar console.log doang — di mana tugas-tugas nya itu adalah mencoba mengakses:</p><ol><li><strong>Variabel-variabel</strong> yang ada di dalam <em>scope </em>nya dan di luar <em>scope </em>nya;</li><li>Dan <strong>parameter-parameter</strong> yang ada di dalam <em>scope </em>nya dan yang ada di luar <em>scope </em>nya.</li></ol><p>Kemudian, si functionInner() langsung kita <em>invoke </em>di dalam <em>function </em>utama. Trus, di bagian luar, giliran functionOuter() deh yang kita <em>invoke</em>.</p><p>Kalo nggak ada konsep yang namanya <em>closures</em>, maka semua console.log itu pasti bakal berujung undefined. Tapi, karena <em>closures </em>itu beneran nyata di Javascript, coba kita lihat langsung hasilnya begitu di-<em>run</em>, ya.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeBuS1lQAwb8rkgFTOYuqg.png" /><figcaption>Oke, semua berhasil diakses sama si closure! Cool!</figcaption></figure><p>Yak! Semua yang pengen diakses sama si functionInner() ternyata beneran bisa terakses. Terbukti dengan <em>log </em>yang keluar benar-benar sesuai.</p><p>Maka, dengan ini kamu udah bisa bikin contoh <em>sample code </em>tentang <em>closures </em>yang <em>working </em>100%. Selamat! Di mana, ini adalah jawaban yang harusnya saya tulis di papan tulis pas <em>interview </em>tempo dulu itu. Iya bener, sekarang saya nyesel. Nyesel karena sebenernya konsep ini nggak susah-susah amat, tapi karena saya terlalu sibuk dengan urusan bagian Javacript yang <em>fancy-fancy </em>aja, jadi hilang, deh, kesempatan saya kerja di perusahaan lumayan <em>elite </em>itu.</p><p>Well, oke, lupain itu! Saatnya <em>move on! 👊 👊</em></p><p>Nah, sekarang, apa gunanya <em>closures </em>ini sebenernya, Va? Dalam<em> real-life app</em>, kenapa <em>closures </em>bisa sangat <em>powerful</em>?</p><p>Oke, bagus kalo kamu nanya gitu. Tapi, jujur, kalo saya jabarin semua di sini, bisa-bisa artikel ini bakal jadi 15 menit durasi ngebaca nya. Jadi, saya putuskan untuk bahas masalah begituannya di part selanjutnya ya. Untuk sekarang, saya pikir cukup lah.</p><p>Yang perlu kamu <em>take a note</em>, <em>closure </em>ini sering dikategoriin sebagai konsep <em>intermediate </em>di Javascript, bahkan beberapa ada yang mengklasifikasikan nya sebagai konsep <em>advanced</em>. Ironis nya, justru <em>closures </em>ini adalah konsep yang amat fundamental dalam Javascript. <em>Meaning</em>, kalo kamu <em>programmer </em>Javascript — baik <em>beginner </em>maupun di atas nya — kamu wajib, kudu, mesti, harus, <em>fardu ain</em>, tau dan paham luar dalem tentang konsep <em>closures</em> ini. Bingung? Iya, emang ngebingungin. Anggap gini aja deh: meskipun kamu (dan juga saya) masih tergolong <em>beginner </em>di dunia Javascript, tapi karena kita udah — sedikit banyak — tau tentang <em>closures </em>ini, boleh lah kita anggap diri kita ini <em>intermediate</em>. 🎃</p><p>Karena — ini nggak mengada-ngada — coba aja tanya senior-senior <em>engineer </em>kamu di kantor tentang konsep <em>closures </em>ini. Dijamin, jarang banget ada yang bisa ngasih penjelasan yang jelas dan <em>clear</em>.</p><blockquote>Ketika kamu nggak bisa menjelaskan sesuatu dengan jelas dan clear, maka kamu belum menguasai hal tersebut dengan baik. — Mario Balotelli</blockquote><p>Nggak. Bukan. Itu bukan perkataan Balotelli. Tapi, <em>at least</em>, perkataan itu bener ada nya.</p><p><em>Well</em>, sampai jumpa lagi di artikel-artikel tentang kebencian Javascript selanjutnya. <em>Byeeee</em>! 👦 👦</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8484a3437a40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jadi, Array itu Object? — Alasan Kamu Benci Javascript]]></title>
            <link>https://medium.com/@rvyw/jadi-array-itu-object-alasan-kamu-benci-javascript-8b79b5147896?source=rss-faac47880b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b79b5147896</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[array-methods]]></category>
            <category><![CDATA[javascript-library]]></category>
            <dc:creator><![CDATA[Riva Yudha]]></dc:creator>
            <pubDate>Wed, 07 Mar 2018 20:11:23 GMT</pubDate>
            <atom:updated>2018-03-08T04:26:07.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xCNnWgnKKdiff2TI." /><figcaption>“Array of People” by <a href="https://unsplash.com/@bill_bokeh?utm_source=medium&amp;utm_medium=referral">Paul Dufour</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Array </em>yang kamu kenal selama ini, itu adalah <em>object</em>. Tapi <em>object</em>, bukanlah <em>array</em>. <em>At least</em>, begitulah yang berlaku di dunia Javascript. Mantap? Mantap!</p><p>Pusing juga, tapi!</p><p>Iya, sama, pusing. Bukan Javascript namanya kalo nggak bikin pala muter dikit, alis <em>standing</em> sebelah, dahi mengernyit indah.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*ZK1xJqJoPKWsee7yO-ZnaA@2x.jpeg" /></figure><p>Tapi, yaa, itulah salah satu tugas artikel-artikel yang saya tulis ini. Kita bahas semua kejanggalan-kejanggalan Javascript, trus kita kupas, deh, satu per satu apa alasannya Javascipt bisa jadi orang yang begitu. Apa dia nggak ada niatan untuk jadi orang yang lebih baik? Kita harus caritau.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1Y2Sdgx96_tQKsLVrOImw.png" /></figure><p>Coba perhatikan <em>code </em>di atas. Kalo perlu kamu ikut nulis, dan <em>run</em>. Lihat apa hasil yang keluar?</p><p>Ha? Apa?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*MGWPxeM-CEbRPVTf9qy7Dw.png" /><figcaption>Kamu pasti sedang kidding me!</figcaption></figure><p>Sip! Benar sekali! Muncul output nya <strong><em>object </em></strong>untuk kedua buah <em>console.log()</em> itu. Untuk <em>line </em>pertama, di mana kita meng-console.log-kan {} (kurung kurawal / <em>curly braces</em>), output yang keluar adalah <em>object</em>, <em>which is makes sense</em>. Dan untuk <em>line </em>kedua, di mana kita meng-console.log-kan <em>array</em>, output yang keluar, ternyata adalah <em>object </em>juga.</p><p>Bukannya <em>array </em>sama <em>object </em>itu berbeda ya? Well, <em>array </em>dan <em>object </em>memang berbeda, tapi sejatinya mereka itu sama — sama-sama <em>object</em>. Yap, <em>array </em>adalah <em>object</em>. <em>A special kind of object, to be precise</em>.</p><p>Oke, supaya lebih pasti, kita liat contoh lainnya. Kali ini kita masukin <em>array</em> nya ke dalam variabel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuF0BR7J0P_lznDzworpTw.png" /><figcaption>Yak! Tetep object ternyata array manapun di bumi ini</figcaption></figure><h3>Nentuin Array adalah Array yang Sesungguhnya</h3><p>Tapi, apapun itu, jangan sampe bingung dulu lah, ya.</p><p>Lah, gimana nggak bingung, Va? Jadi kalo saya lagi ngoding dan pengen ngecek sebuah data <em>array </em>itu adalah beneran <em>array</em>, gimana dong caranya? Sementara, kalo kita cek, sepertinya semua <em>array </em>bakal terbaca sebagai <em>object </em>untuk tipe data nya.</p><p><em>Well</em>, iya sih, emang. Pertama mungkin bakal terlihat seperti jalan buntu, tapi ternyata gampang banget kok caranya buat ngecek apakah elemen ini beneran <em>array </em>atau bukan. Tulis aja pake <em>method </em>isArray().</p><pre>console.log(Array.isArray([]))</pre><pre>// true</pre><pre>console.log(Array.isArray({}))</pre><pre>// false</pre><p>Cara kedua, dengan menggunakan keyword instanceof, seperti ini.</p><pre>console.log([] instanceof Array)</pre><pre>// true<br></pre><pre>console.log({} instanceof Array)</pre><pre>//false</pre><p>Dan tolong diperhatiin, ya, cara penulisannya yang (emang) rada janggal.</p><p><em>Okay, cool</em>! Jadi, sekarang kamu udah bisa menentukan apakah elemen yang lagi kamu hadapin ini beneran array apa nggak.</p><p>Jadi, dengan kamu paham bahwa <em>array </em>itu sebenernya adalah <em>object</em>, adalah merupakan poin penting, dan bakal jadi <em>a big win </em>buat kamu pas lagi <em>interview</em>. Serius, konsep ini juga merupakan salah satu konsep yang paling sering ditanyain sang pewawancara. Biasanya, mereka suka, nih, sama pertanyaan-pertanyaaan mengecoh kayak gini. Jadi, pastikan aja dulu kamu nggak bakal terkecoh sama mereka. 🎃 🎃</p><p>Tapi, pengetahuan fundamental kayak gini bukan cuma bagus buat kamu <em>interview</em>, tapi yaa emang bagus juga untuk bekal kamu di dalam dunia <em>programming </em>secara <em>general</em>. Ngerti ama konsep kayak begini bakal menghemat waktu berharga kamu. Bayangin ketika kamu nggak ngerti, malah waktu kamu abis berjam-jam cuma buat nelusurin <em>bugs </em>(yang nggak perlu) aja.</p><h3>Bonus Tips</h3><p>Sementara <em>array </em>adalah <em>object</em>, kamu tau nggak kalo tipe data <em>null </em>itu juga <em>object</em>? Oh, dan ada satu lagi yang menarik. Liat <em>code </em>ini, nih.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*_DzjMSga7QCr8RI2yOhE2A.png" /><figcaption>Selamat datang di dunia Javascript</figcaption></figure><p>Yak! Makin gila dibuatnya! <em>Null </em>yang biasa menggambarkan keabsenan sebuah <em>value</em>, ternyata tipe data nya <em>object </em>juga. Sementara <em>undefined</em>, tipe data nya <em>undefined</em>. 🐆 🐆</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FWY4WNWUo0s3jW%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fmic-WY4WNWUo0s3jW&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FWY4WNWUo0s3jW%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/79c469d382be37e293e06f8d9c1b2fe9/href">https://medium.com/media/79c469d382be37e293e06f8d9c1b2fe9/href</a></iframe><p>Serah, deh, Javascript, seraaah! 👺 👺 Makin lama dibahas, malah makin aneh, lau.</p><p><em>Well</em>, tapi gapapa. Bertahan lah sebentar lagi. Baca artikel-artikel berikutnya dengan seksama, coba sendiri <em>code-code</em> yang ada, eksperimen dikit dengan <em>code-code</em> nya, dan niscaya kamu jadi cinta, deh, sama Javascript. Pffft…</p><p><em>Okay, see you! Byeee! 🚀</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b79b5147896" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bilangan Desimal yang Aneh — Alasan Kamu Benci Javascript]]></title>
            <link>https://medium.com/@rvyw/bilangan-desimal-yang-aneh-alasan-kamu-benci-javascript-5deaf05a212a?source=rss-faac47880b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/5deaf05a212a</guid>
            <category><![CDATA[bahasa-indonesia]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Riva Yudha]]></dc:creator>
            <pubDate>Mon, 05 Mar 2018 05:21:14 GMT</pubDate>
            <atom:updated>2018-03-17T09:29:13.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f9_hIWr0Z-d__b7q." /><figcaption>Ini floating hat, mas. bukan floating number! — Photo by <a href="https://unsplash.com/@sixstreetunder?utm_source=medium&amp;utm_medium=referral">Craig Whitehead</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Kamu bisa aja cinta sama Javascript, dan kamu mulai <em>build user interfaces </em>keren nan modern dengan menggunakan Javascript. Hasilnya? Betul-betul memuaskan! <em>Well</em>, nggak ada yang salah dengan itu. Nggak sama sekali. Bahkan dianjurkan, tuh, kamu bangun-bangun produk-produk keren. Sunnah hukumnya.</p><p>Tapi, artikel ini bukan tentang itu, sih. Artikel ini — dan artikel-artikel saya selanjutnya — bakal ngupas tentang keunikan-keunikan (kalo nggak mau dibilang keanehan) Javascript yang siap bikin kamu demam. Yah, bisa dibilang artikel ini kembali ke <em>basic </em>nya Javascript dulu. Alasan saya bikin artikel-artikel yang nunjukin “gejala-gejala” aneh dalam tubuh Javascript, nggak lain, supaya para <em>developer beginner </em>kayak saya ini bisa sedikit lebih <em>aware</em> (baca: mawas diri) dalam berhadapan langsung dengan Javascript ke depannya.</p><h3>Desimal dalam Javascript</h3><p>Kenapa, Va? Ada yang aneh sama bilangan desimal dalam Javascript?</p><blockquote>Kalo saya bilang ada, kamu mau percaya, nggak?</blockquote><p>Yaa, gak tau sih. Coba tunjukin aja dulu.</p><blockquote>Yasudin. Kita mulai aja, ya. Sekarang, saya punya <em>code </em>kayak gini.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wabt-ySZCpQ9l6g_efYNvQ.png" /><figcaption>Benar atau salah? Coba katakan sejujurnya.</figcaption></figure><p>Kurang <em>simple </em>apa coba? Nah, seperti biasa, tanpa kamu buka IDE atau DevTools manapun, coba jawab hanya dengan melihat: output nya <em>true </em>atau <em>false</em>? Saya kasih waktu 1 menit.</p><p>Udah?</p><p>Oke, kalo udah, apa jawabannya?</p><p>Yaudah, kita <em>reveal </em>sama-sama ya. Dan setelah di-<em>run</em>, hasilnya adalaaah…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*afS7ZxnZLHUse3Pxp_OZsw.png" /><figcaption>Yassalaaam! Ini for real, nih?</figcaption></figure><p><em>False</em>? Kok <em>false</em>? Apakah <em>false is the new true</em>? Sepertinya nggak. Ini beneran <em>false </em>sefalse-false nya. Yang artinya menunjukkan bahwa 300.3 nggak sama dengan 100.1 * 3. Seriusan? Kan 100.1 x 3 = 300.3, bukan?</p><p>Iya, bener. Nggak ada yang salah sama perkalian bilangan desimal kamu itu. Kamu bawa ke cerdas cermat tetep bakal dibenerin sama jurinya, kok. Tapi masalahnya <em>rule </em>ini nggak selamanya berlaku di dunia Javascript.</p><p>Seriusan, Va? Ah, kalo gitu gua jadi benci aja, deh, sama Javascript sekarang. Keribetan. Baru jadi bahasa aja udah belagu.</p><p>Yaah, jangan gitu juga, dong. Semua ini pasti ada sebab-musabab nya. Yaudah, kita bahas aja deh ya sekarang.</p><h3>Berawal dari IEEE 754…</h3><p>Ngomong apa lu, Va?</p><p>Ntar dulu, sebelum saya jelasin, saya cuma pengen bilang bahwa emang begitulah Javascript. Selama yang saya tau, kita nggak bakal pernah bisa selalu ngedapetin hasil yang akurat jika kita bermain-main dengan bilangan desimal di Javascript. Selalu ada kemungkinan hasilnya lari-lari dari ekspektasi — meskipun memang nggak semua.</p><p>Ini semua karena Javascript menganut standard <a href="https://en.wikipedia.org/wiki/IEEE_754"><strong>IEEE Standard for Floating-Point Arithmetic</strong></a>, atau <a href="https://en.wikipedia.org/wiki/IEEE_754">IEEE 754</a>, atau singkatnya adalah merupakan salah satu <em>standard </em>internasional dalam <em>binary encoded</em> untuk bilangan desimal untuk kebutuhan teknis <em>hardware </em>dan juga <em>software</em>. Meskipun <em>standard</em> internasional, tapi <em>standard </em>ini diketahui banyak kelemahannya, salah satu nya, yaa yang dialami sendiri sama Javascript, nggak bisa memberikan output bilangan desimal yang 100% presisi. Dalam prakteknya, banyak terjadi <em>slip </em>dalam penerjemahan bilangan desimal ini.</p><p>Ini sama seperti saat kamu bermain-main dengan pecahan 2/3. Pecahan 2/3 ini nggak bakal pernah bisa dikonversi ke bilangan desimal secara akurat 100%. Alih-alih ngasih output yang presisi, eh, pecahan ini malah punya output:</p><pre>2/3 = 0.6666666667</pre><p>Di mana doi akan nge-<em>render </em>banyak angka 6, dan terus begitu hingga akhirnya melakukan pembulatan kalo <em>memory </em>sistem yang menjalankannya udah mau <em>limit</em>.</p><p>Faktanya, kalo kamu iseng console.log(100.1 * 3), maka output yang keluar adalah:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*j6k2OqBRLwWgGWWeikyFSQ.png" /><figcaption>Malah aneh-aneh angka yang keluar. Au ah, JS. Bodo amat.</figcaption></figure><p>Kalo udah gini, ya pantes aja hasilnya bakal <em>return false</em>. Lha <em>wong </em>kita ternyata ngebandingin 2 bilangan yang jelas-jelas berbeda <em>value </em>nya. 🐨</p><h3>Solusi?</h3><p>Solusinya? Mau denger? Solusinya: jangan berurusan sama sekali dengan bilangan desimal. Udah. Titik.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxUA7bhxwKXf7kDKdcA%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fwomenshistorymonth-xUA7bhxwKXf7kDKdcA&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxUA7bhxwKXf7kDKdcA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/bba998a73aa2e49b770410b461a4cf30/href">https://medium.com/media/bba998a73aa2e49b770410b461a4cf30/href</a></iframe><p>Tapi, tapiiii, kalo emang kamu emang lagi di posisi yang nggak bisa ngindar sama sekali dari deru dan nestapa ini, <em>fortunately </em>Javascript nyediain beberapa caranya — meskipun rada ribet.</p><h3>1. toFixed</h3><p>Cara pertama, yang umum dilakuin adalah dengan make <em>built-in method </em>namanya toFixed(). <em>Method</em> ini bakal ngebuletin bilangan desimal yang banyak-banyak itu menjadi berapa angka di belakang koma, sesuai dengan parameter yang dia terima. Misal:</p><pre>(100.1 * 3).toFixed(1);</pre><pre>// Output: &quot;300.3”</pre><p>Nah di situ parameter nya kita taro 1, yang mana bakal <em>return </em>300.3. Tapi sayangnya, <em>method </em>toFixed ini bakal nge-<em>return </em>balik ke kita berupa <em>string, </em>bukan <em>integer. </em>Makanya, kalo kamu <em>compare </em>lagi dua bilangan awal kita — tetep pake === — maka hasilnya bakal tetep false.</p><p>Cara betulinnya, <em>wrap </em>aja mereka semua itu ke dalam <em>built-in method</em> lainnya bernama Number().</p><pre>Number( (100.1 * 3).toFixed(1) );</pre><pre>// Output: 300.3</pre><p>Kalo udah gitu, niscaya hasilnya bakal <em>integer</em>, dan kamu pada akhirnya berhasil nge-<em>compare </em>dengan bilangan desimal satunya tadi.</p><h3>2. Operator basic matematika</h3><p>Cara kedua, sebenernya rada <em>nyeleneh</em>, sih. Tapi yaa ini juga umum digunain. Caranya adalah memanfaatkan operator matematika <em>standard </em>dalam code Javascript kamu.</p><p>Pertama, bilangan desimal nya kamu x10.</p><pre>(100.1 * 10) * 3;</pre><pre>// Ini jadi sama dengan 1001 * 3</pre><p>Trus, semua bilangan itu kamu satuin, lalu bagi 10.</p><pre>((100.1 * 10) * 3) / 10;</pre><pre>// Output: 300.3</pre><p>Selesai! Yak, lumayan maksa, kan? Bodo amat. Yang penting kelar. 😌 😌</p><p>Gimana? Lumayan ganggu kan konsep Javascript yang ini? Kalo nggak sabar-sabar nyoba-nyoba, bisa-bisa kamu hilang kesadaran, trus akhirnya mulai ngomong sendiri. Serem.</p><p><em>At least</em>, saya udah beberin. Dan jangan lupain, bahwa konsep ini juga merupakan salah satu materi yang sering keluar di saat <em>interview </em>kerja untuk Javascript. <em>Now, it feels good to know earlier, doesn’t it</em>?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1KqunccpzZ1As%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fkamen-rider-black-1KqunccpzZ1As&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1KqunccpzZ1As%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="348" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f5cfa448a707d8bdf98bd809c73b033/href">https://medium.com/media/6f5cfa448a707d8bdf98bd809c73b033/href</a></iframe><p>Oke, sekarang kamu bisa tidur tenang. Tapi ada baiknya sebelum tidur, bantu tepukin tangan artikel saya ini ya kalo emang dirasa berfaedah. 👭 👭</p><p>Akhirnya, sampai jumpa di artikel-artikel kebencian Javascript berikutnya! <em>Byeee</em>! 🚀 🚀 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5deaf05a212a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Hoisting — Alasan Kamu Benci Javascript (Part II)]]></title>
            <link>https://medium.com/@rvyw/javascript-hoisting-alasan-kamu-benci-javascript-part-ii-93ed3220630d?source=rss-faac47880b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/93ed3220630d</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[bahasa-indonesia]]></category>
            <dc:creator><![CDATA[Riva Yudha]]></dc:creator>
            <pubDate>Sat, 03 Mar 2018 16:34:31 GMT</pubDate>
            <atom:updated>2018-03-04T02:30:48.835Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IxYrAFC40LwC2Y44." /><figcaption>Gambar yang nggak ada hubungannya dengan artikel ini by <a href="https://unsplash.com/@lopify?utm_source=medium&amp;utm_medium=referral">Alejandro Lopez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Artikel ini adalah seri lanjutan dari artikel sebelumnya: <a href="https://medium.com/@rivayudha/javascript-hoisting-alasan-kamu-benci-javascript-part-i-68d50ebf4c9a">Javascript Hoisting — Alasan Kamu Benci Javascript (Part I)</a></blockquote><h3>Refresher</h3><p>Di <a href="https://medium.com/@rivayudha/javascript-hoisting-alasan-kamu-benci-javascript-part-i-68d50ebf4c9a">artikel kemaren</a> kita ngebahas <em>global scope</em> dan <em>function scope</em> dalam <em>hoisting</em> Javascript. Biarpun kayaknya nggak terlalu mendalam, tapi lumayan lah. Tapi berhubung nggak terlalu mendalam, tampaknya kamu masih ada rasa benci sama Javascript, nih. Nah, maka dari itu, di Part II ini saya bakal dalemin lagi masalah <em>hoisting</em> dan masalah skap-skop skap-skop-an ini. Insya Allah. 😢</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGsSuSMXuj-hvM_rfIpOSA.png" /></figure><p>Sebagai <em>refresher</em>, coba perhatiin <em>code</em> berikut ini. Di sini, let nama = &quot;Rusmanto&quot; menerima console.log() masing-masing di atas dan di bawahnya. Dan ketika dijalankan, di console.log() pertama jelas akan <em>undefined</em>, dan di console.log() kedua, baru deh berhasil keluar output nya. Karena ini adalah <em>section</em> untuk <em>refresher</em>, akan saya jelaskan lagi bahwa itu terjadi karena di belakang layar, Javascript <em>interpreter</em> melakukan proses <em>hoisting</em>, seperti ini:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpejZ2Xw9SaiHH8wTmeLIw.png" /><figcaption>Proses hoisting oleh JS interpreter di belakang layar</figcaption></figure><p><em>That’s why</em> variabel nama nggak kedetect sama console.log() pertama. <em>Well</em>, konsep yang satu ini juga berlaku untuk <em>function</em>. Oke, mari tenggelam lagi ke dalam <em>function</em> <em>hoisting</em> dalam Javascipt.</p><h3>Function Hoisting</h3><p>Dalam Javascript ada 2 jenis <em>function</em> yang umum digunain: <em>function expression</em> dan <em>function declaration</em>. Coba liat beda nya di sini.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*o3c4sgoOAQQRE3yZMlnGDg.png" /><figcaption>Expression vs Declaration. Live malam ini di RCTV</figcaption></figure><p>Dua-duanya punya jabatan yang sama, yakni sama-sama sebagai <em>function</em> dalam Javascript. Tapi yang harus diperhatikan, mereka “bertingkah” agak beda dalam urusan <em>hoisting</em>.</p><p><em>Function expression</em> — yang mana selalu di-<em>assign</em> ke dalam variabel (boleh var, let, atau const) — akan bertindak sama dengan <em>behavior</em> variabel-variabel tersebut. Artinya, output <em>function expression</em> nggak bakal kebaca sama JS <em>interpreter</em> kalo mereka di-<em>invoke</em> sebelum dideklarasiin. Liat contohnya di sini:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhD4bfcDI7moPh8MbsQEKw.png" /><figcaption>“Kamu bukanlah function yang kutau!” ujar JS interpreter</figcaption></figure><p>Sementara, <em>function declaration</em> — yang selalu dimulai dengan <em>keyword function</em> di depan —semua bagian <em>function</em> nya (termasuk definisi di dalamnya) bakal di-<em>hoist</em> ke bagian atas <em>file</em> .js kamu tiap kali dideklarasiin. Jadi, <em>function declaration</em> bakal tetap bekerja meskipun kamu manggil (<em>invoke</em>) doi duluan sebelum kamu deklarasiin apa isi <em>function</em> nya. Liat gambar ini:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25ByogYshninLPoDwVDyMQ.png" /><figcaption>Fleksibel banget nih tipe function 😵</figcaption></figure><p>Kefleksibel-an <em>function</em> jenis <em>declaration</em> ini lah kadang yang sering bikin temen kamu yang<strong> <em>nggak-terlalu-javascript</em></strong><em> </em>bakal bingung ngeliat <em>function</em> nya nggak <em>error</em> tiap kali di-<em>invoke</em> sebelum dideklarasiin. 👻 👻</p><h3>Block Scope</h3><p>Jadi, pada dasarnya, <em>hoisting</em> variabel dan <em>function</em> di Javascript <em>works the same way</em>. Tapi, untuk variabel, jangan sampe keliru: <em>keyword</em> var sedikit berbeda jika dibandingin dengan <em>keyword</em> let ataupun const untuk masalah <em>hoisting</em> ini.</p><p><em>Keyword</em> var punya <em>scope</em> yakni <em>global scope</em> dan <em>function scope</em>, sementara untuk let dan const ada tambahan satu lagi: <em>block scope</em>. Jangan sampe lupa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*2XyPohflRXGVh8cwUm-fjg.png" /><figcaption>Sedikit perbedaan, tapi jangan sampe kecele.</figcaption></figure><p>Gak perlu pusing. <em>Block scope</em> konsep nya sama aja, kok. Bedanya cuma, semua variabel (tentunya harus let atau const) yang ada di dalam <em>block of code</em> — macam <em>if else statement</em>, atau <em>for loop</em>, atau <em>while loop</em>, dll — bakal di-<em>hoist</em> sampe ke batas <em>block of code</em> itu aja, gak bakal pernah variabel tersebut di-<em>hoist</em> sampe ke <em>parent block of code</em> tersebut, atau bahkan ke <em>global scope</em>.</p><p>Bingung? Sama. Saya yang nulis aja bingung. Mending langsung contoh aja lah, ya.</p><p>Oke, jadi, ibaratkan kita punya <em>code</em> kayak gini.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HsD_HYKrgNx-lKhIqHd5Eg.png" /><figcaption>Function yang agak bikin serem. Agak aja, sih…</figcaption></figure><p>Ini adalah sebuah <em>function </em>yang ada variabel let dengan value nya 0, kemudian ada <em>for of loop</em> dengan beberapa variabel, let item dengan <em>value </em>nya i, var pengganda dengan value nya 2, kemudian ditotal deh dengan cara meng-<em>assign value </em>baru lagi ke variabel total. Terakhir, total nya di-return, dan abis itu <em>function </em>nya di-<em>invoke </em>deh. Nggak terlalu serem lah ya.</p><p>Nah, dengan menggunakan pengetahuan kita dari artikel terdahulu tentang bagaimana proses <em>hoisting </em>terjadi <em>under the hood</em> di Javascript, maka akan didapatkan struktur <em>code </em>nya bakal jadi kayak gini:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*ddqPDDO1sEdn6r3p4ZtIOg.png" /><figcaption>Simulasi gimana proses hoisting variabel terjadi under the hood</figcaption></figure><p>Perhatiin gimana variabel var pengganda di dalam <em>for of loop</em> bakal ter-<em>hoist </em>sampe ke<em> function parent</em>, karena <em>keyword </em>var nggak bersifat <em>block scope</em>, melainkan <em>function scope</em> (dan juga <em>global scope</em> — jangan lupa). Lain ceritanya sama let item = i di dalam <em>for of loop</em>, cuma bakal mentok ter-<em>hoist </em>sampe ke bagian atas <em>block for of loop</em> itu sendiri.</p><p>Oke, udah kelar!</p><p>Ha? Udah, Va? Gitu doang? Trus, apa intinya?</p><p>Yaa, intinya cuma pengen nunjukin aja, kok, bahwa konsep kayak gini ini beneran ada dalam Javascript. Gunanya dengan ada konsep <em>hoisting </em>ini sebenernya supaya memaksa para <em>developer </em>agar bisa lebih <em>wise </em>lagi dalam meletakkan variabel-variabel yang ada dalam aplikasi nya.</p><p>Toh, kalo kamu taro variabel-variabel kamu di dalam <em>scope global</em> semua nya (mungkin karena kamu mau main aman, misalnya) secara bersamaan, juga gak bakal bagus, dan dipertimbangkan bukan sebagai <em>best practice </em>dalam penulisan code Javascript. Hal ini karena gampang banget bakal memicu <em>conflict </em>variabel ke depannya. Intinya, <em>be wise</em>!</p><h3>Sepenting itukah hoisting?</h3><p>Tapi, kenapa sih, Va, <em>hoisting </em>ini kayaknya penting banget?</p><p>Ya, penting nggak penting, sih. Masalah <em>hoisting </em>ini, kalo nggak diperdalam, kemungkinan besar bakal bikin runyam kehidupan kamu ketika ngoding (cieeek, lebay banget ini 😩). Output <em>code </em>yang nggak disangka-sangka bakal keluar kalo kamu nggak paham fundamental Javascript yang satu ini. Karena, biar gimanapun, behavior dalam Javascript yang satu ini emang rada <em>weird</em>. Dijamin nggak bakal kamu temuin di dalam bahasa pemrograman lainnya. Jadi, daripada kamu ngabisin waktu berjam-jam buat <em>debug error</em> kodingan kamu, mending preventif aja mulai dari sekarang.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*PZZmax14R7kI-PW4nrptqw@2x.jpeg" /></figure><p>Lagian, seperti yang udah saya bahas di <a href="https://medium.com/@rivayudha/javascript-hoisting-alasan-kamu-benci-javascript-part-i-68d50ebf4c9a">artikel part I</a>, <em>hoisting</em> ini termasuk yang lumayan umum ditanyain di seputar <em>interview</em> kerja. Dengan pemahaman kamu yang mendalam tentang materi ini, saya yakin kemungkinan besar sang pewawancara bakal terkesan. Percaya, deh.</p><p>Oke, artikel-artikel berikutnya bakal tetep bikin kamu benci (atau bahkan tambah benci) sama Javascript. Tapi, ya mudah-mudahan pas kamu udah baca keseluruhannya, malah jadi manut-manut sendiri, trus akhirnya malah nyari-nyari Javascript mulu seharian. Yeeeee… 👰 👰</p><p>Silakan tanya kalo ada yang mau ditanya, atau kalo ada yang mau koreksi. Dengan senang hati bakal diterima. Apalagi tepuk tangannya (uhuk), dinanti banget. 😻 😻</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F27bXZY8kF7q7tXcMNu%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FTheOpposition-yeah-yay-27bXZY8kF7q7tXcMNu&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F27bXZY8kF7q7tXcMNu%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f30ad3b0775a641676fede8b1795f36/href">https://medium.com/media/3f30ad3b0775a641676fede8b1795f36/href</a></iframe><p><em>Anyway</em>, sampai jumpa, semua! Makasih banyak, loh, ini. 🚀 🚀 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93ed3220630d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Hoisting — Alasan Kamu Benci Javascript (Part I)]]></title>
            <link>https://medium.com/@rvyw/javascript-hoisting-alasan-kamu-benci-javascript-part-i-68d50ebf4c9a?source=rss-faac47880b00------2</link>
            <guid isPermaLink="false">https://medium.com/p/68d50ebf4c9a</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Riva Yudha]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 20:47:06 GMT</pubDate>
            <atom:updated>2018-03-04T08:07:29.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uzpb-TDZFBtwFh6w." /><figcaption>Hoisting is really something. Photo by <a href="https://unsplash.com/@samuelzeller?utm_source=medium&amp;utm_medium=referral">Samuel Zeller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bukan. Kamu benci Javascript bukan karena dia susah (<em>at least</em>, bagi saya). Bukan juga karena doi <em>evolving </em>terlalu cepat belakangan ini dengan segala teknologi-teknologi baru nya yang muncul hampir tiap hari, yang memaksa kamu harus “belajar” hal baru terus tentang Javascript, <em>almost every single day</em>. Bukan karena itu.</p><p><em>Well</em>, kamu benci Javascript (kemungkinan) karena Javascript sering bertindak <em>nyeleneh</em>, <em>seenakne dewe</em>, dan kadang nggak masuk logika. Khusus untuk yang terakhir, saya sering mikir bahwa Javascript ini sudah barang tentu berkelamin cewe, di mana saya sering dibuat pusing — sampe-sampe saya pernah minta ampun sendiri (ini beneran!) sama dia di depan laptop — karena <em>code </em>yang saya ketik menurut saya udah valid sevalid-valid nya umat, tapi tetep aja dia dengan dinginnya <em>threw me an error</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*v7R_ndqt-JSiILuUf0azyg.jpeg" /><figcaption>Javascript x Novanto x Dilan</figcaption></figure><p>Belum pernah ngerasain didinginin sama Javascript tanpa alasan yang jelas? Kalo belum, baca aja terus post ini — dan juga <em>post-post</em> lanjutan berikutnya — di mana saya bakal nunjukin beberapa keanehan Javascript yang sering bikin para <em>developer </em>pengen gigit gelas (<em>since </em>gigit jari kadang terlihat semacam sedang sange).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9KyaJgGAH94aanFaV4C-Q.png" /><figcaption>Block of code yang nggak keliatan janggal sama sekali. Until…</figcaption></figure><p>Oke, udah liat? Iya, bener. Nggak ada yang aneh sama <em>code </em>di atas<em>. </em>Yang kita lakukan simpel banget, sih<em>. </em>Kita definisikan variabel global num dengan <em>value </em>nya 100 , kemudian kita bikin <em>function declaration </em>yang tugas nya cuma ngeprint data ke <em>console, plus </em>di situ kita deklarasi ulang variable num nya dengan <em>value</em> yang berbeda<em>.</em> Di <em>line </em>terakhir, kita <em>invoke function</em> nya, deh.</p><p>Sebelum kita tenggelam lebih dalam, saya pengen minta tolong kamu fokus ke <em>code </em>itu dulu. Tanpa kamu utak-atik <em>code </em>tersebut di IDE atau di DevTools manapun, coba kamu — dengan hanya melihat — tebak, deh, apa output yang kira-kira bakal keluar setelah <em>function </em>nya di-<em>invoke</em>?</p><p>Udah coba nebak? Apa hasilnya?</p><p>25?</p><p>Ha? 100?</p><p>Yakin, nih? Yaudah. Kita coba jalanin <em>code </em>nya, dan output nya adalah…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*pW7yilVxN_-2XG9sIruynQ.png" /><figcaption>Kejanggalan mulai menampakkan dirinya…</figcaption></figure><p>Kenapa mesti <em>undefined</em>? Perasaan udah dideklarasiin, deh. <em>Well</em>, oke, ini memang janggal, tapi kalo kita ngerti konsep fundamental Javascript, ini masuk akal banget, kok. Tapi, itu kalo kita udah ngerti konsep nya. Kalo kasusnya kayak saya — yang awalnya nggak ngeh ada konsep semacam ini — sumpah serapah buat Javascript akan dengan amat lancar dilontarkan, apalagi kalo kita udah <em>trial-and-error</em> berpuluh-puluh kali tapi tetep hasil yang keluar gak sesuai ekspektasi. 😢</p><p>Yang perlu diketahui di sini adalah setiap variabel dengan <em>keyword </em>var<em> </em>akan di-<em>hoist </em>(Indo nya sih “diangkat”, tapi saya lebih suka menerjemahkan <em>hoist </em>itu “dilempar ke atas”) ke bagian atas <em>file </em>.js kita. <em>Normally</em>, bakal seperti itu, tapi karena (khusus si) var num = 25 itu ada di dalam <em>body function, </em>jadi dia cuma bakal dilempar sampe ke bagian atas function nya aja (dalam hal ini, yakni <em>function printNumber()</em>). Ini karena <em>keyword</em> var itu bersifat <em>function scope, </em>yang berarti kalo dia berada di dalam sebuah <em>function</em>, maka dia cuma bakal dilempar sampe ke bagian atas <em>body function</em> tempat dia berada aja, dan nggak bakal sampe ke luar-luar dari <em>function </em>itu.</p><p>Ini berarti, kalo kita mau simulasiin proses <em>hoisting </em>tersebut di <em>code </em>kita, bakal jadi begini nih posisi si num yang ada di dalam <em>function:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQ7jwvsvIzW5C4wcLAioWw.png" /><figcaption>Simulasi: Karena hoisted, doi kelempar deh sampe ke perbatasan function yang menaunginya</figcaption></figure><p>Oh, gitu. Oke, deh. Eh, tunggu tunggu! Karena dia udah di atas si <em>statement </em>console.log, kok tetep <em>undefined</em>? Harusnya <em>value </em>num malah jadi kebaca, dong?</p><p>Nah, oke. Bagus kalo kamu nyadar. Ini karena proses <em>hoisting </em>sebenernya<em> </em>bukanlah seperti itu<em>. </em>Tadi saya agak boong dikit. 👼</p><p>Jadi, sebenernya, <em>under the hood</em>, proses <em>hoisting </em>yang terjadi di dalam Javascript (khususnya pada variabel num kita yang ada di dalam <em>function</em>) adalah seperti ini:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVX7WL9tE8giFTFoQZSBMw.png" /><figcaption>Simulasi: Proses hoisting asli. Kali ini no tipu-tipu.</figcaption></figure><h4>Inget, <em>code </em>di atas itu (terutama untuk bagian <em>body function</em>) cuma simulasi ya, nunjukin gimana JS bekerja untuk masalah beginian, di belakang layar. <em>Code </em>sebenernya (<em>as you already knew</em>) nggak kayak gitu.</h4><p>Oke, jadi kalo kita tilik, yang terjadi di situ adalah:</p><ol><li>JS bakal inisialisasi variabel nya tanpa ngasih value apapun;</li><li>Kemudian console.log(num) dijalankan;</li><li>Akhirnya, JS <em>assign value</em> yang semestinya ke si num (<em>finally</em>, ya, num…)</li></ol><p>Berhubung di bagian var num nggak ada <em>value </em>sama sekali, <em>statement </em>console.log bakal <em>return undefined, </em>karena <em>value </em>yang dibutuhkan malah ada di bawahnya, <em>which is</em> doi nggak punya kuasa buat ngambil <em>value </em>sampe<em> </em>ke bawah-bawah.</p><p>Lah, tapi, Va, kan ada variabel global tuh di atas, udah nunggu banget tuh pengen diambil <em>value </em>nya. Kok si console.log nggak ngambil <em>value </em>si variabel global aja?</p><p>Nah, itu lah dia <em>hoisting</em>. Sesuai yang saya simulasiin di atas, berhubung var num udah ada di atas nya console.log(), jadi mau gak mau console.log() cuma berhak ambil bagian dari si var num aja. Ini lah yang disebut <em>scope </em>atau <em>scoping </em>tadi.</p><p>Oke, untuk lebih memahami ini, saya bakal coba hapus var num = 25 di dalem <em>function </em>ya. Dan apa hasilnya? Udah bisa ketebak? Yak!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*SsWd71YsLtH9WCF5kAuK1A.png" /><figcaption>Kali ini si console.log dikasih value beneran. Akhirnya…</figcaption></figure><p>Kita dapet output nya 100! Ini <em>simply </em>karena console.log() kali ini berhasil ngambil <em>value </em>dari variabel yang tersedia secara global — dalam hal ini si var num = 100 di atas. Kenapa dia berhasil? Karena kali ini nggak ada yang nge-<em>block </em>dia untuk menggapai cita-cita nya itu. Si var num = 25 udah di-<em>remove </em>demi si console.log() yang lebih baik lagi ke depannya. 😫</p><p>Oke, gimana? Udah agak ngerti, kan? Lumayan lah ya. Nah, sekarang, itu kan pake var, gak jaman banget, sih, Va. Pake let kek, apa kek.</p><p>Nah, pertanyaan bagus! <em>The fact is</em>, kalo kita udah make <em>keyword </em>variabel yang lain, semacam let atau const, bakal ngasih hasil yang lain pula.</p><p>Lah, kok bisa?</p><p>Iya bisa, karena var berbeda secara <em>scoping </em>jika dibandingin sama let dan const. Kalo var itu sifatnya <em>function scope</em>, kalo si let dan const sifatnya <em>block scope</em>. Ribet? Banget! Tapi gapapa, masalah <em>scoping </em>masing-masing <em>keyword </em>variabel itu bakal saya bahas lagi secara mendalam di artikel -artikel selanjutnya. Untuk sekarang, mari <em>stick to </em>yang ini<em> </em>aja dulu.</p><p><em>Alright</em>, sekarang, saya ganti, nih, ya <em>keyword </em>var nya jadi ke let. Dan lihat apa hasilnya…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*sqrtdL8c97PS-jJjzlmguw.png" /><figcaption>Apa-apaan lagi sih ini, JS? Ah elah!</figcaption></figure><p>Bentar! Jangan marah dulu! Oke, kali ini malah dikasih <em>error </em>beneran. Yang tadi <em>undefined</em>, yang ini malah <em>error </em>asli. Orisinil.</p><p>Nah, jadi gini. Justru ini <em>solve problem</em> kita. Ha? Malah ini <em>solve problem</em> kita? Gilak ya, Va?</p><p>Nggak, ini serius. Jadi, dengan let kita dikasih <em>error </em>harusnya kita bersyukur, karena memang seharusnya masalah <em>scoping </em>dan<em> hoisting </em>ini jangan sampe bikin pusing.</p><p>Kalo pake var tadi, kita dikasih <em>undefined</em>, <em>which is</em> itu cuma nunjukin kayak “Oke, nggak apa-apa. Ada sesuatu yang nggak beres, tapi nggak apa-apa kok, lanjutin aja.” Sementara dengan pake teknologi baru (ya, let kan termasuk teknologi baru di JS), kita langsung dikomplain bahwa mereka gak mau terima sistem kayak gini. Yang mana mengharuskan kita nulis ulang <em>code </em>nya lebih “terdidik” lagi. 😚</p><p>Jadi, dengan komplain yang <em>straightforward </em>itu, apa yang kita harus lakuin, yaa, ubah posisi si console.log() supaya berada di bawah var num = 25, dong. Sesimpel itu, sih. Dan, coba kita <em>run </em>lagi <em>code </em>nya…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*t9D4-kQIK8HmZR6T4AWlIw.png" /><figcaption>Pada akhirnya semua berjalan sebagaimana mestinya hidup ini berjalan…</figcaption></figure><p><em>Well done</em>! <em>Function </em>kita udah berjalan. Dengan ini artinya kita udah berhasil <em>tackle</em> salah satu fundamental Javascript yang bikin ribet. Serius! Ini salah satu topik yang berhasil bikin saya benci sama Javascript, dulu.</p><p>Oke, hal utama yang perlu diperhatikan yakni bahwa masalah <em>hoisting</em>, <em>scope</em>, dan <em>behavior </em>para variabel ini merupakan masalah-masalah yang paling umum ditanyain di tiap <em>interview </em>kerja Javascript. Dengan kamu mengetahui fundamental nya, <em>hopefully</em> si <em>interviewer </em>bisa terkesan dan akhirnya ngejamin kamu masuk sur, eh, kantor mereka. Saran saya: banyakin waktu luang untuk utak-atik <em>code</em> kamu. Biarin tangan kamu kotor sama <em>code</em> kamu sendiri. Karena katanya, cara efektif supaya jago ngoding, yaa, dengan ngoding. Udah, itu aja sih.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*fxQxG9z_FdIL_mWtjxp9dw@2x.jpeg" /></figure><p>Anyway, kalo masih ada yang kurang ngerti, silakan komentar aja di bawah, selama bisa dijawab pasti bakal dijawab. Dan kalo kamu ngerasa artikel ini ada manfaatnya, tepuk tangan, ya, supaya rada semangat dikit saya nya — dalam menjalani hidup. 💃</p><p>Makasih banyak, loh, ini. <em>See you in the next articles! 👋🏼👋🏼👋🏼</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68d50ebf4c9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>