<?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 taka on Medium]]></title>
        <description><![CDATA[Stories by taka on Medium]]></description>
        <link>https://medium.com/@takadevxyz?source=rss-590e2bb5b926------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KuMXN_02-lVjdEXb2wHcPQ.png</url>
            <title>Stories by taka on Medium</title>
            <link>https://medium.com/@takadevxyz?source=rss-590e2bb5b926------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:22:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@takadevxyz/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[I Just Wanted to Install k6. Debian Said No — Here’s What Broke and How I Fixed It]]></title>
            <link>https://takadevxyz.medium.com/i-just-wanted-to-install-k6-debian-said-no-heres-what-broke-and-how-i-fixed-it-cb5206067ae3?source=rss-590e2bb5b926------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb5206067ae3</guid>
            <category><![CDATA[k6]]></category>
            <category><![CDATA[grafana-k6]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[apt]]></category>
            <category><![CDATA[debian]]></category>
            <dc:creator><![CDATA[taka]]></dc:creator>
            <pubDate>Wed, 17 Dec 2025 16:14:36 GMT</pubDate>
            <atom:updated>2025-12-17T16:14:36.025Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Just Wanted to Install k6. Debian Said No — Here’s What Broke and How I Fixed It</h3><figure><img alt="Illustrated banner showing a hooded developer, Debian Linux imagery, installation error warnings, and a chained k6 symbol." src="https://cdn-images-1.medium.com/max/1024/1*fTrzH0USNYIn8-0s9as9dQ.png" /><figcaption><em>Illustrated banner showing a hooded developer, Debian Linux imagery, installation error warnings, and a chained k6 symbol.</em></figcaption></figure><h3>Introduction</h3><p>I wasn’t trying to do anything fancy. No edge-case configuration. No experimental setup.</p><p>I just wanted to install <strong>k6</strong>.</p><p>A few commands in, apt update completely refused to cooperate. Errors everywhere. EOF. Failed to parse keyring. And the classic closer: <em>“The repository is not signed.”</em></p><p>This wasn’t a network issue. This wasn’t a typo.</p><p>This was Debian doing exactly what it was designed to do — <strong>block untrusted software</strong>.</p><p>This is the story of what broke, why it broke, and the exact steps I took to fix it <em>properly</em>.</p><h3>The Setup</h3><ul><li>OS: <strong>Debian Trixie</strong></li><li>Goal: Install <strong>k6</strong> for load testing</li><li>Method: Official repository</li><li>Expectation: Quick install</li><li>Reality: Signature verification failure</li></ul><p>Everything looked normal until apt update ran.</p><h3>The Problem: When apt update Says “No”</h3><p>Here’s the kind of error I kept seeing:</p><ul><li>Failed to parse keyring</li><li>EOF</li><li>Sub-process /usr/bin/sqv returned an error code (1)</li><li>The repository is not signed</li></ul><p>At first glance, this feels random. But it’s not.</p><p>Modern Debian uses <a href="https://book.sequoia-pgp.org/sqv.html"><strong>sqv</strong></a> for signature verification, and it is <strong>far stricter</strong> than older systems.</p><p>And that strictness is exactly what exposed the real issue.</p><h3>What Actually Broke</h3><p>The problem wasn’t k6.</p><p>The problem was this file:</p><pre>/usr/share/keyrings/k6-archive-keyring.gpg</pre><p>It existed — but it was <strong>empty or corrupted</strong>.</p><p>That happened because I initially imported the key using a keyserver method that silently failed. The file was created, but with <strong>no valid data inside it</strong>To sqv, that means one thing:</p><blockquote><em>“I cannot trust this repository.”</em></blockquote><p>And Debian shuts the door. Correctly.</p><h3>The Wrong Fixes (Don’t Do This)</h3><p>At this point, it’s tempting to:</p><ul><li>Disable signature checks</li><li>Use --allow-unauthenticated</li><li>Ignore the error and move on</li></ul><p>That would “work” — and completely defeat the security model. I didn’t want a workaround. I wanted a <strong>clean, future-proof fix</strong>.</p><h3>The Correct Fix (Step by Step)</h3><p>This is the exact sequence that solved it.</p><h3>Step 1: Remove the broken keyring and repo</h3><pre>sudo rm -f /usr/share/keyrings/k6-archive-keyring.gpg<br>sudo rm -f /etc/apt/sources.list.d/k6.list</pre><p>This clears all corrupted state.</p><h3>Step 2: Recreate the keyring the right way</h3><p>Instead of pulling keys from a keyserver, I used a deterministic approach.</p><pre>curl -fsSL https://dl.k6.io/key.gpg \<br>| sudo gpg --dearmor -o /usr/share/keyrings/k6-archive-keyring.gpg</pre><p>This produces a valid binary keyring that sqv can verify.</p><h3>Step 3: Validate the keyring</h3><p>Before trusting it, I verified it:</p><pre>gpg --no-default-keyring \<br>  --keyring /usr/share/keyrings/k6-archive-keyring.gpg \<br>  --list-keys</pre><p>If this outputs a key, the trust chain is intact.</p><h3>Step 4: Re-add the k6 repository</h3><pre>echo &quot;deb [signed-by=/usr/share/keyrings/k6-archive-keyring.gpg] https://dl.k6.io/deb stable main&quot; \<br>| sudo tee /etc/apt/sources.list.d/k6.list</pre><p>Explicit trust. No legacy behavior.</p><h3>Step 5: Update and install</h3><pre>sudo apt update<br>sudo apt install k6</pre><p>No warnings. No errors. Clean install.</p><p>Verification</p><pre>k6 version</pre><p>At this point, k6 is fully installed and verified.</p><h3>What I Learned</h3><p>This wasn’t a k6 problem.<br> It was a <strong>modern Linux security lesson</strong>.</p><ul><li>Debian is strict by design</li><li>sqv doesn’t tolerate malformed keyrings</li><li>Keyservers can silently fail</li><li>Deterministic key imports are safer and future-proof</li><li>If apt blocks something, it usually has a good reason</li></ul><p>Once you align with the system’s trust model, everything works smoothly.</p><h3>Final Thoughts</h3><p>What started as a five-minute install turned into a deep dive into how modern Debian handles software trust.</p><p>And honestly? I’m glad it did.</p><p>Because now I don’t just have k6 installed — I understand <strong>why</strong> it installs cleanly.</p><p>If this saves you an hour of debugging, it was worth writing.</p><p>k6 official docs: <a href="https://grafana.com/docs/k6/latest/set-up/install-k6/">https://grafana.com/docs/k6/latest/set-up/install-k6/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb5206067ae3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Enable SSH Access and Activate SSH Key Authentication on a VPS]]></title>
            <link>https://takadevxyz.medium.com/how-to-enable-ssh-access-and-activate-ssh-key-authentication-on-a-vps-a5d2332fe65c?source=rss-590e2bb5b926------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5d2332fe65c</guid>
            <category><![CDATA[remote-ssh]]></category>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[termius]]></category>
            <category><![CDATA[vps]]></category>
            <category><![CDATA[linux-terminal]]></category>
            <dc:creator><![CDATA[taka]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 10:29:50 GMT</pubDate>
            <atom:updated>2025-11-10T10:29:50.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZG3_oa6XOGFMnTomluk_eQ.png" /><figcaption>background image article</figcaption></figure><p>This guide walks you through the process of setting up secure SSH access on your VPS using key-based authentication. Learn how to generate SSH keys, upload them to your server, configure SSH for secure login, and understand why SSH keys are a safer and more reliable alternative to root passwords.</p><h3>🧩 Outline</h3><h3>1. Introduction</h3><ul><li>Briefly explain what SSH (Secure Shell) is and why it’s used to access a VPS.</li><li>Mention that SSH is the standard method for remote server administration.</li></ul><p><strong>Example:</strong></p><blockquote><em>SSH (Secure Shell) is a protocol used to securely connect to and manage remote servers. Instead of logging in with insecure methods, SSH encrypts your communication and allows you to control your VPS safely from anywhere.</em></blockquote><h3>2. Why Use SSH Keys Instead of a Root Password</h3><p>Explain the advantages of SSH key authentication:</p><p><strong>a. Stronger Security:</strong><br> SSH keys are much harder to brute-force compared to passwords because they use long, complex cryptographic pairs.</p><p><strong>b. Protection Against Password Theft:</strong><br> Even if someone knows your username, they can’t log in without your private key.</p><p><strong>c. Easier Automation:</strong><br> SSH keys can be used for secure automation (e.g., Git deployment, server scripts) without needing to type a password.</p><p><strong>d. Compliance and Best Practices:</strong><br> Disabling password login is a standard security practice for production servers.</p><p><strong>Example:</strong></p><blockquote><em>Using SSH keys eliminates the risk of weak or reused passwords, providing a stronger and more reliable way to access your VPS.</em></blockquote><h3>3. Generate an SSH Key Pair</h3><p>Explain how to create an SSH key pair on the local machine:</p><pre>ssh-keygen -t ed25519 -C &quot;your_email@example.com&quot;</pre><p>Explain what each file means:</p><ul><li>id_ed25519 → private key (keep safe)</li><li>id_ed25519.pub → public key (to share with your VPS</li></ul><h3>4. Upload the Public Key to the VPS</h3><p>copy content of id_ed25519.pub</p><p>manually paste it into ~/.ssh/authorized_keys and set permissions:</p><pre>chmod 700 ~/.ssh<br>chmod 600 ~/.ssh/authorized_keys</pre><h3>5. Configure the SSH Daemon</h3><p>Edit /etc/ssh/sshd_config and ensure the following lines are set:</p><pre>PubkeyAuthentication yes<br>PasswordAuthentication no<br>PermitRootLogin prohibit-password</pre><p>Then restart SSH:</p><pre>sudo systemctl restart ssh</pre><h3>6. Test SSH Access</h3><p>open terminal in your local machine the run</p><pre>ssh root@your_server_ip</pre><p>or you can use other app to remote vps, like <a href="https://termius.com/index.html">termius</a></p><p>If setup correctly, it should log in <strong>without asking for a password.</strong></p><h3>7. (Optional) Enable Firewall for SSH</h3><p>For Ubuntu (UFW):</p><pre>sudo ufw allow ssh<br>sudo ufw enable<br>sudo ufw status</pre><h3>8. Conclusion</h3><p>Summarize the benefits:</p><ul><li>Secure remote access using encryption</li><li>No password-based attacks</li><li>Easier automation and management</li><li>Follows best security practices for any production VPS</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5d2332fe65c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ How to Add Swap Space on Linux/ Debian (Extend Your RAM Using Disk Storage)]]></title>
            <link>https://takadevxyz.medium.com/how-to-add-swap-space-on-linux-debian-extend-your-ram-using-disk-storage-acb37703483f?source=rss-590e2bb5b926------2</link>
            <guid isPermaLink="false">https://medium.com/p/acb37703483f</guid>
            <category><![CDATA[debian]]></category>
            <category><![CDATA[gui̇de]]></category>
            <category><![CDATA[linux-swap-space]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[swap]]></category>
            <dc:creator><![CDATA[taka]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 04:19:29 GMT</pubDate>
            <atom:updated>2025-11-08T04:19:29.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7YYa4YOYGBPx8RhLypdsQ.png" /><figcaption>Visual Guide</figcaption></figure><p>If your Debian server or VPS only has a small amount of RAM, like 2 GB or 4 GB, you might notice it slows down or even kills processes when running out of memory.<br> Luckily, Linux allows you to use part of your storage as <strong>virtual memory</strong>, called <strong>swap space</strong>.</p><p>This guide will show you how to create and enable swap space on Debian step by step.</p><h3>💡 What Is Swap Space?</h3><p><strong>Swap space</strong> is an area on your disk that Linux uses as an extension of your physical RAM.<br> When your system runs out of real memory, it temporarily moves inactive data from RAM to swap — freeing up space for active applications.</p><p>Although swap is <strong>slower</strong> than real RAM (because it uses disk I/O), it can prevent crashes and “Out of Memory” errors.</p><h3>🧩 Two Ways to Add Swap</h3><p>You can create swap in two main ways:</p><ol><li><strong>Swap Partition</strong> — a dedicated partition on your disk.</li><li><strong>Swap File</strong> — a file that acts as swap (easier and more flexible).</li></ol><p>In this tutorial, we’ll use the <strong>swap file method</strong>.</p><h3>⚙️ Step-by-Step: Create Swap File on Debian</h3><h3>1. Check Existing Swap</h3><p>Run this command to see if swap is already enabled:</p><pre>swapon --show</pre><p>If there’s no output, you don’t have swap enabled yet.</p><h3>2. Check Available Disk Space</h3><p>Make sure your disk has enough free space:</p><pre>df -h</pre><p>You’ll need at least a few gigabytes of free space (e.g., 2 GB–4 GB).</p><h3>3. Create the Swap File</h3><p>Let’s create a 4 GB swap file.</p><p>Use <strong>fallocate</strong> (fast method):</p><pre>sudo fallocate -l 4G /swapfile</pre><p>If fallocate isn’t supported on your file system, use <strong>dd</strong> instead:</p><pre>sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 status=progress</pre><h3>4. Secure the File</h3><p>For security reasons, only root should be able to read or write this file:</p><pre>sudo chmod 600 /swapfile</pre><h3>5. Format It as Swap</h3><p>Now we’ll turn the file into swap space:</p><pre>sudo mkswap /swapfile</pre><p>Expected output:</p><pre>Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)<br>no label, UUID=xxxxxxx</pre><h3>6. Enable the Swap File</h3><p>Activate your new swap space:</p><pre>sudo swapon /swapfile</pre><p>Verify it’s working:</p><pre>swapon --show<br>free -h</pre><p>You should see something like:</p><pre>              total        used        free      shared  buff/cache   available<br>Mem:           3.8G        2.6G        0.6G        0.1G        0.6G        0.9G<br>Swap:          4.0G          0B        4.0G</pre><h3>7. Make It Permanent</h3><p>To enable swap automatically at boot:</p><pre>echo &#39;/swapfile none swap sw 0 0&#39; | sudo tee -a /etc/fstab</pre><h3>🧮 How Much Swap Should You Use?</h3><pre>&#39; Recommended Swap Space Based on RAM Size<br><br>| RAM Size | Recommended Swap        |<br>| -------- | ----------------------- |<br>| 1 GB     | 2 GB                    |<br>| 2 GB     | 2–3 GB                  |<br>| 4 GB     | 4 GB                    |<br>| 8 GB+    | 2 GB or none (optional) |</pre><h3>✅ Conclusion</h3><p>You’ve successfully created and enabled swap space on your Debian system.<br> Now your server has more room to handle heavy workloads, even with limited physical RAM.</p><p><strong>In summary:</strong></p><ul><li>Swap acts as virtual RAM using disk space.</li><li>It’s easy to create and manage with a swap file.</li><li>Adjust swappiness to optimize performance.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acb37703483f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Renting a VPS? Don’t Forget to Check the IP Type!]]></title>
            <link>https://takadevxyz.medium.com/renting-a-vps-dont-forget-to-check-the-ip-type-eea9b041b5d1?source=rss-590e2bb5b926------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea9b041b5d1</guid>
            <category><![CDATA[warp]]></category>
            <category><![CDATA[ipv6]]></category>
            <category><![CDATA[gui̇de]]></category>
            <category><![CDATA[vps]]></category>
            <category><![CDATA[remote-work]]></category>
            <dc:creator><![CDATA[taka]]></dc:creator>
            <pubDate>Fri, 07 Nov 2025 02:23:13 GMT</pubDate>
            <atom:updated>2025-11-07T02:23:13.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8Oh0bQBJXjsopVmBNE8zA.png" /><figcaption>visual guide: how to check ipv6 on your machine and enable warp</figcaption></figure><p>When you’re about to rent a VPS, it’s easy to get lost in CPU specs, RAM, and disk space. But there’s one detail most people overlook — and it can make or break your setup: <strong>the type of IP your VPS provides.</strong></p><p>Yes, I’m talking about <strong>IPv4 vs IPv6</strong>.</p><h3>Why IP Type Matters</h3><p>Most VPS providers still offer <strong>IPv4</strong>, but some are now providing <strong>IPv6-only</strong> or dual-stack (IPv4 + IPv6). If your VPS has an IPv6 address, you <strong>must ensure your local machine and ISP can handle IPv6</strong>. Otherwise, connecting via SSH or RDP might fail completely.</p><h3>How to Check if Your Local Machine &amp; ISP Support IPv6</h3><p>Here’s the quick way to check:</p><ol><li><strong>On Windows:</strong></li></ol><ul><li>Open Command Prompt and type:</li></ul><pre>ipconfig</pre><ul><li>Look for an IPv6 address under your active network adapter.</li></ul><p>2. <strong>On macOS/Linux:</strong></p><ul><li>Open Terminal and type:</li></ul><pre>ifconfig</pre><p>or</p><pre>ip addr</pre><ul><li>Check if there’s an IPv6 address assigned.</li></ul><p>3. <strong>Check your ISP:</strong></p><ul><li>Visit <a href="https://test-ipv6.com/">https://test-ipv6.com</a>.</li><li>It will tell you if your network supports IPv6.</li></ul><p>If your machine or ISP <strong>doesn’t support IPv6</strong>, don’t worry — you still have a solution.</p><h3>Use Cloudflare WARP as a Workaround</h3><p><strong>Cloudflare WARP</strong> can act as a bridge, allowing your IPv4-only machine to communicate with IPv6-only VPS. Here’s how:</p><p>1. Install <strong>Cloudflare WARP</strong> on your local machine.</p><p>2. Enable <strong>IPv6 support</strong> in the WARP settings.</p><p>3. Now your machine can reach IPv6 VPS addresses as if your ISP natively supports IPv6.</p><p>This is a lifesaver when renting VPS with IPv6-only setups.</p><h3>Key Takeaways</h3><ul><li>Always <strong>check the VPS IP type</strong> before renting.</li><li>Ensure your <strong>local machine &amp; ISP support IPv6</strong> if the VPS uses IPv6.</li><li>If not, <strong>Cloudflare WARP</strong> is an easy fix.</li><li>Planning ahead saves time, frustration, and headache.</li></ul><p>By keeping IPv6 in mind, you’ll never be stuck wondering why your VPS is unreachable. Think ahead, connect seamlessly, and enjoy your server from day one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea9b041b5d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Tips: Connect to an Existing Container Using Nginx Reverse Proxy]]></title>
            <link>https://takadevxyz.medium.com/docker-tips-connect-to-an-existing-container-using-nginx-reverse-proxy-d9dd96e92233?source=rss-590e2bb5b926------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9dd96e92233</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[taka]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 00:05:11 GMT</pubDate>
            <atom:updated>2025-10-14T00:05:11.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*WCfOXwO0W4XcJi_5l-zRBA.png" /><figcaption><em>“Accessing an existing container through a reverse proxy.”</em></figcaption></figure><p>Have you ever wanted to access a running Docker container but realized you’d have to re-run it just to expose a port?</p><p>In this article, I’ll show you a simple trick using <strong>Nginx as a reverse proxy</strong> so you can connect to an existing container without restarting or rebuilding anything.</p><p>Let’s say you already have a container running your app:</p><pre>docker run -d --name my-app my-app-image</pre><p>But you forgot to expose the port! Normally, you’d have to stop and re-run it with -p, like:</p><pre>docker run -d -p 8080:80 --name my-app my-app-image</pre><p>That means downtime and losing your container state. 😩</p><p>Instead of re-running the container, you can spin up an <strong>Nginx container</strong> that routes traffic to your existing container internally.</p><h4>Step 1: Create a custom network</h4><pre>docker network create my-network</pre><h4>Step 2: Connect your existing container to that network</h4><pre>docker network connect my-network my-app</pre><h4>Step 3: Run an Nginx container on the same network</h4><p>make sure in your machine has image nginx. if not just pull from docker hub then run the image</p><pre>docker pull nginx</pre><pre>docker run -d \<br>  --name nginx-proxy \<br>  --network my-network \<br>  -p 8080:80 \<br>  nginx</pre><h4>Step 4: Configure Nginx</h4><p>Create a config file default.conf:</p><pre>server {<br>    listen 80;<br>    location / {<br>        proxy_pass http://my-app:80;<br>    }<br>}</pre><p>Then mount it:</p><pre>docker run -d \<br>  --name nginx-proxy \<br>  --network my-network \<br>  -p 8080:80 \<br>  -v $(pwd)/default.conf:/etc/nginx/conf.d/default.conf \<br>  nginx</pre><p>Open your browser:</p><pre>http://localhost:8080</pre><h3>Conclusion</h3><p>Using an Nginx reverse proxy is a clean and efficient way to access containers without touching their original configuration.</p><p>It saves time, avoids downtime, and gives you flexibility when debugging or testing multiple services.</p><p>✅ <strong>Key takeaway:</strong><br> You don’t need to re-run containers, just let Nginx handle the routing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9dd96e92233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Functions in JavaScript: A Beginner’s Guide]]></title>
            <link>https://takadevxyz.medium.com/mastering-functions-in-javascript-a-beginners-guide-ffc9074330ee?source=rss-590e2bb5b926------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffc9074330ee</guid>
            <category><![CDATA[coding-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[js-function]]></category>
            <dc:creator><![CDATA[taka]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 02:27:54 GMT</pubDate>
            <atom:updated>2024-10-30T02:27:54.417Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqspbmC3UVfAkULPwr8JTA.png" /><figcaption>Function in JavaScript</figcaption></figure><h3>What is a Function?</h3><p>A function is a block of reusable code designed to perform a particular task. Instead of repeating the same code multiple times, you can define a function and call it whenever needed. Functions help make your code more readable, maintainable, and scalable.</p><h3>Syntax of a Function</h3><p>In JavaScript, a function is defined using the function keyword, followed by:</p><ul><li>A <strong>name</strong> (optional, but recommended for clarity).</li><li><strong>Parameters</strong> (input values the function can use).</li><li>A <strong>body</strong> (the block of code the function will execute).</li></ul><p>Here’s a simple example:</p><pre>function greet(name) {<br>    return &quot;Hello, &quot; + name + &quot;!&quot;;<br>}<br><br>// Calling the function<br>console.log(greet(&quot;Haiiru&quot;));  // Output: Hello, Haiiru!</pre><p>In this example, greet is the function name, and name is a parameter that the function uses.</p><h3>Types of Functions in JavaScript</h3><p>JavaScript provides multiple ways to define functions. Let’s explore the most common ones.</p><h4>1. Function Declaration</h4><p>A function declaration is the most common way to define a function. These functions are hoisted, meaning they can be called before their definition in the code.</p><pre>function add(a, b) {<br>    return a + b;<br>}<br><br>console.log(add(2, 3));  // Output: 5</pre><h4>2. Function Expression</h4><p>A function expression assigns a function to a variable. Unlike function declarations, function expressions are not hoisted, so they must be defined before they are called.</p><pre>const multiply = function(a, b) {<br>    return a * b;<br>};<br><br>console.log(multiply(4, 5));  // Output: 20</pre><h4>3. Arrow Functions</h4><p>Arrow functions provide a concise way to write functions in JavaScript. They are especially useful for shorter, inline functions. One key feature of arrow functions is that they do not have their own this context.</p><pre>const divide = (a, b) =&gt; a / b;<br><br>console.log(divide(10, 2));  // Output: 5</pre><h4>4. Immediately Invoked Function Expression (IIFE)</h4><p>An IIFE is a function that is executed immediately after it is defined. This is useful for creating a local scope and avoiding polluting the global scope.</p><pre>(function() {<br>    console.log(&quot;This function runs immediately!&quot;);<br>})();</pre><h4>5. Anonymous Functions</h4><p>Anonymous functions are functions without a name. They are typically used as arguments in higher-order functions (such as map, filter, or forEach).</p><pre>const numbers = [1, 2, 3];<br>numbers.forEach(function(num) {<br>    console.log(num * 2);  // Output: 2, 4, 6<br>});</pre><h3>Parameters and Arguments</h3><p>A function can take input values, known as <strong>parameters</strong>, which allow you to pass data into the function. When you call a function, you provide <strong>arguments</strong>, which are the actual values for those parameters.</p><h4>Default Parameters</h4><p>You can set default values for parameters in case arguments are not provided.</p><pre>function greetUser(name = &quot;Guest&quot;) {<br>    return &quot;Hello, &quot; + name;<br>}<br><br>console.log(greetUser());  // Output: Hello, Guest<br>console.log(greetUser(&quot;Haiiru&quot;); // Output: Hello, Haiiru</pre><h3>Return Values</h3><p>A function can return a value using the return keyword. Once the return statement is executed, the function stops executing.</p><pre>function subtract(a, b) {<br>    return a - b;<br>}<br><br>const result = subtract(10, 5);<br>console.log(result);  // Output: 5</pre><h3>Function Scope</h3><p>In JavaScript, variables declared inside a function are local to that function, meaning they cannot be accessed outside of it. This is known as <strong>function scope</strong>.</p><pre>function example() {<br>    let localVariable = &quot;I&#39;m local!&quot;;<br>    console.log(localVariable);  // Accessible here, Output: I&#39;m Llocal!<br>}<br><br>console.log(localVariable);  // Error: localVariable is not defined</pre><h3>Closures</h3><p>A <strong>closure</strong> occurs when a function “remembers” its lexical scope, even after it is executed outside of that scope. Closures allow functions to access variables from an outer function even after that function has finished execution.</p><pre>function outer() {<br>    let count = 0;<br>    return function() {<br>        count++;<br>        return count;<br>    };<br>}<br><br>const increment = outer();<br>console.log(increment());  // Output: 1<br>console.log(increment());  // Output: 2</pre><h3>Callback Functions</h3><p>A <strong>callback function</strong> is a function passed as an argument to another function. Callbacks allow you to execute a function after another function has finished execution.</p><pre>function processUserInput(callback) {<br>    const name = prompt(&quot;Please enter your name.&quot;);<br>    callback(name);<br>}<br><br>function greet(name) {<br>    console.log(&quot;Hello, &quot; + name);<br>}<br><br>processUserInput(greet);  // Executes greet after getting user input</pre><h3>Best Practices for Using Functions</h3><p>Here are some tips to follow when writing functions:</p><ol><li><strong>Keep Functions Small</strong>: Break complex logic into smaller functions.</li><li><strong>Use Descriptive Names</strong>: Function names should be clear about what the function does.</li><li><strong>Avoid Side Effects</strong>: Functions should ideally return values rather than modifying external state.</li><li><strong>Use Default Parameters</strong>: This can simplify your code by avoiding checks for undefined.</li><li><strong>Use Arrow Functions for Short Callbacks</strong>: They are concise and help with clean syntax.</li></ol><h3>Conclusion</h3><p>Functions are a powerful tool in JavaScript, providing structure, reusability, and modularity to your code. By mastering different types of functions and applying best practices, you can write more efficient, readable, and maintainable JavaScript code. Whether you’re just starting or refining your skills, functions are an essential concept in becoming a proficient JavaScript developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffc9074330ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding JavaScript Runtime Environment]]></title>
            <link>https://takadevxyz.medium.com/understanding-javascript-runtime-environment-952acc49119f?source=rss-590e2bb5b926------2</link>
            <guid isPermaLink="false">https://medium.com/p/952acc49119f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[bunjs]]></category>
            <category><![CDATA[runtime-environment]]></category>
            <dc:creator><![CDATA[taka]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 02:32:38 GMT</pubDate>
            <atom:updated>2024-10-12T02:32:38.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6UdV6-66-Gy46MIGxnuNdA.png" /><figcaption>Thumbnail JavaScript Runtime Environment</figcaption></figure><p>JavaScript (JS) is a popular programming language widely used in web development. While many are familiar with its syntax and features, understanding the <strong>JavaScript Runtime Environment (JRE)</strong> is crucial for truly grasping how JavaScript code gets executed. This article will explain what a runtime environment is, how JavaScript runs within different environments, and how various components work together to make JS functional.</p><h3>What is a Runtime Environment?</h3><p>A <strong>runtime environment</strong> provides the necessary tools and resources to execute programs written in a specific programming language. It manages memory, handles input/output operations, and interacts with other system components. For JavaScript, the runtime environment is responsible for executing JavaScript code and managing its interaction with the browser or server.</p><h3>Components of a JavaScript Runtime Environment</h3><p>The JavaScript Runtime Environment includes several key components that work together to run your code. These are:</p><p><strong>JavaScript Engine</strong>: This is the core of the runtime environment. It reads and executes JavaScript code. The engine is responsible for converting the JavaScript code into machine-readable instructions. Popular JS engines include:</p><ul><li><strong>V8</strong> (used by Chrome, Node.js)</li><li><strong>SpiderMonkey</strong> (used by Firefox)</li><li><strong>JavaScriptCore</strong> (used by Safari)</li><li><strong>Bun’s Engine (JavaScriptCore)</strong>: Bun uses <strong>WebKit’s JavaScriptCore engine</strong>, but enhances it with optimizations specific to modern web and server needs. It’s a high-performance engine designed for speed and efficiency.</li></ul><p><strong>Call Stack</strong>: The call stack is a data structure that keeps track of the function calls in the program. When a function is called, it’s added to the stack. Once the function completes, it’s removed from the stack. If functions are nested, the stack helps the engine keep track of which function to execute next.</p><p><strong>Heap</strong>: This is the memory where objects and variables are stored during execution. JavaScript handles memory allocation and garbage collection, which cleans up memory once objects are no longer in use.</p><p><strong>Event Loop</strong>: One of JavaScript’s most powerful features is its ability to handle asynchronous operations like HTTP requests or timeouts. The event loop continuously monitors the <strong>call stack</strong> and <strong>callback queue</strong> to determine what code should be executed next. When asynchronous events (like an API response) occur, the associated callback function is pushed into the callback queue, which the event loop processes once the call stack is empty.</p><p><strong>Web APIs (Browser Environment Only)</strong>: In the browser, JavaScript interacts with various APIs (like fetch or setTimeout) that allow developers to perform tasks like making HTTP requests or setting timers. These APIs are not part of the JavaScript language itself but are provided by the browser as part of its runtime environment.</p><p><strong>Node.js APIs (Server-Side Environment)</strong>: For server-side JavaScript (like in Node.js), the runtime environment includes its own set of APIs. These APIs enable file system access, database interaction, and more. Node.js also uses the V8 engine but extends it with features that are not available in the browser.</p><p><strong>Bun APIs (Server-Side Environment)</strong>: <strong>Bun</strong> is a relatively new, fast JavaScript runtime designed for server-side development, and it also offers its own APIs for enhanced performance and efficiency in modern web applications. Bun focuses on:</p><ul><li><strong>Native TypeScript support</strong>: Unlike Node.js, Bun compiles TypeScript natively without needing a separate transpiler like tsc.</li><li><strong>Bundling and Transpiling</strong>: Bun includes built-in tools for bundling JavaScript and CSS files, reducing the need for additional tools like Webpack or Babel.</li><li><strong>Server-Side Enhancements</strong>: It provides fast file and network operations, offering an optimized experience for building scalable backends.</li></ul><h3>Browser vs. Server Runtime Environment</h3><p>The <strong>browser environment</strong>, <strong>Node.js environment</strong>, and <strong>Bun environment</strong> are the three common runtime environments for JavaScript today:</p><ul><li><strong>Browser Environment</strong>: JavaScript runs within the browser’s context, interacting with the DOM (Document Object Model) and performing client-side tasks like rendering UI or handling user inputs.</li><li><strong>Node.js Environment</strong>: JavaScript runs on a server, where it performs backend tasks such as handling requests, managing databases, or interacting with the operating system.</li><li><strong>Bun Environment</strong>: Built for speed and modern web applications, Bun also runs on the server like Node.js but emphasizes performance, supporting native TypeScript, fast bundling, and optimized async handling. It’s especially designed for developers looking to streamline web development with fewer dependencies.</li></ul><h3>Event Loop in Action: How Asynchronous JavaScript Works</h3><p>JavaScript is single-threaded, meaning it can only execute one task at a time. However, thanks to the event loop, it can handle asynchronous tasks efficiently. Here’s how it works:</p><ul><li>When an asynchronous task (like an HTTP request) is made, the browser, Node.js, or Bun runtime offloads it to a Web API or Node.js/Bun API.</li><li>Once the task is complete, the associated callback function is placed in the callback queue.</li><li>The event loop checks if the call stack is empty. If so, it pulls the next task from the callback queue and pushes it onto the call stack for execution.</li></ul><p>This allows JavaScript to handle tasks like fetching data from a server without blocking the main thread, ensuring smoother performance.</p><h3>Bun: The Next Generation JavaScript Runtime</h3><p><strong>Bun</strong> is gaining attention for its speed and modern features. It aims to replace many tools used in JavaScript development, including Node.js, Webpack, and Babel, all in one package. Here are a few reasons why Bun stands out:</p><ul><li><strong>Performance</strong>: Bun is designed to be fast, from startup to runtime. It improves performance with optimizations in JavaScriptCore, the engine it is built on.</li><li><strong>TypeScript Support</strong>: Unlike Node.js, which requires separate tools to handle TypeScript, Bun compiles TypeScript files natively.</li><li><strong>Built-in Tools</strong>: Bun has built-in support for bundling, transpiling, and handling both JavaScript and CSS, reducing the need for external build tools like Webpack.</li><li><strong>Optimized Server-Side Execution</strong>: Bun’s APIs offer improved performance in areas like file system access, network operations, and async handling, making it ideal for server-side applications.</li></ul><h3>Conclusion</h3><p>The JavaScript Runtime Environment is the behind-the-scenes system that makes JavaScript code work. By understanding its key components — the engine, call stack, heap, event loop, and APIs — you can become a more effective developer. Whether you’re working on the client side in a browser, the server side with Node.js, or exploring new technologies like <strong>Bun</strong>, the runtime environment plays a crucial role in executing your JavaScript code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=952acc49119f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JavaScript: Declaration and Initialization Like a Pro!]]></title>
            <link>https://takadevxyz.medium.com/mastering-javascript-declaration-and-initialization-like-a-pro-44b53cfbccb1?source=rss-590e2bb5b926------2</link>
            <guid isPermaLink="false">https://medium.com/p/44b53cfbccb1</guid>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[fundamental-js]]></category>
            <category><![CDATA[variables-in-javascript]]></category>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[taka]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 03:19:33 GMT</pubDate>
            <atom:updated>2024-09-28T03:19:33.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXTyUgBEyxY7Vh0dN7sJ0g.png" /></figure><p>JavaScript is at the core of every web developer’s toolkit, and variables are the building blocks of every program. But, do you know how to fully harness the power of <strong>declaration</strong> and <strong>initialization</strong> in JavaScript?</p><p>If you’re ready to stop guessing and start mastering these foundational concepts, read on! We’ll demystify <strong>var</strong>, <strong>let</strong>, and <strong>const</strong>, show you how to leverage them for clean, maintainable code, and avoid the pitfalls that even experienced developers fall into.</p><h3>What Exactly Are Declaration and Initialization?</h3><p>Before diving into the code, let’s break it down simply:</p><ul><li><strong>Declaration</strong>: This is where we tell JavaScript, “Hey, we are creating a variable here!”</li><li><strong>Initialization</strong>: This is where we say, “Here’s the value we are assigning to that variable.”</li></ul><p>Here’s the kicker: while these two can happen together, they don’t always. And knowing the difference is your key to preventing unexpected bugs and tricky errors.</p><h3>Meet the Keywords: var, let, and const</h3><p>JavaScript gives you three ways to declare variables — each with its own rules and quirks. Let’s break them down, one at a time. You can read for more specific topic about the keywords in my other article here -&gt;</p><p><a href="https://medium.com/@takachan0012/understanding-variables-in-javascript-var-let-and-const-470639493015">https://medium.com/@takachan0012/understanding-variables-in-javascript-var-let-and-const-470639493015</a></p><h3>1. var: The Old Guard</h3><p>Before ES6, var was the only way to declare variables in JavaScript. It’s still used, but should you?</p><p><strong>-&gt; Scope</strong>: var is function-scoped, meaning if you declare it inside a function, it won’t exist outside. But declare it in a loop or an if block, and <strong>surprise</strong>—it leaks out into the broader scope!</p><pre>if (true) {<br>    var x = 5;<br>}<br>console.log(x); // Outputs: 5 (uh-oh)</pre><p><strong>-&gt; Hoisting</strong>: var is <strong>hoisted</strong>, meaning it can be used before it’s actually declared. But here’s the catch—it’ll be undefined until it’s assigned a value.</p><pre>console.log(y); // Outputs: undefined<br>var y = 10;</pre><h3>2. let: The Modern Favorite</h3><p>Introduced in ES6, let is the new standard. It fixes a lot of var&#39;s quirks and makes your code more predictable.</p><p>-&gt; <strong>Scope</strong>: Unlike var, let is block-scoped. Declare a let inside an if, for, or any other block, and it stays right where you put it—no leaking out into the global scope.</p><pre>if (true) {<br>    let z = 10;<br>}<br>console.log(z); // ReferenceError: z is not defined</pre><p>-&gt; <strong>No Hoisting Surprises</strong>: Unlike var, let is not accessible before it’s declared, so you avoid the common <strong>&quot;undefined&quot;</strong>.</p><h3>3. const: The Immutable Hero</h3><p>Do you want variables that don’t change? Say hello to <strong>const</strong>! This keyword is also block-scoped, like let, but there’s a catch: <strong>once you set its value, you can’t change it.</strong></p><p><strong>-&gt; Must Initialize</strong>: You cannot declare a const without giving it a value upfront. If you try, JavaScript will throw an error.</p><pre>const a; // SyntaxError: Missing initializer</pre><p>-&gt; <strong>No Reassignment</strong>: Once assigned, const won’t let you change its value. This makes your code predictable and avoids accidental value changes.</p><pre>const b = 20;<br>b = 30; // TypeError: Assignment to constant variable</pre><p>However, note that const doesn’t make objects or arrays completely immutable—it just prevents reassigning the variable. The contents of an object or array declared with const can still be modified:</p><pre>const person = { name: &quot;Taka&quot; };<br>person.name = &quot;Haiiru&quot;; // Works fine</pre><h3>Declaration Without Initialization? Yes, You Can!</h3><p>Sometimes, you might want to declare a variable without giving it a value right away. With let and var, this is perfectly fine. But be warned—this approach has different consequences depending on which keyword you use:</p><pre>let x;<br>var y;<br>const z; // This throws an error—const MUST be initialized</pre><p>With var, if you forget to initialize, the value will default to undefined. Same with let, but with better scoping rules. const? Forget it—you <strong>must</strong> initialize it when you declare it.</p><h3>Best Practices for Declaring and Initializing Variables</h3><p>Now that you know the differences, let’s dive into best practices that can make your code more readable, maintainable, and bug-free!</p><ul><li><strong>Use </strong><strong>let and </strong><strong>const—Avoid </strong><strong>var!</strong> let and const give you more predictable behavior than var. The latter’s function-scoping and hoisting often lead to confusing, buggy code.</li><li><strong>Prefer </strong><strong>const for Immutable Values , </strong>Use const by default unless you know the variable needs to change. This helps prevent accidental reassignments and makes your intentions clear to anyone reading your code.</li></ul><pre>const MAX_USERS = 100;<br>let userCount = 10;</pre><ul><li><strong>Declare Variables at the Top of Their Scope, </strong>Keeping all your variable declarations at the top of their scope makes your code easier to understand.</li><li><strong>Be Careful with Object and Array Mutations, </strong>Just because const locks the variable doesn’t mean the contents of arrays or objects are safe. If you need immutability, use libraries or techniques like <strong>Object.freeze()</strong>.</li></ul><h3>Conclusion: Take Control of Your Variables!</h3><p>Understanding <strong>declaration</strong> and <strong>initialization</strong> is fundamental to writing better JavaScript code. Now that you’ve got the inside scoop on <strong>var</strong>, <strong>let</strong>, and <strong>const</strong>, you’re ready to start writing cleaner, more efficient code.</p><p>So go ahead, start declaring and initializing like a pro! Your future self (and your team) will thank you for it. :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44b53cfbccb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Variables in JavaScript: var, let, and const]]></title>
            <link>https://takadevxyz.medium.com/understanding-variables-in-javascript-var-let-and-const-470639493015?source=rss-590e2bb5b926------2</link>
            <guid isPermaLink="false">https://medium.com/p/470639493015</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[understanding]]></category>
            <category><![CDATA[variables-in-javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[taka]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 04:46:45 GMT</pubDate>
            <atom:updated>2024-09-09T04:46:45.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Understanding Variables in JavaScript" src="https://cdn-images-1.medium.com/max/1024/1*iKxWT3V-pgsFxdnRuUmWqw.png" /></figure><p>In JavaScript, variables are fundamental for storing data. There are three main ways to declare variables: using var, let, and const. Each has its own behavior and use cases, and choosing the right one is crucial for writing efficient and bug-free code.</p><h3>1. Declaring Variables with var</h3><p>The var keyword was used widely in earlier versions of JavaScript. However, it has some quirks related to scope that can lead to unexpected behavior.</p><ul><li><strong>Scope</strong>: var has function scope, meaning it is accessible within the entire function it is declared in, but not outside of it. If declared outside a function, it&#39;s globally scoped.</li><li><strong>Re-declaration</strong>: Variables declared with var can be redeclared and updated.</li></ul><p><strong>Example:</strong></p><pre>var name = &quot;Takashi&quot;;<br>name = &quot;Haiiru&quot;; // Variable can be updated<br>var name = &quot;Takachan&quot;; // Variable can be redeclared<br>console.log({name}); // Outputs: {name: &quot;Takachan&quot;}</pre><h3>2. Declaring Variables with let</h3><p>let was introduced in ES6 (ECMAScript 2015) and is now the preferred way to declare variables when their values need to change.</p><ul><li><strong>Scope</strong>: let is block-scoped, meaning it&#39;s only accessible within the block {} where it is declared.</li><li><strong>Re-declaration</strong>: You cannot redeclare a variable using let in the same scope, which helps avoid accidental overwriting.</li></ul><p><strong>Example:</strong></p><pre>let name = &quot;Takashi&quot;;<br>name = &quot;Haiiru&quot;; // Variable can be updated<br>// let name = &quot;Takachan&quot;; // Error: Cannot redeclare &#39;name&#39; in the same scope<br>console.log({name}); // Outputs: {name: &quot;Haiiru&quot;}</pre><h3>3. Declaring Variables with const</h3><p>const is also block-scoped, but unlike let, it is used to declare variables whose values should remain constant. Once a value is assigned to a const variable, it cannot be changed.</p><ul><li><strong>Immutability</strong>: You cannot update or redeclare a variable declared with const.</li><li><strong>Objects and Arrays</strong>: For objects and arrays declared with const, their properties or items can be modified, but the reference to the object or array cannot change.</li></ul><p><strong>Example:</strong></p><pre>const name = &quot;Takashi&quot;;<br>// name = &quot;Haiiru&quot;; // Error: Assignment to constant variable<br>console.log({name}); // Outputs: {name: &quot;Takashi&quot;}<br><br>// For objects and arrays<br>const person = { name: &quot;Takashi&quot;, age: 22};<br>person.age = 23; // Property of object can be changed<br>console.log(person.age); // Outputs: 23</pre><h3>4. Best Practices for Using var, let, and const</h3><ul><li><strong>Prefer </strong><strong>const over </strong><strong>let</strong>: Use const by default, as it signals that the variable will not change. This makes your code easier to understand and helps prevent bugs.</li><li><strong>Use </strong><strong>let when the value needs to change</strong>: If the value of the variable is expected to change later in the code, use let.</li><li><strong>Avoid </strong><strong>var</strong>: Due to its function-scoped nature and the potential for redeclaration, var is generally not recommended in modern JavaScript. Stick to let and const for better clarity and block-level scope.</li><li><strong>Descriptive Naming</strong>: Always use meaningful and descriptive names for variables to make your code more readable.</li></ul><p><strong>Example of Best Practices:</strong></p><pre>const maxAttempts = 5; // Constant variable as the value will not change<br><br>for (let i = 0; i &lt; maxAttempts; i++) {<br>  // Using let for loop iteration as the value changes on each iteration<br>  console.log(i);<br>}</pre><h3>Conclusion</h3><p>In modern JavaScript, let and const provide better control over scope and behavior, making code more predictable and easier to maintain. Stick to const for values that won’t change, and use let when they will.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=470639493015" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inserting JavaScript Code into HTML]]></title>
            <link>https://takadevxyz.medium.com/inserting-javascript-code-into-html-c1bbf3fa2665?source=rss-590e2bb5b926------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1bbf3fa2665</guid>
            <category><![CDATA[html5-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[taka]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 04:54:51 GMT</pubDate>
            <atom:updated>2024-08-20T04:54:51.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHQKVsS3SZj9VzKkpe6VWQ.png" /></figure><p>JavaScript can be added to an HTML document in various ways, depending on the needs of your project. In this article, we’ll explore five common methods to insert JavaScript into HTML:</p><ul><li><strong>JavaScript in the </strong><strong>&lt;head&gt; Section</strong></li><li><strong>JavaScript in the </strong><strong>&lt;body&gt; Section</strong></li><li><strong>External JavaScript in the </strong><strong>&lt;head&gt; Section</strong></li><li><strong>External JavaScript in the </strong><strong>&lt;body&gt; Section</strong></li><li><strong>Inline JavaScript</strong></li></ul><h3>1. JavaScript in the &lt;head&gt; Section</h3><p>Placing JavaScript inside the &lt;head&gt; section is useful when you need to run scripts that configure settings or handle events as soon as the page loads. Typically, this method is less common for interactive scripts that affect page content.</p><p><strong>Example:</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;script&gt;<br>        function myFunction(){<br>        document.getElementById(&#39;demo&#39;).innerHTML=&#39;Hello&#39;<br>        }<br>    &lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;p id=&quot;demo&quot;&gt;World&lt;/p&gt;<br>    &lt;button type=&quot;button&quot; onclick=&quot;myFunction()&quot;&gt;Change to Hello&lt;/button&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>2. JavaScript in the &lt;body&gt; Section</h3><p>Placing JavaScript directly within the &lt;body&gt; section is common for scripts that need to interact with the HTML content. The script can be positioned either at the beginning or at the end of the body.</p><ul><li><strong>At the beginning of the body</strong>: May block content rendering.</li><li><strong>At the end of the body</strong>: Recommended for performance, as it ensures all HTML elements are loaded first.</li></ul><p><strong>Example:</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;p id=&quot;demo&quot;&gt;World&lt;/p&gt;<br>    &lt;button type=&quot;button&quot; onclick=&quot;myFunction()&quot;&gt;Change to Hello&lt;/button&gt;<br>    &lt;script&gt;<br>        function myFunction(){<br>        document.getElementById(&#39;demo&#39;).innerHTML=&#39;Hello&#39;<br>        }<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>3. External JavaScript in the &lt;head&gt; Section</h3><p>Linking to an external JavaScript file from the &lt;head&gt; section allows you to keep your code modular and organized. This approach is useful for scripts that should load early but don’t depend on the DOM being fully loaded.</p><p><strong>Example:</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;p id=&quot;demo&quot;&gt;World&lt;/p&gt;<br>    &lt;button type=&quot;button&quot; onclick=&quot;myFunction()&quot;&gt;Change to Hello&lt;/button&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Contents of </strong><strong>script.js:</strong></p><pre>function myFunction(){<br>        document.getElementById(&#39;demo&#39;).innerHTML=&#39;Hello&#39;<br>}</pre><h3>4. External JavaScript in the &lt;body&gt; Section</h3><p>Placing an external JavaScript file at the end of the &lt;body&gt; <strong>is a best practice for performance optimization. </strong>This ensures the HTML content is fully loaded before running the script.</p><p><strong>Example:</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;p id=&quot;demo&quot;&gt;World&lt;/p&gt;<br>    &lt;button type=&quot;button&quot; onclick=&quot;myFunction()&quot;&gt;Change to Hello&lt;/button&gt;<br>    &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>Contents of </strong><strong>script.js:</strong></p><pre>function myFunction(){<br>        document.getElementById(&#39;demo&#39;).innerHTML=&#39;Hello&#39;<br>}</pre><h3>5. Inline JavaScript</h3><p>Inline JavaScript is directly added to HTML elements using the onclick, onmouseover, or other event attributes. While it can be convenient for small tasks, this approach is generally discouraged for larger projects due to poor maintainability and separation of concerns.</p><p><strong>Example:</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;p id=&quot;demo&quot;&gt;World&lt;/p&gt;<br>    &lt;button onclick=&quot;(<br>        function(){<br>        document.getElementById(&#39;demo&#39;).innerHTML=&#39;Hello&#39;<br>        }()<br>        )&quot;&gt;Change to Hello&lt;/button&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Using <strong>external JavaScript</strong> files instead of <strong>internal JavaScript</strong> (embedded within the HTML file) offers several advantages:</p><h3>1. Code Reusability</h3><ul><li>External JavaScript files can be linked to multiple HTML pages, allowing you to reuse the same code across different web pages without duplication.</li></ul><h3>2. Separation of Concerns (Cleaner Code)</h3><ul><li>Separating HTML, CSS, and JavaScript into their own files promotes a clean code structure. HTML handles content, CSS manages styling, and JavaScript deals with behavior. This improves maintainability.</li></ul><h3>3. Easier Maintenance</h3><ul><li>Updates to the JavaScript code can be made in a single file (the external JS file), and the changes will be reflected across all linked HTML pages.</li></ul><h3>4. Better Performance (Caching)</h3><ul><li>External JavaScript files can be cached by the browser. Once a file is loaded, it doesn’t need to be downloaded again until it is updated, reducing load times on subsequent visits.</li></ul><h3>5. Improved Readability and Organization</h3><ul><li>Keeping the HTML file free from inline scripts results in more readable and organized code, which is especially helpful in larger projects.</li></ul><h3>6. Scalability</h3><ul><li>For larger projects, managing code in separate files is crucial. External JavaScript makes it easier to scale projects as complexity grows.</li></ul><h3>7. Collaboration</h3><ul><li>In team environments, separating JavaScript into its own file allows different team members to work on HTML, CSS, and JavaScript simultaneously without conflicts.</li></ul><h3>8. Debugging and Testing</h3><ul><li>Having JavaScript in a separate file simplifies debugging and testing, as issues can be isolated more easily in a dedicated environment.</li></ul><h3><strong>Conclusion</strong></h3><p>Each method of inserting JavaScript into HTML serves different purposes and scenarios. For small, quick scripts, inline JavaScript might be enough, but for larger projects, external JavaScript files offer better maintainability and performance. Where you place your JavaScript — whether in the &lt;head&gt; or &lt;body&gt;—can significantly impact the performance and behavior of your web page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1bbf3fa2665" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>