<?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 Anurag Joshi on Medium]]></title>
        <description><![CDATA[Stories by Anurag Joshi on Medium]]></description>
        <link>https://medium.com/@itsanuragjoshi?source=rss-736e5a078bf6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1_BxCWSPMWSGZ-6PdyWmwA.png</url>
            <title>Stories by Anurag Joshi on Medium</title>
            <link>https://medium.com/@itsanuragjoshi?source=rss-736e5a078bf6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:41:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@itsanuragjoshi/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[Polyfill for forEach() in JavaScript]]></title>
            <link>https://medium.com/@itsanuragjoshi/polyfill-for-foreach-in-javascript-1c2a098db3b1?source=rss-736e5a078bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c2a098db3b1</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Anurag Joshi]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 07:29:55 GMT</pubDate>
            <atom:updated>2024-11-09T11:05:38.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5L39vStDHiKdHTqa" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In JavaScript, the forEach() method allows you to iterate over array elements and execute a provided function for each element. It&#39;s a handy tool that every JavaScript developer uses.</p><h3>Syntax</h3><pre>forEach(callbackFn)<br>forEach(callbackFn, thisArg)</pre><h4>Parameters of forEach()</h4><p><strong>callbackFn</strong> (Required): A function executed for each element in the array</p><p><strong>Arguments passed to </strong><strong>callbackFn:<br></strong><strong>element</strong>: The current element being processed<br><strong>index</strong>: The index of the current element<br><strong>array</strong>: The array forEach() was called on</p><p><strong>thisArg</strong> (Optional): A value to use as this when executing callbackFn</p><h4>Return Value</h4><p>forEach() always returns undefined</p><p>However, what happens if forEach() isn’t available?</p><p>Maybe you&#39;re working in an older browser or in an environment where it’s missing.</p><p>That’s where <strong>polyfills</strong> come into play!</p><blockquote>A polyfill is like a safety net — it ensures that even if a feature doesn’t exist natively, we can replicate its behavior.</blockquote><p>Let’s break this down in two levels, depending on the expertise expected for different roles.</p><h3>Level 1 — Simple (SDE1) Implementation</h3><p>You’ve been asked to implement a simple polyfill for forEach() to ensure compatibility in case the method isn’t natively available.</p><p>Here’s the code:</p><pre>// Simulate browser incompatibility<br>Array.prototype.forEach = null;<br><br>// Level 1<br>if (!Array.prototype.forEach) {<br>    Array.prototype.forEach = function(callbackFn) {<br>        for (let index = 0; index &lt; this.length; index++) {<br>            callbackFn(this[index]);<br>        }<br>    };<br>}</pre><h4>How It Works?</h4><ol><li><strong>Check for Existence</strong>: The if (!Array.prototype.forEach) ensures that we only define forEach if it doesn&#39;t already exist</li><li><strong>Define </strong><strong>forEach()</strong>: We define forEach as a function that takes a callbackFn</li><li><strong>Iterate Over Array</strong>: Using a for loop, we go through each element of the array</li><li><strong>Call the Callback</strong>: For each element, the callback function (callbackFn) is executed</li></ol><h4>Example Usage</h4><pre>const arr = [1, 2, 3, 4];<br><br>arr.forEach(function(element) {<br>    console.log(element * 2);<br>}); // Output: 2, 4, 6, 8</pre><h4>What This Covers?</h4><ul><li>Basic iteration</li><li>Simulating how forEach works in modern JavaScript</li></ul><h4>Limitations:</h4><ul><li><strong>No error handling</strong>: What if callbackFn is missing or not a function?</li><li><strong>No </strong><strong>this context support</strong>: The forEach method allows an optional thisArg to set the context of this inside the callback, but this implementation doesn&#39;t handle that</li></ul><h3>Level 2 — Advanced (SDE2/3) Implementation</h3><p>Now let’s level up.</p><p>What if we want to impress interviewers by mimicking more of forEach&#39;s native behavior, including error handling and support for a this context?</p><p>Here’s a more advanced implementation:</p><pre>// Level 2<br>if (!Array.prototype.forEach) {<br>    Array.prototype.forEach = function(callbackFn, thisArg) {<br>        // Error handling<br>        if (!callbackFn) <br>            throw &#39;TypeError: missing argument 0 when calling function Array.prototype.forEach&#39;;<br>        if (typeof callbackFn !== &#39;function&#39;) <br>            throw `TypeError: ${callbackFn} is not a function`;<br><br>        // Iterate over array<br>        for (let index = 0; index &lt; this.length; index++) {<br>            if (this.hasOwnProperty(index)) {<br>                callbackFn.call(thisArg, this[index], index, this);<br>            }<br>        }<br>    };<br>}</pre><h4>What’s Different in Level 2?</h4><ol><li><strong>Error Handling</strong>: Throws an error if callbackFn isn’t provided or not a function</li><li><strong>Context Binding (</strong><strong>thisArg)</strong>: The call() method binds the thisArg (if provided) as the this context inside the callbackFn</li><li><strong>Additional Arguments</strong>: The callbackFn receives element, index, and array as arguments, just like the native forEach</li><li><strong>Property Check</strong>: The hasOwnProperty check ensures that only the array&#39;s own elements (not inherited ones) are processed.</li></ol><h4>Example Usage</h4><pre>const arr = [1, 2, 3, 4];<br><br>// Testing with a valid function<br>arr.forEach(function(element) {<br>    console.log(element * 2);<br>});<br>// Output: 2, 4, 6, 8<br><br>arr.forEach(123);  // Uncaught TypeError: 123 is not a function<br>arr.forEach();     // Uncaught TypeError: missing argument 0</pre><h4>Why This is Impressive?</h4><ul><li><strong>Mimics Native Behavior</strong>: This implementation closely resembles the built-in forEach</li><li><strong>Error Resilience</strong>: Handles incorrect usage gracefully, as the native method does</li><li><strong>Professional Grade</strong>: Shows deeper understanding of how JavaScript methods manage context and handle edge cases</li></ul><h3>Conclusion</h3><p>Implementing a polyfill for forEach() demonstrates your understanding of JavaScript fundamentals and showcases your ability to build robust, backward-compatible solutions. Here&#39;s a quick summary:</p><ul><li><strong>Level 1</strong>: Focuses on basic functionality.</li><li><strong>Level 2</strong>: Includes error handling, thisArg, and full support for callbackFn arguments.</li></ul><p>Mastering both levels ensures you’re prepared for a range of interview scenarios, from junior roles to senior ones. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c2a098db3b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Center a Div — Simplified Solutions for Developers]]></title>
            <link>https://medium.com/@itsanuragjoshi/how-to-center-a-div-simplified-solutions-for-developers-f24b5061edb1?source=rss-736e5a078bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f24b5061edb1</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Anurag Joshi]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 18:15:32 GMT</pubDate>
            <atom:updated>2024-04-26T18:16:51.672Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Center a Div — Simplified Solutions for Developers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDI6OFqRO-dWXbatltyqBw.png" /></figure><p>Hey there, fellow web developer!</p><p>Have you ever found yourself scratching your head over how to center a div?</p><p>Don’t worry, you’re not alone! In fact, it’s one of the most frequently asked questions in web development interviews.</p><p>Whether you’re just starting out or you’ve been coding for years, mastering the various methods of centering a div is key to creating beautifully balanced layouts.</p><p>In this guide, we’ll break down div centering into simple steps.</p><p>We’ll explore four different techniques, breaking down each method step by step. By the end of this journey, you’ll be equipped with the knowledge and confidence to tackle this common challenge with ease.</p><p>Let’s get started and make div centering simple!</p><h3>Starter Code</h3><p>Let’s begin with our starter code:</p><pre>&lt;section&gt;<br>    &lt;div&gt;<br>        &lt;p&gt;Center Me!&lt;/p&gt;<br>    &lt;/div&gt;<br>&lt;/section&gt;</pre><pre>section {<br>    width: 400px;<br>    height: 400px;<br>    border: 1px solid blue;<br>}<br><br>div {<br>    max-width: fit-content;<br>    background-color: pink;<br>    border: 1px solid red;<br>    padding: 20px;<br>}</pre><p>This is what it looks like on the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nqb1CnvBh-30Bn4dD12oyw.png" /></figure><p>Currently, the div is aligned to the top-left corner of the section. Our objective is to center the div both horizontally and vertically within the section.</p><p>To achieve our goal, we’ll employ some CSS techniques to center the div within its parent section.</p><p>This is what we want to achieve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnzhOujUEo-TjbNjGQTuag.png" /></figure><h3><strong>Method 1 — Using TABLE and MARGIN</strong></h3><p>In this method, we utilize CSS tables to center the div both horizontally and vertically within its parent container.</p><p>We’ll add the following CSS to the starter code:</p><pre>section {<br>    display: table-cell;<br>    vertical-align: middle;<br>}<br><br>div {<br>    margin: 0 auto;<br>}</pre><p>By setting the parent container (section) to display: table-cell, we establish a table layout context. Then, vertical-align: middle ensures vertical alignment. Additionally, by applying margin: 0 auto to the child div (div), we achieve horizontal centering.</p><p>This method is reliable and widely supported across browsers.</p><h3>Method 2 — <strong>Using POSITION and TRANSFORM</strong></h3><p>This approach utilizes absolute positioning and the transform property to center the div.</p><p>We’ll add the following CSS to the starter code:</p><pre>section {<br>    position: relative;<br>}<br><br>div {<br>    position: absolute;<br>    top: 50%;<br>    left: 50%;<br>    transform: translate(-50%, -50%);<br>}</pre><p>By setting the parent container (section) to position: relative, we establish a positioning context for the child div (div). Then, by applying position: absolute, along with top: 50% and left: 50%, we move the div to the center of its parent. Finally, using transform: translate(-50%, -50%), we adjust the div&#39;s position to perfectly center it both horizontally and vertically.</p><h3>Method 3 — <strong>Using FLEXBOX</strong></h3><p>One simple way to center the div is by using Flexbox. Flexbox provides a powerful and flexible way to layout elements within a container.</p><p>We’ll add the following CSS to the starter code:</p><pre>section {<br>    display: flex;<br>    justify-content: center;<br>    align-items: center;<br>}</pre><p>By setting the parent container (section) to display: flex and applying justify-content: center and align-items: center, we effortlessly center the child div (div) both horizontally and vertically.</p><p>Flexbox is a modern approach to layout and is well-supported across modern browsers.</p><h3>Method 4 — Using GRID</h3><p>CSS Grid is another modern layout method that offers precise control over the positioning of elements.</p><p>We’ll add the following CSS to the starter code:</p><pre>section {<br>    display: grid;<br>    place-content: center;<br>}</pre><p>By setting the parent container (section) to display: grid and using the shorthand place-content: center, we center the child div (div) within its parent container.</p><p>Alternatively, you can achieve the same effect by using justify-content: center; and align-items: center; separately.</p><p>CSS Grid provides a robust and intuitive way to create complex layouts, making it a valuable tool in a developer&#39;s toolkit.</p><h3>Conclusion</h3><p>In wrapping up, we’ve covered four simple ways to center a div on a webpage. Whether you like the straightforwardness of Flexbox, the precise control of CSS Grid, or other methods, there’s an option that fits your style. By grasping these techniques, you’ll be better at crafting neat and balanced layouts for your websites.</p><p>Keep experimenting to find what works best for you. With a bit of practice, you’ll nail div centering like a pro!</p><p>Happy reading 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f24b5061edb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP Made Simple: Understanding the Basics of Web Communication]]></title>
            <link>https://medium.com/@itsanuragjoshi/http-made-simple-understanding-the-basics-of-web-communication-263c33475f3b?source=rss-736e5a078bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/263c33475f3b</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Anurag Joshi]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 17:32:31 GMT</pubDate>
            <atom:updated>2024-04-22T17:36:36.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DZ4n47Ohkq6T_GPq" /><figcaption>Photo by <a href="https://unsplash.com/@yapics?utm_source=medium&amp;utm_medium=referral">Leon Seibert</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>HTTP, or Hypertext Transfer Protocol, is like a set of rules for how computers talk to each other on the internet.</blockquote><p>Imagine you’re sending a letter to a friend. You have to write the address, put the letter in an envelope, and then the postal service delivers it. HTTP is like those instructions, but for computers.</p><p>When you visit a website, your computer sends a request to the website’s computer asking for the webpage. HTTP tells your computer how to ask for that webpage, and then it helps the website’s computer know how to send it back to you. It’s like a secret language that computers use to understand each other and share information. So, every time you browse the web, you’re actually using HTTP to communicate with websites and get the content you want.</p><h3>HTTP Unpacked — Understanding How Instagram Sends Your Photos</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*92JbPpqL3Cfn95rN" /><figcaption>Photo by <a href="https://unsplash.com/@kate_torline?utm_source=medium&amp;utm_medium=referral">Kate Torline</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s break down the process of sharing a photo on Instagram with a friend who lives far away, focusing on how Hypertext Transfer Protocol (HTTP) comes into play:</p><h4>Hypertext</h4><ol><li><strong>Posting the Photo:</strong> You start by uploading the photo to your Instagram account. When you post the photo, you might add a <strong>caption </strong>and maybe <strong>tag </strong>some friends in the photo. These elements are like hypertext links within the Instagram platform. They provide additional information or connections to other users or content.</li><li><strong>Exploring Related Content:</strong> Your friend, who lives far away, wants to see the photo you posted. They open their Instagram app and navigate to your profile. When they tap on the photo, it’s like clicking on a hypertext link in a book. Instead of being limited to just that photo, they can explore related content like comments, likes, and other photos you’ve posted.</li></ol><h4>Transfer</h4><ol><li><strong>Sending the Photo:</strong> When you uploaded the photo to Instagram, your device initiated a transfer process. The photo was broken down into smaller pieces called <strong>packets</strong>, similar to breaking a large package into smaller parcels for easier shipping. These packets are then sent over the internet to Instagram’s servers.</li><li><strong>Receiving the Photo:</strong> When your friend opens Instagram and taps on your photo, their device sends a request to Instagram’s servers, asking for the photo data. The servers then transfer the photo data back to your friend’s device in the form of packets. It’s like the postal service delivering the package (photo) from Instagram’s servers to your friend’s device.</li></ol><h4>Protocol</h4><ol><li><strong>Following the Protocol:</strong> Behind the scenes, both your device and Instagram’s servers follow the rules laid out by the Hypertext Transfer Protocol (HTTP). This protocol defines <strong>how data should be formatted</strong>, <strong>how requests and responses should be structured</strong>, and <strong>how devices should communicate with each other</strong>.</li><li><strong>Ensuring Smooth Communication:</strong> HTTP ensures that your device and Instagram’s servers speak the same language. It defines how your device should send requests for data, how Instagram’s servers should process those requests, and how the requested data should be transferred back to your device. It’s like having a rulebook that guides the entire process, making sure that data transfer happens smoothly and efficiently.</li></ol><p>So, when you share a photo on Instagram with a friend who lives far away, HTTP enables the seamless transfer of data between your device and Instagram’s servers. Hypertext links within the Instagram platform allow for easy navigation and exploration of related content, while the transfer process ensures that the photo reaches your friend’s device securely and efficiently, all while following the rules/protocols laid out by the HTTP.</p><h3>HTTPS — Keeping Your Photos Safe</h3><p>When you share photos on Instagram, you want them to reach your friend safely, right? Think of HTTP as sending your photos like regular mail. You put them in an envelope and send them off. It’s simple and gets the job done, but there’s a small risk of someone peeking inside the envelope while it’s on its way.</p><p>Now, imagine using HTTPS or<strong> Hypertext Transfer Protocol Secure</strong>. It’s like sending your photos in a special, locked envelope, handled by a trusted courier. With HTTPS, your photos are scrambled into a secret code before they’re sent, so even if someone tries to look inside the envelope, they can’t understand what they’re seeing. It’s like having a secret language only you and your friend understand.</p><h4>HTTPS vs HTTP</h4><ol><li><strong>Encryption:</strong> HTTPS scrambles your data into a secret code, while HTTP sends it as plain text. So, even if someone tries to snoop on your photos while they’re traveling through the internet, they won’t be able to understand them if you’re using HTTPS.</li><li><strong>Security:</strong> HTTPS makes sure your photos are safe and sound on their journey to your friend. It’s like having a security guard checking every step of the way to make sure no one messes with your photos. HTTP doesn’t have this extra protection, so there’s a tiny chance someone could tamper with your photos while they’re on the move.</li><li><strong>Trust:</strong> Websites that use HTTPS are like trusted shops with security cameras and guards. You know they’re safe to visit because they have a little padlock icon 🔒 in the address bar. HTTP sites don’t have this extra security, so it’s a bit like visiting a shop without any security measures in place — you’re not quite sure if it’s safe.</li></ol><p>In simple terms, HTTPS adds an extra layer of protection to your photos when you share them on Instagram. It’s like putting them in a locked envelope and handing them to a trusted courier, ensuring they reach your friend safe and sound. So, the next time you share a photo on Instagram, look out for the little padlock icon in the address bar — it means your photos are traveling securely.</p><h3>Client-Server Model — Establishing Connections</h3><h4><strong>Client-Server Interaction</strong></h4><p>Imagine you’re at home, wanting to share a photo with your friend who lives across town. In this scenario, your smartphone acts as the client, while Instagram’s servers act as the server. When you select the photo you want to share and tap the “Share” button in the Instagram app, your phone sends a request to Instagram’s servers, asking them to upload and share the photo.</p><h4><strong>Request and Response</strong></h4><p>Your phone sends a request to Instagram’s servers, saying something like, “Hey, can you please upload this photo to my profile?” Instagram’s servers then process this request, checking things like if the photo meets their guidelines and if your account has the necessary permissions to post. Once everything checks out, Instagram’s servers respond with a confirmation message, letting your phone know that the photo has been successfully shared. Once shared, the photo is visible to all followers, including your friend.</p><h4><strong>Viewing the Photo</strong></h4><p>When your friend sees the photo, they tap on it to see it better. Their phone (client) asks Instagram’s servers for all the details (such as the image file, comments, and likes) about the photo. Instagram’s servers quickly gather everything and send it back to your friend’s phone, so they can see the photo up close.</p><p>This way, the client-server model in HTTP facilitates the sharing of photos between you and your friend, allowing you to stay connected and share moments, even if you’re physically apart.</p><h3>HTTP Headers — Metadata for Smooth Communication</h3><p>Imagine you’re sending a letter. The content of the letter itself is like the actual data you’re sending, while the address, postage stamps, and other details on the envelope are like the headers. They provide crucial information about the letter — where it’s going, who it’s from, and how it should be handled.</p><p>HTTP headers are like labels on envelopes for your internet requests and responses. It contains important information about the data being sent or received.</p><p>HTTP headers are metadata, serving as key-value pairs. Each key (such as “Content-Type” or “User-Agent”) corresponds to a value (like “text/html” or “Mozilla/5.0”). They specify crucial information like content type, browser details, and caching behavior, facilitating smooth communication between clients and servers on the web.</p><h4>Why are HTTP headers required?</h4><p>Well, they help computers understand each other better. For example, they can tell a server who you are, what kind of data you’re sending or receiving, and how to handle that data.</p><p>HTTP headers are like notes attached to your internet requests and responses, providing important instructions and details.</p><p><strong>Authentication:</strong> Think of headers as a password that allows you to access certain areas on a website. They help servers confirm your identity, ensuring you’re allowed to view or do certain things.</p><p><strong>Caching:</strong> Headers tell your browser and servers whether they can save copies of web pages. This helps speed up your browsing because your browser can reuse saved copies instead of loading everything from scratch each time.</p><p><strong>Managing States:</strong> Headers help keep track of your interactions with websites. For example, they can remember your preferences or where you left off in a game, making your experience smoother and more personalized.</p><p>In simple terms, HTTP headers make sure your online experience is safe, fast, and tailored to your needs</p><h4>Types of HTTP Headers</h4><p>Now, let’s talk about some types of headers:</p><ol><li><strong>Request Headers from Client:</strong> When your device asks a server for something, like loading a webpage or sending a photo on Instagram, it attaches request headers. These headers might include information like your device type, the language you prefer, or even your login details to prove it’s really you.</li><li><strong>Response Headers from Server:</strong> When the server sends back a response, like loading a webpage or confirming that your photo was uploaded successfully on Instagram, it includes response headers. These headers can provide details about the server itself, like its type or version, and instructions on how to handle the data it’s sending back.</li><li><strong>Representation Headers — Encoding/Compression:</strong> Let’s say you’re sending a letter to your friend. You might choose to write it in English, Spanish, or even encode it in a secret code. Similarly, representation headers specify how the data is encoded or compressed. For example, if your photo is too big, Instagram might compress it before sending it to save bandwidth.</li><li><strong>Payload Headers — Data:</strong> Finally, think of the payload headers as labels on individual items inside your package. They tell you what’s inside each box. In our Instagram analogy, the payload headers would specify details about the actual data being sent, like the image file format or the size of the photo.</li></ol><h4>Some Common HTTP Headers</h4><p><strong>Accept:</strong> This header tells the server what kind of response the client can accept. For example, “application/json” indicates that the client prefers JSON-formatted responses.</p><p><strong>User-Agent:</strong> The User-Agent header identifies the software making the HTTP request. It typically includes information about the client’s operating system, browser, and version.</p><p><strong>Authorization:</strong> When a client needs to access restricted resources, it includes the Authorization header with a token. The token could be a username and password, a JWT (JSON Web Token), or another authentication mechanism.</p><p><strong>Content-Type:</strong> This header specifies the type of data being sent in the request or response body. For instance, “application/json” indicates JSON data, while “text/html” indicates HTML content.</p><p><strong>Cookie:</strong> When a server wants to remember information about a client’s session, it sends a Cookie header with a unique identifier. The client then includes this identifier in subsequent requests to maintain the session state.</p><p><strong>Cache-Control:</strong> This header provides directives to control caching behavior. It tells caches how to store and reuse responses, such as whether to cache the response and for how long.</p><p><strong>CORS (Cross-Origin Resource Sharing):</strong> CORS headers determine whether a client-side web application is allowed to make requests to a server from a different origin (domain). These headers include <strong>Access-Control-Allow-Origin</strong>, <strong>Access-Control-Allow-Methods</strong>, and others.</p><p><strong>Security:</strong> Various security-related headers help protect against common web vulnerabilities. Examples include <strong>Strict-Transport-Security (HSTS)</strong> for enforcing HTTPS usage, <strong>X-Content-Type-Options</strong> for preventing MIME-sniffing attacks, and <strong>Content-Security-Policy</strong> for mitigating cross-site scripting (XSS) attacks.</p><h3>HTTP Request Methods — Interacting with Servers</h3><p>Think of HTTP request methods as the different buttons you use while browsing Instagram. Each button helps you do something specific, just like each HTTP request method helps you perform a particular action with Instagram’s servers.</p><p>Let’s break it down:</p><ol><li><strong>GET</strong>: Think of this as browsing through Instagram. When you open the app, you’re using the GET method to retrieve data, like photos and comments, from Instagram’s servers. It’s like asking Instagram to show you what’s on your feed.</li><li><strong>POST</strong>: Imagine you’re uploading a new photo to share on Instagram. You use the POST method to send your photo and caption to Instagram’s servers. It’s like giving Instagram a new photo to add to your profile.</li><li><strong>DELETE</strong>: Suppose you want to remove a comment you made on someone else’s post. You’d use the DELETE method to ask Instagram’s servers to delete that comment. It’s like asking Instagram to erase your comment from the post.</li><li><strong>PUT</strong>: Let’s say you want to update your Instagram bio with new information. You’d use the PUT method to send your updated bio text to Instagram’s servers. It’s like telling Instagram to replace your old bio with the new one.</li><li><strong>PATCH</strong>: Imagine you want to edit the caption of a photo you posted. You’d use the PATCH method to send the updated caption to Instagram’s servers. It’s like asking Instagram to make a small change to your post’s caption.</li><li><strong>HEAD</strong>: Suppose you’re checking if someone has liked your latest photo. You’d use the HEAD method to ask Instagram’s servers to send you just the headers (metadata) about that photo, like the number of likes, without actually fetching the entire photo. It’s like peeking at the number of likes without seeing the photo itself.</li><li><strong>OPTIONS</strong>: Let’s say you want to see what actions you can perform on a particular post, like editing or deleting it. You’d use the OPTIONS method to ask Instagram’s servers for a list of available actions. It’s like asking Instagram, “What can I do with this post?”</li><li><strong>TRACE</strong>: Imagine you’re trying to diagnose a connection issue with Instagram. You’d use the TRACE method to send a request that gets echoed back by Instagram’s servers. It’s like sending a message and having Instagram repeat it back to you to check if it’s received correctly.</li><li><strong>CONNECT</strong>: Suppose you’re accessing Instagram through a proxy server. You’d use the CONNECT method to establish a connection with the proxy server, which then forwards your requests to Instagram’s servers. It’s like setting up a secure tunnel between you and Instagram through the proxy server.</li></ol><p>Each of these HTTP request methods serves a specific purpose, allowing users to interact with Instagram’s servers in different ways to perform actions like browsing, uploading, deleting, and updating content on the platform.</p><h3>HTTP Response Status Codes — Understanding Server Communication</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vjhf7HGEan4neOlp" /><figcaption>Photo by <a href="https://unsplash.com/@introspectivedsgn?utm_source=medium&amp;utm_medium=referral">Erik Mclean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>HTTP response status codes are like messages you receive after sending a request to a server. They let you know if your request was successful, if there’s a problem on your end, or if there’s an issue with the server itself. These responses are divided into five categories:</p><ol><li><strong>1xx Informational Responses:</strong> Think of this as the server sending you a message to let you know it’s processing your request. It’s like a receptionist telling you to wait while they find the information you asked for.</li><li><strong>2xx Success Responses:</strong> When you receive a status code in the 200 range, it means your request was successful. It’s like getting a thumbs-up from the server, indicating that everything went as planned.</li><li><strong>3xx Redirection Responses:</strong> If your request needs to go to a different location or webpage, you’ll get a status code in the 300 range. It’s like being redirected to a new address after asking for directions.</li><li><strong>4xx Client Error Responses:</strong> Status codes in the 400 range indicate that there was a problem with your request, such as a typo in the URL or trying to access a restricted page. It’s like getting an error message when you type in the wrong website address.</li><li><strong>5xx Server Error Responses:</strong> If the server encounters an issue while processing your request, you’ll receive a status code in the 500 range. It’s like getting a message from the server saying, “Sorry, we’re having technical difficulties right now.”</li></ol><h4>Some Common HTTP Response Status Codes</h4><p>Now, let’s look at some common status codes:</p><p><strong>100 Continue:</strong> You’ve sent a message to a friend on Instagram, and they respond with a “Got it! I’ll reply soon.”</p><p><strong>102 Processing:</strong> You’ve asked Instagram to upload a video, and it responds with “Working on it! Video upload in progress.”</p><p><strong>200 OK:</strong> You’ve posted a photo on Instagram, and it shows up in your feed with all the likes and comments. Everything went smoothly!</p><p><strong>201 Created:</strong> You’ve requested to create a new Instagram account, and Instagram replies with “Account successfully created! Welcome to Instagram!”</p><p><strong>202 Accepted:</strong> You’ve requested to change your profile picture, and Instagram replies with “Got your request! We’re updating your profile picture.”</p><p><strong>307 Temporary Redirect:</strong> You’re trying to view a friend’s post, but it’s been temporarily moved to a new location. Instagram tells you, “Post moved temporarily! Check out the new location.”</p><p><strong>308 Permanent Redirect:</strong> Similar to 307, but this time Instagram says, “Post moved permanently! Here’s the new location for future reference.”</p><p><strong>400 Bad Request:</strong> You’re trying to comment on a post, but Instagram tells you, “Sorry, we couldn’t understand your comment. Please try again.”</p><p><strong>401 Unauthorized:</strong> You’re trying to view a private account’s posts, but Instagram tells you, “Access denied! You need to follow this account to see their posts.”</p><p><strong>402 Payment Required:</strong> This one isn’t used by Instagram, but it could be like trying to access exclusive content that requires a subscription fee.</p><p><strong>404 Not Found:</strong> You’re trying to view a post that has been deleted or doesn’t exist, and Instagram says, “Sorry, this post isn’t available. It may have been deleted or removed.”</p><p><strong>500 Internal Server Error:</strong> You’re browsing Instagram, but suddenly you encounter an error message saying, “Oops! Something went wrong. We’re working to fix it.”</p><p><strong>504 Gateway Timeout:</strong> You’re trying to send a direct message, but there’s a delay in delivering it. Instagram tells you, “Sorry, we couldn’t send your message right now. Please try again later.”</p><h3>Wrapping Up</h3><p>In conclusion, HTTP, HTTPS, HTTP headers, HTTP request methods, and HTTP response status codes are the fundamental building blocks of web communication. They form the backbone of how data is transferred, secured, and managed across the internet, allowing users to seamlessly interact with websites and services like Instagram.</p><p>By understanding these basic concepts, you gain insight into the inner workings of the online world and how different components come together to create a smooth and efficient browsing experience. So, the next time you share a photo on Instagram or browse your favorite website, remember the intricate system of protocols, rules, and codes working behind the scenes to make it all possible.</p><p>Happy reading 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=263c33475f3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Essentials of HTML5: What You Need to Know]]></title>
            <link>https://medium.com/@itsanuragjoshi/the-essentials-of-html5-what-you-need-to-know-23581e622898?source=rss-736e5a078bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/23581e622898</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Anurag Joshi]]></dc:creator>
            <pubDate>Sun, 21 Apr 2024 17:44:46 GMT</pubDate>
            <atom:updated>2024-04-21T17:44:46.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IUQGhBX0QPiaUE5r" /><figcaption>Photo by <a href="https://unsplash.com/@jacksonsophat?utm_source=medium&amp;utm_medium=referral">Jackson Sophat</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Welcome to the era of HTML5 — the latest and greatest version of Hypertext Markup Language, the building blocks of the internet.</blockquote><p>If you’re a web developer or just someone curious about how websites work, you’re in for a treat. HTML5 is like a shiny new toolkit that’s packed with some of the following awesome features and tools to make websites more interactive, attractive, and functional than ever before.</p><p>Here are just a few of the fantastic features HTML5 introduces:</p><h3><strong>Semantics — Making Sense of Web Pages</strong></h3><p>In the old days, when we wanted to structure our web pages, we used a lot of &lt;div&gt; and &lt;span&gt; tags. While they helped organize the layout, they didn&#39;t really tell us much about the content they held. This made it hard for programmers to understand the structure of the page, especially when the code got complicated.</p><h4><em>Previous Version (Using Divs)</em></h4><pre>&lt;div id=&quot;header&quot;&gt;Header&lt;/div&gt;<br>&lt;div id=&quot;nav&quot;&gt;Navigation&lt;/div&gt;<br>&lt;div id=&quot;content&quot;&gt;<br>  &lt;div id=&quot;article&quot;&gt;<br>    &lt;div id=&quot;section1&quot;&gt;Section 1&lt;/div&gt;<br>    &lt;div id=&quot;section2&quot;&gt;Section 2&lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br>&lt;div id=&quot;footer&quot;&gt;Footer&lt;/div&gt;</pre><p>Here, we’re just using nested &lt;div&gt; tags to structure our page. It&#39;s not very clear what each section represents, right?</p><h4><strong>How Semantic Elements Help?</strong></h4><p>HTML5 introduced new elements that give more meaning to our code. They help us understand the structure of the page better, both for humans and machines like search engines.</p><p><em>HTML5 (Using Semantic Elements)</em></p><pre>&lt;header&gt;Header&lt;/header&gt;<br>&lt;nav&gt;Navigation&lt;/nav&gt;<br>&lt;article&gt;<br>  &lt;section&gt;Section 1&lt;/section&gt;<br>  &lt;section&gt;Section 2&lt;/section&gt;<br>&lt;/article&gt;<br>&lt;footer&gt;Footer&lt;/footer&gt;</pre><p>Now, we’re using elements like &lt;header&gt;, &lt;nav&gt;, &lt;article&gt;, &lt;section&gt;, and &lt;footer&gt;. These elements are like labels that tell us exactly what each part of the page is for. It&#39;s much easier to understand and maintain the code this way.</p><p>So, Semantic Elements in HTML5 make our code more meaningful and easier to work with, both for programmers and for the web browsers and search engines that read our code.</p><h3><strong>Forms — Friendlier and Smarter</strong></h3><p>In the past, forms on websites were pretty basic. You’d fill in your info and hit submit, but there wasn’t much help if you made a mistake. HTML5 changed that by adding some awesome new features to forms, making them much friendlier for users.</p><p><em>Previous Version (Basic Form)</em></p><pre>&lt;form&gt;<br>  &lt;label for=&quot;email&quot;&gt;Email:&lt;/label&gt;<br>  &lt;input type=&quot;text&quot; id=&quot;email&quot; name=&quot;email&quot;&gt;<br>  &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;<br>&lt;/form&gt;</pre><h4><strong>New Input Fields</strong></h4><p>HTML5 introduced new input types to make forms smarter and easier to use. For example:</p><ul><li>type=&quot;email&quot;: This tells the browser that the input should be an email address.</li><li>type=&quot;url&quot;: Similar to email, but for website URLs</li><li>type=&quot;tel&quot;: For phone numbers</li><li>type=&quot;number&quot;: For numeric input</li><li>type=&quot;range&quot;: Creates a slider control</li><li>type=&quot;date&quot;: Lets users pick a date from a calendar</li><li>type=&quot;color&quot;: Adds a color picker control</li></ul><h4><strong>Built-in Form Validation</strong></h4><p>HTML5 also added built-in form validation, so you don’t have to rely solely on JavaScript. You can now add attributes to your form fields to specify rules for validation. For example:</p><ul><li>required: Makes a field mandatory, so users have to fill it out</li><li>maxlength and minlength: Specify the maximum and minimum length of input</li><li>min and max: Define minimum and maximum values for numeric input</li><li>pattern: Allows you to specify a regex pattern that the input must match</li></ul><p><em>HTML5 (Enhanced Form)</em></p><pre>&lt;form&gt;<br>  &lt;label for=&quot;email&quot;&gt;Email:&lt;/label&gt;<br>  &lt;input type=&quot;email&quot; id=&quot;email&quot; name=&quot;email&quot; required&gt;<br>  &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;<br>&lt;/form&gt;</pre><p>With these enhancements, forms become more user-friendly and error-proof, making the browsing experience smoother for everyone.</p><h3><strong>Storage Capability — Web Storage API</strong></h3><p>In the earlier days of web development, if you wanted to store data locally in the user’s browser, your main option was using cookies. However, cookies had limitations — they were primarily designed for communication between the web server and the browser, and their storage capacity was quite limited (usually around 4KB per cookie).</p><p>Then came HTML5 and the Web Storage API, which changed the game entirely. This new API provided a dedicated mechanism for storing data locally in the user’s browser, without the limitations of cookies.</p><p>Before HTML5, cookies were often misused for local storage. Developers would encode and store data in cookies, even though that wasn’t their intended purpose. But with the Web Storage API, developers now have a more efficient and purpose-built solution for local storage.</p><p>Here’s how it works:</p><pre>// Storing data<br>localStorage.setItem(&#39;username&#39;, &#39;John&#39;);<br><br>// Retrieving data<br>const username = localStorage.getItem(&#39;username&#39;);<br><br>// Removing data<br>localStorage.removeItem(&#39;username&#39;);<br><br>// Clearing all data<br>localStorage.clear();</pre><p>In this example, we use localStorage to store and retrieve data locally in the user&#39;s browser. Unlike cookies, which are sent with every HTTP request, data stored with localStorage remains on the client side and is not automatically sent to the server. This makes it ideal for storing user preferences, settings, or other data that doesn&#39;t need to be shared with the server.</p><p>By leveraging the Web Storage API, developers can create more efficient and responsive web applications that provide a better user experience.</p><h3><strong>Responsive Images — Fit for Every Screen</strong></h3><p>In the earlier days of web development, displaying images on websites was pretty straightforward. You’d just use the &lt;img&gt; tag with a single image source. However, with the advent of different devices with varying screen sizes and resolutions, it became essential to serve appropriately sized images for the best user experience.</p><p>HTML5 introduced the srcset attribute for the &lt;img&gt; element, which allows us to provide multiple image sources based on factors like device pixel density or viewport size. This means we can serve different images to different devices, ensuring a better user experience across various screen sizes.</p><pre>&lt;img src=&quot;image-400.jpg&quot; <br>     srcset=&quot;image-400.jpg 400w, image-800.jpg 800w&quot; <br>     sizes=&quot;(max-width: 600px) 400px,<br>            (max-width: 1000px) 800px,<br>            1200px&quot; <br>     alt=&quot;Image&quot;&gt;</pre><p>In this example, we have an &lt;img&gt; tag with two image sources specified in the srcset attribute. The sizes attribute specifies different image widths based on the viewport width using media queries.</p><ul><li>For screens up to 600px wide, the image width is set to 400px</li><li>For screens up to 1000px wide, the image width is set to 800px</li><li>For screens wider than 1000px, the image width is set to 1200px</li></ul><p>The browser will use this information along with the srcset attribute to select the most appropriate image from the available sources (image-400.jpg or image-800.jpg) based on both the viewport size and pixel density. This allows for a more responsive image layout tailored to different screen sizes.</p><p>This feature ensures that users get the best quality images without unnecessarily large file sizes, improving page load times and overall user experience.</p><p>With the srcset attribute, HTML5 has made it easier for developers to create responsive websites that adapt seamlessly to different devices, ultimately revolutionizing web development and enabling more dynamic, accessible, and engaging websites and applications.</p><h3><strong>Audio and Video Support — Built-In Entertainment</strong></h3><p>Before HTML5, embedding audio and video content on web pages required third-party plugins like Flash or Silverlight. However, HTML5 introduced native support for audio and video elements, making it much easier to integrate multimedia content directly into web pages without relying on external plugins.</p><pre>&lt;audio controls&gt;<br>  &lt;source src=&quot;audio.mp3&quot; type=&quot;audio/mp3&quot;&gt;<br>  Your browser does not support the audio element.<br>&lt;/audio&gt;</pre><pre>&lt;video controls width=&quot;400&quot; height=&quot;300&quot;&gt;<br>  &lt;source src=&quot;video.mp4&quot; type=&quot;video/mp4&quot;&gt;<br>  Your browser does not support the video element.<br>&lt;/video&gt;</pre><p>In these examples:</p><ul><li>The &lt;audio&gt; and &lt;video&gt; tags are used to embed audio and video content, respectively.</li><li>The controls attribute adds playback controls (play, pause, volume, etc.) to the audio and video players.</li><li>The &lt;source&gt; tag specifies the source file of the audio or video content, along with the MIME type.</li><li>The width and height attributes set the dimensions of the video player.</li></ul><p>HTML5’s native audio and video support allows developers to create more engaging and interactive web experiences with multimedia content.</p><h3><strong>Canvas — Unleash Your Creativity</strong></h3><p>HTML5 introduced the &lt;canvas&gt; element, which provides a drawable region in HTML for rendering graphics, animations, and other visual elements dynamically using JavaScript.</p><pre>&lt;canvas id=&quot;myCanvas&quot; width=&quot;400&quot; height=&quot;200&quot;&gt;&lt;/canvas&gt;</pre><p>With the &lt;canvas&gt; element, you can draw shapes, paths, text, and images, and manipulate them in real-time using JavaScript. This enables the creation of interactive games, data visualizations, and multimedia applications directly within the web browser, without the need for external plugins or libraries.</p><p>Here’s a simple example of drawing a rectangle on a canvas using JavaScript:</p><pre>const canvas = document.getElementById(&#39;myCanvas&#39;);<br>const ctx = canvas.getContext(&#39;2d&#39;);<br>ctx.fillStyle = &#39;red&#39;;<br>ctx.fillRect(50, 50, 100, 100); // (x, y, width, height)</pre><p>This code draws a red rectangle on the canvas with the top-left corner at coordinates (50, 50) and a width and height of 100 pixels each.</p><h3><strong>Drag and Drop API — Intuitive Interactions</strong></h3><p>HTML5 introduced the Drag and Drop API, which allows developers to create interactive web applications with drag-and-drop functionality. This API provides a standardized way to handle the dragging and dropping of elements on a web page, making it easier to build intuitive and user-friendly interfaces.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot;&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>  &lt;title&gt;Drag and Drop Example&lt;/title&gt;<br>  &lt;style&gt;<br>    .draggable {<br>      width: 100px;<br>      height: 100px;<br>      background-color: #f00;<br>      cursor: pointer;<br>    }<br>    .dropzone {<br>      width: 200px;<br>      height: 200px;<br>      border: 2px dashed #000;<br>    }<br>  &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br><br>&lt;div class=&quot;draggable&quot; draggable=&quot;true&quot;&gt;Drag me!&lt;/div&gt;<br>&lt;div class=&quot;dropzone&quot;&gt;&lt;/div&gt;<br><br>&lt;script&gt;<br>  const draggable = document.querySelector(&#39;.draggable&#39;);<br>  const dropzone = document.querySelector(&#39;.dropzone&#39;);<br><br>  draggable.addEventListener(&#39;dragstart&#39;, (event) =&gt; {<br>    event.dataTransfer.setData(&#39;text/plain&#39;, &#39;Dragged element&#39;);<br>  });<br><br>  dropzone.addEventListener(&#39;dragover&#39;, (event) =&gt; {<br>    event.preventDefault();<br>  });<br><br>  dropzone.addEventListener(&#39;drop&#39;, (event) =&gt; {<br>    event.preventDefault();<br>    const data = event.dataTransfer.getData(&#39;text/plain&#39;);<br>    event.target.textContent = data;<br>  });<br>&lt;/script&gt;<br><br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>In this example:</p><ul><li>The .draggable element is marked as draggable using the draggable=&quot;true&quot; attribute.</li><li>The dragstart event is fired when the user starts dragging the draggable element. We use event.dataTransfer.setData() to specify the data being dragged.</li><li>The .dropzone element is a drop target where draggable elements can be dropped.</li><li>The dragover event is fired when a draggable element is dragged over the dropzone. We use event.preventDefault() to allow dropping.</li><li>The drop event is fired when a draggable element is dropped onto the dropzone. We use event.dataTransfer.getData() to retrieve the data from the dragged element.</li></ul><p>The Drag and Drop API opens up a wide range of possibilities for creating interactive interfaces, such as drag-and-drop file uploads, rearranging items in a list, and creating interactive games.</p><h3><strong>Geolocation API — Where Are You?</strong></h3><p>HTML5 introduced the Geolocation API, which allows web applications to access the user’s geographical location. This enables developers to create location-aware web applications that can provide location-based services, such as finding nearby restaurants, displaying local weather information, or showing the user’s current position on a map.</p><pre>if (&quot;geolocation&quot; in navigator) {<br>  navigator.geolocation.getCurrentPosition((position) =&gt; {<br>    const latitude = position.coords.latitude;<br>    const longitude = position.coords.longitude;<br>    console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);<br>  });<br>} else {<br>  console.log(&quot;Geolocation is not supported by this browser.&quot;);<br>}</pre><p>In this example:</p><ul><li>We first check if the Geolocation API is supported by the user’s browser using the navigator.geolocation object.</li><li>If supported, we use the getCurrentPosition() method to retrieve the user&#39;s current position.</li><li>The getCurrentPosition() method takes a success callback function as an argument, which receives a Position object containing the user&#39;s coordinates (latitude and longitude).</li><li>We then access the latitude and longitude coordinates from the Position object and log them to the console.</li></ul><p>The Geolocation API provides developers with powerful tools for creating location-aware web applications that enhance user experiences with personalized, location-based features. However, it’s important to respect user privacy and obtain consent before accessing their location information.</p><h3>Conclusion</h3><p>HTML5 is a game-changer in web development, bringing a slew of new features and enhancements that make websites more dynamic, accessible, and engaging than ever before. Whether you’re a developer or just someone who loves browsing the web, HTML5 is sure to make your online experience better and more enjoyable.</p><p>Happy reading 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23581e622898" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Authentication: Cookies, Sessions, and Tokens]]></title>
            <link>https://medium.com/@itsanuragjoshi/simplifying-authentication-cookies-sessions-and-tokens-d8478ac65503?source=rss-736e5a078bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8478ac65503</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Anurag Joshi]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 18:56:13 GMT</pubDate>
            <atom:updated>2024-04-19T18:56:13.614Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*adG68uvcPkGUOXCc" /><figcaption>Photo by <a href="https://unsplash.com/@impelling?utm_source=medium&amp;utm_medium=referral">Ed Hardie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>Authentication means proving who you are</strong>, especially online when you log into websites or apps.</blockquote><p>In the digital world, authentication is crucial for accessing personal accounts, sensitive information, or secure services. Let’s break down the fancy terms like cookies, sessions, and tokens to see how they work in everyday language.</p><h3>Exploring Session-Based Authentication</h3><h4><strong>Understanding Cookies and Sessions</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*UEgFbI9KFbqI15bhyIPLUw.gif" /></figure><p>Imagine you’re logging into your bank account online. You type in your username and password, and Voila! You’re in.</p><p>But what’s really going on?</p><ol><li><strong>Checking Your Info</strong>: When you hit the login button, your bank’s computer does a quick check. It looks at your username and password to make sure they match what’s stored in its secret database. <strong>This is called authentication — making sure you’re really you.</strong></li><li><strong>Getting a Special ID</strong>: If everything checks out, the bank’s computer gives you a special ID called a session ID. It’s like a ticket that says you’re allowed to be on the website. This session ID is unique to you and helps the bank’s computer keep track of who’s who.</li><li><strong>Cookie Time</strong>: The bank sends this ticket to your web browser as a cookie. It’s a tiny file that your browser stores on your computer. Think of it as a secret note that your browser keeps safe for you.</li><li><strong>Automatic Login</strong>: Next time you visit the bank’s website, your browser shows the cookie (or ticket). This way, the bank knows it’s you without needing your username and password again.</li><li><strong>When You Leave</strong>: When you’re done with your banking session and log out, the bank’s computer cancels your session ID. It also tells your browser to throw away the cookie. If you’re not active for a while, the session expires too, and you have to log in again next time.</li></ol><p>Cookies and sessions are like buddies — they work together to keep you safe and logged in while you’re on a website.</p><h4><strong>Why Cookies and Sessions Matter</strong></h4><ul><li><strong>Easy Access</strong>: Cookies and sessions make it easy for you to access your accounts without having to remember your username and password every time.</li><li><strong>Safe and Secure</strong>: Your session ID is kept secret between you and the website’s computer. This makes it harder for bad guys to pretend to be you and access your account.</li><li><strong>Personalized Experience</strong>: Have you ever noticed how websites remember your preferences or settings even after you’ve logged out and come back later? That’s because of cookies and sessions — they make your experience on the website feel more personal and tailored to you.</li></ul><h3><strong>Exploring Token-Based Authentication</strong></h3><p>Now, let’s talk about tokens. Imagine you’re using a new app that helps you budget your money. The app needs to see your bank transactions, but you don’t want to share your bank login. Here’s how tokens help:</p><ol><li><strong>App Approval</strong>: The app asks your bank if it’s okay to look at your transactions. Your bank checks your credentials and asks if you agree to share.</li><li><strong>Getting a Pass</strong>: If you agree, the bank gives the app a special pass called a token. It’s like a temporary key that lets the app see your transactions — but not everything else.</li><li><strong>Staying Safe</strong>: Tokens are safer than sharing your actual login info. And if you change your mind, you can cancel the token without changing your password.</li></ol><h4><strong>What Does a Token Look Like?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HDIdDe7tZMKlRDbZ" /><figcaption>Photo by <a href="https://unsplash.com/@ferhat?utm_source=medium&amp;utm_medium=referral">Ferhat Deniz Fors</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s see what a token from the bank looks like.</p><p>Think of it as a special pass. This pass, called a JSON Web Token (JWT), is more than just a temporary password. It’s like a digital ID card with extra info like your customer ID, what the token allows you to do, when it was made, and when it expires.</p><p>What’s really cool is that this information is <strong>crypto-graphically signed</strong>, which means that it’s easy to verify that the content hasn’t been changed. It’s like having a seal of approval that can’t be tampered with unless you’re the bank.</p><p>So, when you use this token in an app, the app can get your bank info, like your transactions, without needing your actual login details. It’s like a secret code that only works for you and keeps your info safe.</p><p>This is just one way tokens help keep your info secure online.</p><h3><strong>Cookies vs. Tokens</strong></h3><ul><li><strong>Who’s Talking</strong>: While cookies primarily facilitate interaction between the your browser and the website’s server, tokens enable secure communication between multiple parties, including third-party applications and API endpoints.</li><li><strong>Rules and Guidelines</strong>: Tokens follow rules like OAuth 2.0, OpenID or JSON Web Tokens (JWT), which make sure they work well with different systems and always keep your info safe. It’s like having a set of guidelines to make sure everyone speaks the same language and follows the same safety rules when using tokens. Cookies are more flexible but don’t have strict rules.</li><li><strong>What They Do / A</strong>llow: Tokens give you detailed control over what you can access online. They work like magic keys that let you open specific doors but keep others locked. With tokens, you can say exactly what you want to access, like certain files or features. On the other hand, when you use cookie-based authentication, it’s like getting a master key that unlocks everything. So, tokens give you more control, while cookies give you access to everything.</li></ul><p>Both session-based and token-based approaches are widely used in authentication, often in combination. For instance, a session-based approach is commonly used when accessing websites, while token-based authentication may be preferred for interactions with apps from the same service. By knowing how they work can help you navigate the online world with confidence.</p><h3><strong>Wrapping Up — Making Sense of Authentication</strong></h3><p>In short, cookies, sessions, and tokens are like the secret handshakes of the internet — they help keep things safe and make life easier online. Whether you’re logging into your favorite website or letting a new app access your data, understanding these secret handshakes helps you stay secure and in control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8478ac65503" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cooking up Text — Exploring Character Sets in the Digital Kitchen]]></title>
            <link>https://medium.com/@itsanuragjoshi/cooking-up-text-exploring-character-sets-in-computer-kitchen-a6e6e6a9c0a5?source=rss-736e5a078bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6e6e6a9c0a5</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Anurag Joshi]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 12:26:50 GMT</pubDate>
            <atom:updated>2024-04-12T12:58:12.664Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OLJCfYbEkxrgAUaz" /><figcaption>Photo by <a href="https://unsplash.com/@socialcut?utm_source=medium&amp;utm_medium=referral">S O C I A L . C U T</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the digital kitchen of computers, <strong>characters </strong>are like ingredients, and <strong>character sets </strong>are the recipe books guiding the computer chef.</p><p>Let’s dive into this tasty analogy to understand how characters turn into readable text, from the basic recipes of ASCII to the universal language of Unicode.</p><h3>Introduction: Ingredients in the Digital Kitchen</h3><blockquote>Every letter, number, and symbol you see on a screen is a character.</blockquote><p>Imagine characters as ingredients in a chef’s pantry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cueTUyDNO9ZntPJ9" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Just like flour, sugar, and eggs are essential for baking, “A,” “B,” and “!” are the basic building blocks of digital text. Each character has its special code in the recipe books, called <strong>character sets</strong>, which the computer chef follows to create text.</p><h3>The Story Begins: ASCII Recipe Book</h3><p>The ASCII recipe book is like the starting cookbook for our computer chef. ASCII stands for <strong>American Standard Code for Information Interchange</strong>. It has 128 simple ingredients — characters — from “A” to “Z,” numbers, and symbols. It’s great for making basic English text but isn’t enough for other languages or symbols.</p><ul><li><strong>Character “A” in ASCII</strong>: Like flour for baking, “A” has a code of 65 (hexadecimal: 41) in ASCII.</li><li><strong>Character “B” in ASCII</strong>: Similar to sugar, “B” has a code of 66 (hexadecimal: 42).</li><li><strong>Character “!” in ASCII</strong>: Just as eggs are vital, “!” has a code of 33 (hexadecimal: 21) in ASCII.</li></ul><h3>Evolving Flavors: ECS and OEM Code Page Recipes</h3><p>As demands grew, our chef needed more recipes. The ECS (IBM PC Extended Character Set) and OEM Code Page recipe books were introduced.</p><p>ECS kept the original 128 ingredients but added European and special characters, like adding new spices.</p><p><strong>OEM Code Pages</strong> were special recipe books for specific regions, ensuring the chef could cook in various languages. However, using different OEM code pages for different regions became a headache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*rMzdO_TrvbPG23XpJi4Cxg.gif" /></figure><p>Imagine a chef in a big kitchen with many recipe books (code pages). Each book is in a different language, making it hard for the chef (computer) to understand and cook the right dish (text). It was a chaotic kitchen with recipes scattered everywhere, causing confusion and mistakes.</p><h3>The Grand Cookbook: Unicode Recipe Book</h3><p>To solve this chaos, Unicode emerged as the grand universal recipe book. It has space for nearly every character from every language, symbol, and emoji.</p><p>With Unicode, our chef (computer) now has one giant recipe book with clear instructions for every character, making text creation smooth and efficient.</p><p><strong>Character “A” in Unicode</strong>: In this grand recipe book, “A” has a unique code point of 65 (hexadecimal: 0041), among thousands of others.</p><h3>Cooking Techniques: UTF-8 and UTF-16</h3><blockquote>In the digital world, <strong>encoding </strong>is like translating characters into numbers so computers worldwide can “read” and display them correctly.</blockquote><p>Computers use different cooking methods, called encoding formats. UTF-8 is versatile, using 1 to 4 “bytes” to represent characters, great for web pages and emails. UTF-16 uses 2 “bytes” for most characters and is commonly used in Windows kitchen.</p><h3>Why Unicode?</h3><ol><li><strong>Universal Compatibility</strong>: Unicode works for every language and symbol worldwide. It’s like having a recipe book that speaks every language, making it easy for our computer chef to create dishes in any language.</li><li><strong>Efficient and Flexible</strong>: Unicode’s UTF-8 encoding is like a smart cooking method. It uses 1 to 4 “bytes” to represent characters, adjusting based on the character’s complexity. This makes it perfect for web pages and emails where space efficiency is crucial.</li><li><strong>Clear and Consistent</strong>: With Unicode, every character has a unique code point, ensuring clarity and consistency in text display. No more guessing games in the kitchen — our chef knows exactly which recipe to follow for each character.</li></ol><h3>Encoding in Action: Cooking Text</h3><p>When our computer chef receives a text recipe (string), it needs to know which recipe book (character set) to use. This is where encoding comes in. If the recipe book is Unicode, the chef uses the UTF-8 or UTF-16 technique to cook the text.</p><ul><li><strong>UTF-8 Technique</strong>: It’s like using a flexible measuring cup that adjusts for different ingredient amounts. Each character takes up 1 to 4 “bytes” (utensils), ensuring efficient storage and display.</li><li><strong>UTF-16 Technique</strong>: This method uses 2 “bytes” for most characters. It’s commonly used in Windows kitchens.</li></ul><h3>Preserving Recipe Secrets: Ensuring Text is Cooked Just Right</h3><p>In our digital kitchen, just like in a real kitchen, we need to ensure our recipes are followed correctly. Encoding, like our recipes, tells the computer how to “cook” the text. So, how do we make sure the computer knows the right recipe?</p><h4>For Email Messages</h4><p>Think of an email message as a letter with a special note at the top:</p><pre>Content-Type: text/plain; charset=&quot;UTF-8&quot;</pre><p>This note, like the “Content-Type” header, tells the email reader what recipe (encoding) was used to write the message.</p><h4>For Web Pages</h4><p>Originally, web servers would send a similar note along with the web page, like a waiter bringing the recipe before the dish. But, this caused issues.</p><p>Imagine a big kitchen with many chefs using different recipes. The kitchen (server) couldn’t always know the right recipe for each dish (web page).</p><p>So, a clever idea was born: the <strong>HTML meta tag</strong>.</p><pre>&lt;html&gt;<br>&lt;head&gt;<br>&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot;&gt;</pre><p>This meta tag, like a hidden note in a recipe book, tells the computer exactly which recipe (encoding) to use.</p><h3>Wrapping Up: From Ingredients to Text</h3><p>In short, characters in the digital world are the ingredients in a culinary symphony led by our computer chef. From the simple beginnings of ASCII to the vast library of Unicode, each character finds its place in the recipe books of character sets. Unicode, with its UTF-8 and UTF-16 techniques, ensures efficient and clear text creation.</p><p>So, the next time you read a message or see text on a screen, remember the culinary journey these characters have taken, all prepared by our computer chef in the lively kitchen of the digital world. Enjoy the flavors of characters and the recipes that bring them to life!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*398pjzAl4zT4fkYTKAFkJg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6e6e6a9c0a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Your Web Browser Works]]></title>
            <link>https://medium.com/@itsanuragjoshi/how-your-web-browser-works-0c22aa4fad0e?source=rss-736e5a078bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c22aa4fad0e</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Anurag Joshi]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 21:24:57 GMT</pubDate>
            <atom:updated>2024-04-10T21:27:34.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uEGeTFjwXWu66Szn" /><figcaption>Photo by <a href="https://unsplash.com/@richygreat?utm_source=medium&amp;utm_medium=referral">Richy Great</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the vast landscape of the digital world, web browsers are our gateway to the internet. They seamlessly bring together complex technologies to present us with the websites we interact with every day.</p><p><strong>Have you ever wondered what happens behind the scenes when you click a link or type in a web address on your browser?</strong></p><blockquote><strong>A web browser is not just a simple piece of software; it’s like a mini operating system in itself!</strong></blockquote><p>Let’s dive into the fascinating world of web browsers and see what powers them.</p><h3>HTML and C++ Partnership</h3><p>When you visit a website, the pages you see on your screen are more than just pretty pictures and text. They’re the result of a fascinating dance between different technologies, creating the magic that brings the internet to life on your screen.</p><h4>HTML: The Facade</h4><p>Let’s start with HTML. You might have heard of it — it’s the code that structures a web page. HTML tells your browser what content should be on a page and how it should be laid out. But here’s the surprising part: HTML is not the real star when it comes to making those stunning web pages come to life.</p><p>Technically, <strong>HTML is essentially a parser </strong>(like a messenger) that tells the browser what to display and where to put things. But the real work, the heavy lifting, is done by a language called C++.</p><h4>C++: The Real Workhorse</h4><p>C++ is a powerful programming language that works behind the scenes of your browser. It’s like the engine of a car, powering everything you see and interact with. <strong>When your browser gets that HTML message, it turns to C++ to bring it to life.</strong></p><h4><strong>HTML is just an abstraction layer on top of C++.</strong></h4><p>In simpler terms, HTML is like a translator. HTML makes it easier for developers to create web pages without having to directly work with C++. It provides a simpler way to describe the content and structure of a page, and then C++ steps in to make it happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*3fC9M6WA1sqjGrBj5tZjlQ.gif" /></figure><h3>The Browser: More Than Just Software</h3><p>Imagine your web browser as a powerful system with various capabilities:</p><h4>Data Storage / Persistence Layer</h4><p>While you browse the web, your browser acts like a personal memory bank. It stores data like cookies and local storage to remember your preferences and activity. This allows features like browsing history, pre-filled forms, saved logins, and personalized recommendations.</p><p>Tools like the <strong>Web Storage API</strong> (localstorage), <strong>IndexedDB</strong>, <strong>WebSQL</strong>, and <strong>FileSystem </strong>power this behind-the-scenes functionality.</p><h4>User Interface (UI) Layer</h4><p>This is the part you interact with — buttons, menus, and everything you see on your screen. The UI layer makes it easy for you to navigate and use the browser.</p><h4>Browser / Rendering / Layout Engine</h4><p>Browser engines, such as <strong>Blink </strong>(Chrome, Edge), <strong>WebKit </strong>(Safari), and <strong>Gecko</strong> (Firefox), are unique to each browser. Though they’re different, they all do similar core work. Think of this as the brain of the browser.</p><p>This part is responsible for taking the HTML, CSS, and a bit of JavaScript code and turning it into what you see on your screen. It’s like a translator that converts website instructions into something visually appealing.</p><h4>JavaScript (JS) Engine</h4><p>JavaScript is what makes web pages interactive. The JS engine in your browser helps to run these scripts smoothly, making buttons clickable, forms work, and animations happen.</p><p>Common JavaScript engines include <strong>V8 </strong>(Chrome, Edge), <strong>SpiderMonkey</strong> (Firefox), and <strong>JavaScriptCore </strong>(Safari), powering interactive web experiences.</p><h4>Networking Capabilities</h4><p>Surprisingly, your browser can communicate over the internet without needing its own network card. It uses protocols like HTTP, FTP, and SMTP to fetch data from servers.</p><h4>Timers</h4><p>JavaScript itself doesn’t have a built-in timer. So, when you use functions like setTimeout or setInterval, your browser steps in with its own timers. This helps in scheduling tasks and animations on web pages.</p><h4>What Makes a Browser Like an OS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*VaKiQ7iBPozSKADl_T4nHg.gif" /></figure><p>Looking at all these parts, you start to realize a browser has a lot in common with an operating system:</p><ul><li><strong>Timers:</strong> Just like an OS manages tasks and schedules, browsers handle timers for JavaScript.</li><li><strong>Networking Capabilities:</strong> Browsers can fetch data from the internet, even though they’re not a network device</li><li><strong>Data Storage:</strong> Your browser stores cookies and local storage data, much like an OS stores files and settings.</li><li><strong>Rendering Engine:</strong> This is akin to how an OS displays windows and icons on your screen.</li><li><strong>JS Engine:</strong> Like an OS managing applications, the JS engine helps run interactive elements on web pages.</li><li><strong>User Interface:</strong> Finally, the UI layer is what you interact with, similar to how an OS provides buttons and menus.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*QY6pW612gdnDtrbL2BQcuQ.gif" /></figure><p><strong>Isn’t it amazing how much power is packed into your web browser?</strong></p><p>The next time you open a webpage, remember that it’s not just pixels on your screen; it’s a complex system at work, making the internet accessible and interactive for you!</p><h3>Loading HTML and Displaying Elements</h3><p>Now that we have a grasp of the components, let’s walk through how a browser loads an HTML page and presents its elements on the screen:</p><p><strong>1. Load the HTML File</strong></p><p>The browser starts by requesting the HTML file from the web server via the browser’s network engine. The browser’s rendering engine receives the information as raw bytes, which is just a stream of data without any meaning yet.</p><p><strong>2. Character Encoding</strong></p><p>After receiving the raw bytes, the browser’s rendering engine needs to interpret them using a process called character encoding. This scheme guides the rendering engine on how to convert these bytes into readable characters such as letters, numbers, and symbols.</p><p>When you see a &lt;meta charset=&quot;UTF-8&quot;&gt; tag in the HTML document, it&#39;s like a message to the browser: &quot;This document uses UTF-8 encoding for its characters. Please use this scheme to correctly display the characters on the screen.&quot; Without this tag, the browser might struggle to interpret the characters, leading to text appearing garbled or displaying strange symbols on the webpage.</p><p><strong>3. Tokenization</strong></p><p>The browser’s rendering engine breaks down the encoded characters into smaller meaningful units called tokens. These tokens could be HTML tags like &lt;p&gt;, text content like &quot;Hello World&quot;, or attributes like href in an &lt;a&gt; tag.</p><p><strong>4. Building the Object Model (DOM)</strong></p><p>The browser’s rendering engine uses the tokens to build a hierarchical structure called the <strong>Document Object Model (DOM)</strong>. This DOM is like a tree where each element (like paragraphs, headings, images) is a node, and their relationships are represented by connections between nodes.</p><p><strong>5. Similar Process for CSS (CSSOM)</strong></p><p>Similar to HTML, the rendering engine loads the CSS file, interprets the characters, and builds another object model called the <strong>CSS Object Model (CSSOM)</strong>. This model stores all the styling information defined in the CSS.</p><p><strong>6. Building the Render Tree</strong></p><p>Once both the DOM and CSSOM are ready, the browser merges them to create a “render tree”. This tree combines elements from the DOM with styles from the CSSOM, determining how each element should be positioned and displayed on the screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*PsSundrmsvwwksMMMk7vtw.gif" /></figure><p>The rendering engine then calculates <strong>layout </strong>based on screen dimensions, ensuring elements are correctly placed and sized according to CSS rules.</p><p><strong>7. Painting</strong></p><p>Finally, the browser uses the render tree to paint the elements on the screen. This is like drawing the website pixel by pixel based on the instructions in the render tree.</p><p><strong>8. JavaScript Execution</strong></p><p>While the browser prioritizes building the render tree, JavaScript execution can be involved. The browser’s JavaScript engine executes this code. This might involve making network requests, handling user interactions, or updating the DOM dynamically.</p><p>In some cases, the browser might pause painting until the CSSOM is completely built, as JavaScript might affect styles. JavaScript execution itself can also be halted until the CSSOM is ready. This is why asynchronous code is written in JavaScript.</p><p>Asynchronous code allows the browser to continue painting while the JavaScript is processed in the background.</p><p><strong>9. The Final Product</strong></p><p>Once everything is painted, you see the complete webpage on your screen!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*UIWZ9Z3oLh8fArlFbatIXg.gif" /></figure><p><strong>Remember:</strong> This is a simplified explanation. Browsers are incredibly complex and there are many optimizations and exceptions to these steps. But this gives you a basic understanding of how the magic happens behind the scenes when you open a website.</p><h3><strong>Wrapping Up</strong></h3><p>Next time you visit a website, think about all the cool stuff happening in the background. Your browser uses different tools to turn that web address into what you see on your screen. It’s like a behind-the-scenes magic trick, thanks to clever engineering!</p><p>Happy reading 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c22aa4fad0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Web: Understanding the Internet]]></title>
            <link>https://medium.com/@itsanuragjoshi/navigating-the-web-understanding-the-internet-b140579870fa?source=rss-736e5a078bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b140579870fa</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Anurag Joshi]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 20:02:59 GMT</pubDate>
            <atom:updated>2024-04-09T10:00:52.427Z</atom:updated>
            <content:encoded><![CDATA[<p>The Internet is more than just a part of our lives — it’s an essential tool we use every day. It’s where we work, chat with friends, watch videos, and find information.</p><p>But have you ever wondered how this vast network really works?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*FSnYTK2ON40k2W1gPRMAHg.gif" /></figure><p>Let’s take a journey into the world of the Internet , uncovering its secrets and understanding how it connects us all.</p><h3>What is the Internet?</h3><blockquote>At its core, the Internet is an “<strong>INTERconnection of computer NETworks.</strong>”</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FTNQsmPf24go%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DTNQsmPf24go&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FTNQsmPf24go%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/41caa7dc5e48a7de0410a41af5a299b2/href">https://medium.com/media/41caa7dc5e48a7de0410a41af5a299b2/href</a></iframe><p>Think of the Internet as a massive web of connections between computers and devices all over the world. When you connect to the Internet, you’re joining this web, which lets you access websites, send emails, watch videos on YouTube, or chat with friends on social media.</p><p>This web of networks enables users to share resources, communicate, and access information from virtually anywhere on the planet.</p><p>Just how many people are on this web? — <strong>A mind-boggling 5.35 billion people worldwide use the Internet.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*M_JUQoldzYjgfnPV9Z48mw.gif" /></figure><p>That’s about two-thirds (66%) of all the people on the planet according to <a href="https://www.statista.com/statistics/617136/digital-population-worldwide/">Statista</a>!</p><h3>Who Created the Internet?</h3><p>The story of the Internet starts way back in the 1960s when big computers were the size of rooms. Scientists and researchers wanted a way for these computers to talk to each other, even if they were far apart. The Internet began as a project called ARPANET, funded by the U.S. government. It was a way for scientists to share information, like emails and research papers.</p><p>The Internet as we know it really kicked off on January 1, 1983. That’s when a new set of rules, called TCP/IP, was set up. These rules allowed all kinds of computers to talk to each other, no matter what type they were. This was a huge step, and it’s when we say the Internet was officially born.</p><h3>Who Runs the Internet?</h3><p>Nowadays, the Internet is like a big community where lots of different groups work together. One of the most fascinating aspects of the Internet is its decentralized nature.</p><p>Imagine each part of the Internet as a piece of a puzzle. No single person or company owns the whole puzzle. Instead, thousands of organizations around the world take care of their pieces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i1oRK6Cud6pa-6sp" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This decentralized structure is part of what makes the Internet resilient. This way, if one part of the Internet has a problem, it doesn’t affect the whole thing. It’s like having lots of roads to get to the same place — if one road is blocked, you can still take another to reach your destination.</p><h3>Where is the Internet?</h3><p>Let’s think of the Internet as a big highway system.</p><h4>First / Last Mile Network</h4><p>The “last mile” is like the road that connects your house to the highway. It’s how you get onto the Internet from your home or phone. This includes the cables, fiber optics, and cell towers that enable users to access the internet.</p><p>Conversely, the “first mile” is the road going back to your house when you send something out, like an email or a photo.</p><p><strong>Internet Service Providers (ISPs)</strong> maintain the infrastructure that allows users to access the Internet, whether through wired connections or wireless networks. You can think of ISPs as the companies that manage the highways of the Internet. They give you the tools, like routers, to hop on and off the Internet highway. These routers help direct your online traffic to the right places, like websites or apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QGg-pQtP9PoudkGn" /><figcaption>Photo by <a href="https://unsplash.com/@comparefibre?utm_source=medium&amp;utm_medium=referral">Compare Fibre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Internet Hub / Data Centers</h4><p>Imagine data centers as huge storage warehouses for the Internet.</p><p>These places store all the videos, photos, and information you see online. Big companies like Google and Facebook have their own warehouses, while others are like shared storage for smaller websites.</p><p>Data centers need really fast internet connections to handle all the information they store and share with us. They’re often found in quieter, cheaper areas, away from cities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TtQ7OL02Mola56Su" /><figcaption>Photo by <a href="https://unsplash.com/@imgix?utm_source=medium&amp;utm_medium=referral">imgix</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Backbone Network</h4><p>The backbone network is like the main highway of the Internet.</p><p>It’s made up of super-fast cables that carry information between data centers and your devices. These cables stretch across oceans and continents, making sure information can travel quickly and reach you wherever you are.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fyd1JhZzoS6A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dyd1JhZzoS6A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fyd1JhZzoS6A%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/81ddfa359a7f37806b0c0d601450ecd1/href">https://medium.com/media/81ddfa359a7f37806b0c0d601450ecd1/href</a></iframe><p>Backbone providers often connect their networks at <strong>Internet Exchange Points (IXPs)</strong>, typically located in major cities, facilitating the flow of data across vast distances.</p><h3>How do you Connect to the Internet?</h3><p>Imagine the Internet as a massive highway system with lanes going in all directions. To get onto this highway, you need a few things.</p><p>First, you have your device like a phone or computer, which is like your car. Then, you have your Internet Service Provider (ISP), which is like the entrance ramp onto the highway. Your ISP gives you a special tool called a router, which is like a GPS for your car. The router helps your device find the right lanes on the Internet highway to reach the websites, videos, or games you want to access.</p><p>These components work together to ensure your online experience is smooth and efficient, much like driving on a well-maintained highway system.</p><h3>Understanding TCP/IP: The Road Signs of the Internet</h3><p>Think of TCP (Transmission Control Protocol) and IP (Internet Protocol) as the road signs and rules on the Internet highway.</p><p>TCP makes sure that the information you send or receive gets to the right place. It’s like a postman who ensures your letters reach the correct addresses.</p><p>IP, on the other hand, is like your home address on the Internet to send and receive data. Every device connected to the Internet has a unique IP address, which is a set of numbers separated by dots (like 192.168.1.1).</p><p>When you send something online, it’s like putting an envelope with your IP address on it. The Internet uses this address to make sure your data gets to the right device.</p><h4>IP Address: IPv4 vs. IPv6</h4><p>There are two main types of IP addresses: IPv4 and IPv6. IPv4 uses 32-bit addresses in dotted notations, whereas IPv6 uses 128-bit addresses in hexadecimal notations.</p><p>IPv4 is like an older, more crowded neighborhood with addresses that look like 192.168.1.1. The problem is, we’re running out of these IPv4 addresses because there are so many devices on the Internet now. That’s where IPv6 comes in.</p><p>IPv6 is like a newer, bigger neighborhood with addresses that look like 2001:0db8:85a3:0000:0000:8a2e:0370:7334. It provides way more addresses, enough for every device on the planet to have its unique spot on the Internet highway.</p><h3>MAC Address: Your Device’s License Plate</h3><p>Lastly, let’s talk about<strong> MAC (Media Access Control) address</strong>. It is a 48-bit address that contains 6 groups of 2 hexadecimal digits, separated by either hyphens (-) or colons(.).</p><p>This is like your device’s license plate on the Internet highway for local communication on the network. Every device, like your phone or computer, has a unique MAC address that’s hardwired into its hardware. It’s a set of letters and numbers that looks something like “00:1A:2B:3C:4D:5E.”</p><p>Your MAC address is used on the local network, like in your home, to make sure data goes to the right device. It’s like how a toll booth knows which car to charge based on its license plate.</p><h3>DNS: Your Internet Directory</h3><p>Now that we’re cruising on the Internet highway, let’s talk about DNS (Domain Name System). Imagine you want to visit a website, like “<a href="http://www.example.com/">www.example.com</a>.&quot;</p><p>DNS is like the directory that translates this easy-to-remember name into the actual IP address (like 192.168.1.1) of the website’s server.</p><p>It’s similar to looking up a phone number in a phone book based on someone’s name. Without DNS, we’d have to remember long strings of numbers for every website we visit!</p><p>Organizations like <strong>ICANN (Internet Corporation for Assigned Names and Numbers) </strong>manage the DNS system, making sure domain names are registered correctly and directing traffic to the right places.</p><h4>Types of Domain Names: gTLDs and ccTLDs</h4><p>When it comes to domain names, there are different types.</p><ul><li><strong>Generic Top-Level Domains (gTLDs)</strong> are the familiar endings like .com, .org, and .net. These are often used by businesses and organizations worldwide.</li><li><strong>Country Code Top-Level Domains (ccTLDs) </strong>are specific to countries, like .uk for the United Kingdom or .in for India. They help websites identify their country of origin. So, if you see a website with a .uk or .in at the end, you’ll know it’s based in the UK or India, respectively.</li></ul><h3>SSL: Keeping Your Data Safe</h3><p>Now, let’s talk about <strong>SSL (Secure Sockets Layer),</strong> which is like the security guard of the Internet highway. When you visit a website with “https://” in the URL, that “s” stands for SSL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7imWscvulXMlqV0d" /><figcaption>Photo by <a href="https://unsplash.com/@flyd2069?utm_source=medium&amp;utm_medium=referral">FlyD</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>SSL encrypts the data sent between your device and the website’s server. It’s like sealing your information in a locked box before sending it out. This encryption is crucial for protecting sensitive data like passwords, credit card numbers, and personal information.</p><p>Websites with SSL certificates show a padlock icon 🔒in the address bar, giving you peace of mind that your information is secure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*MK22EXRIbm1L0o1nana5tA.png" /></figure><h3>The World Wide Web: Your Digital Playground</h3><p>Now that we’ve covered the inner workings of the Internet, let’s focus on the <strong>World Wide Web (WWW)</strong>, which is like the most popular attraction on this vast Internet highway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*3pJoh_qIXuqDAuUyBIwNkQ.gif" /></figure><p>The <strong>WWW was invented by Sir Tim Berners-Lee in 1989 </strong>and has since transformed how we access and share information globally.</p><p>When you open a web browser and visit websites, watch videos on YouTube, or shop online, you’re using the World Wide Web. It’s a collection of interconnected documents and resources, each identified by a unique <strong>URL (Uniform Resource Locator)</strong>.</p><h4>Internet ≠ World Wide Web</h4><p>It’s essential to differentiate between the Internet and the World Wide Web because they’re often used interchangeably, but they’re not the same thing.</p><p><strong>The Internet is the infrastructure</strong> — the vast network of interconnected computers and devices spanning the globe. It’s the physical cables, routers, servers, and data centers that enable communication and data exchange.</p><p>On the other hand, the <strong>World Wide Web is just one of the many applications that run on this Internet infrastructure</strong>. It’s the virtual space where websites, webpages, and multimedia content live.</p><p><strong>Email</strong>, for example, is another widely used application. When you send an email, it travels through the Internet to reach its destination, much like sending a letter through the postal service.</p><p><strong>FTP (File Transfer Protocol)</strong> is another application used for transferring files between computers on the Internet. It’s like having a digital courier service for sharing files, documents, and images.</p><p>Think of the Internet as the entire highway system, and the World Wide Web as one of the cities you can visit along the way. There are other cities (applications) like email, FTP, online gaming, BitTorrent and more — all running on the same Internet infrastructure.</p><h3>Exploring the Web with Web Browsers</h3><p>When we surf the web, we rely on web browsers — our digital vehicles for navigating the World Wide Web. Popular browsers like Google Chrome, Mozilla Firefox, Safari, and Microsoft Edge take us to websites, videos, articles, and beyond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QhbR_TisZpWqmfnM" /><figcaption>Photo by <a href="https://unsplash.com/@redaquamedia?utm_source=medium&amp;utm_medium=referral">Denny Müller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Websites and Webpages: Building Blocks of the Web</h4><p>So, what exactly is a website? A website is a collection of related webpages hosted on a server and accessible through the Internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RQhr92Mn7jncrDYP" /><figcaption>Photo by <a href="https://unsplash.com/@pankajpatel?utm_source=medium&amp;utm_medium=referral">Pankaj Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Each webpage is like a digital document containing text, images, videos, and links to other pages. When you visit a website, you’re essentially viewing one of these webpages.</p><p>For example, let’s say you visit<a href="http://www.example.com/"> www.example.com</a>. This is the website’s domain name, which is like the address of a house. When you enter this address into your web browser, it fetches the webpage associated with that domain. This webpage might be the homepage of the website, displaying information about the company, its services, or products.</p><h4>HTTP: The Language of the Web</h4><p>Now, how do webpages connect and communicate with each other? This is where <strong>HTTP (Hypertext Transfer Protocol)</strong> comes into play.</p><p>HTTP is like the language that web browsers and web servers use to exchange information. When you click a link on a webpage to navigate to another page, your browser sends an HTTP request to the server hosting that page.</p><p>Let’s break it down:</p><ul><li><strong>You Click a Link:</strong> You’re on a webpage and decide to click a link to view another page on the same website.</li><li><strong>Browser Sends an HTTP Request:</strong> Your web browser sends an HTTP request to the server hosting the new webpage. This request includes the URL (like <a href="http://www.example.com/newpage)">www.example.com/newpage)</a> of the page you want to visit.</li><li><strong>Server Responds with an HTTP Response:</strong> The server receives the request, fetches the requested webpage, and sends it back to your browser as an HTTP response. This response includes the webpage’s content, such as text, images, and videos.</li><li><strong>Browser Displays the Webpage:</strong> Your browser receives the response, interprets the HTML (Hypertext Markup Language) code of the webpage, and displays it on your screen. Voila! You’re now viewing the new webpage.</li></ul><h4>The Dynamic Web: Interactive and Ever-Changing</h4><p>What makes the web so powerful is its interactivity and constant evolution. Webpages can contain forms for submitting information, buttons for interactions, and multimedia elements for engagement.</p><p>Furthermore, webpages are not static; they can be updated and changed by their creators. This means that every time you visit a webpage, you might see new content, updated information, or fresh designs.</p><h3>Conclusion</h3><p>That’s the Internet for you — an incredible network that empowers billions of people worldwide. It’s not just about staying connected; it’s also about secure data sharing and seamless communication. And understanding a bit about how it all works gives us a peek into this incredible digital world we’re all a part of.</p><p>Happy reading 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b140579870fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of Stack using Linked List — Data Structures & Algorithms]]></title>
            <link>https://medium.com/@itsanuragjoshi/implementation-of-stack-using-linked-list-data-structures-algorithms-5e7877500209?source=rss-736e5a078bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e7877500209</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Anurag Joshi]]></dc:creator>
            <pubDate>Mon, 29 Jan 2024 08:20:39 GMT</pubDate>
            <atom:updated>2024-01-29T15:46:52.747Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementation of Stack using Linked List — Data Structures &amp; Algorithms</h3><h3>Introduction</h3><p>A stack is a fundamental data structure that follows the Last In, First Out (LIFO) principle. Implementing a stack using a linked list is an efficient way to manage dynamic data structures. In this article, we’ll explore the creation and basic operations of a stack using a linked list.</p><h3>Stack Structure using Linked List</h3><p>A linked list is a collection of nodes where each node contains data and a reference (link) to the next node in the sequence. For our stack implementation, <strong>each node represents an element in the stack</strong>.</p><pre>// Structure definition in C<br>struct Stack {<br>    int data;<br>    struct Stack* next;<br>};<br><br>// Global variable declaration in C<br>struct Stack* top = NULL;</pre><pre>// Class definition in C++<br>class Stack {<br>public:<br>    int data;<br>    Stack* next;<br>};<br><br>// Global variable declaration in C++<br>Stack* top = nullptr;</pre><h3>Representation of Stack using Linked List</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_3m8xvyavVvcAK2Gpn_3w.png" /><figcaption>Representation of stack using linked list</figcaption></figure><blockquote>When implementing a stack using a linked list, you typically perform insertions and deletions at the front of the linked list. This is because the top of the stack corresponds to the front (head) of the linked list.</blockquote><h3>Display Stack Elements</h3><p>The display function checks if the stack is empty. If not, it traverses the stack and prints each element.</p><pre>// Function to display elements of stack<br>void display() {<br>    // Check if stack is empty<br>    if (top == NULL) {<br>        printf(&quot;Stack is empty.\n&quot;);<br>        return;<br>    }<br><br>    printf(&quot;Elements in the stack: &quot;);<br>    // Initialize a pointer to traverse stack<br>    struct Stack* current = top;<br><br>    // Traverse stack and print each element<br>    while (current != NULL) {<br>        printf(&quot;\n%d&quot;, current-&gt;data);<br>        current = current-&gt;next;<br>    }<br>}</pre><h4>Time &amp; Space Complexity</h4><ul><li>Time Complexity: O(n) — Linear time complexity is incurred when displaying each element in the stack</li><li>Space Complexity: O(1) — Only a constant amount of additional space is required for the traversal and printing operations</li></ul><h3>Push Operation</h3><p>The push function creates a new node, checks for overflow, sets the data, links the new node to the current top, and updates the top to the new node.</p><pre>// Function to push an element onto stack<br>void push(int x)<br>{<br>    // Create a new node<br>    struct Stack* temp = (struct Stack*)malloc(sizeof(struct Stack)); <br>    <br>    // Check for overflow condition<br>    if(temp == NULL) {<br>        printf(&quot;Stack Overflow&quot;);<br>        return; // Exit function in case of overflow<br>    }<br><br>    temp-&gt;data = x; // Set data of new node to input value &#39;x&#39;<br>    temp-&gt;next = top; // Link new node to current top<br>    top = temp; // Update top to new node<br>}<br><br>int main() {<br>    // Push elements onto stack<br>    push(1);<br>    push(2);<br>    push(3);<br><br>    // Display elements of stack<br>    display();<br><br>    return 0;<br>}</pre><p>Upon executing the program, the output displays the elements in the stack. In the provided example, the stack contains the values 3, 2, and 1. The order of display reflects the Last In, First Out (LIFO) nature of the stack, where the most recently added element (3) is presented first, followed by 2 and then 1.</p><pre>Elements in the stack: <br>3<br>2<br>1</pre><h4>Time &amp; Space Complexity</h4><p>Time Complexity: O(1) — The push operation has a constant time complexity as it involves a fixed number of steps</p><p>Space Complexity: O(1) — The memory required for the new node is constant and does not depend on the size of the stack</p><h3>Pop Operation</h3><p>The pop operation removes the top element from the stack. It checks for underflow conditions, and if the stack is not empty, it updates the top to the next node and frees the memory of the removed node.</p><pre>// Function to pop an element from stack<br>int pop()<br>{<br>    // Check for underflow condition<br>    if (top == NULL) {<br>        printf(&quot;Stack Underflow&quot;);<br>        return -1; // Return -1 indicating underflow<br>    }<br><br>    struct Stack* temp = top; // Save current top<br>    int poppedValue = temp-&gt;data; // Save data<br>    top = top-&gt;next; // Move top to next node<br>    free(temp); // Free memory of removed node<br>    <br>    // Assuming data is an integer, you can return popped value<br>    return poppedValue;<br>}<br><br>int main() {<br>    // Push elements onto the stack<br>    push(1);<br>    push(2);<br>    push(3);<br><br>    // Display elements before popping<br>    printf(&quot;Elements before popping: &quot;);<br>    display();<br><br>    // Pop an element from stack<br>    printf(&quot;Popped element: %d\n&quot;, pop());<br><br>    // Display elements after popping<br>    printf(&quot;Elements after popping: &quot;);<br>    display();<br>    <br>    return 0;<br>}</pre><p>The output of the above provided code reflects the state of the stack before and after popping an element.</p><pre>Elements before popping: <br>3<br>2<br>1<br>Popped element: 3<br>Elements after popping: <br>2<br>1</pre><h4><strong>Time &amp; Space Complexity</strong></h4><ul><li>Time Complexity: O(1) — Constant time is required for the pop operation as it involves a fixed number of steps</li><li>Space Complexity: O(1) — The memory released by freeing the removed node is constant</li></ul><h3>Peek Operation</h3><p>The peek operation returns the data of the element at a specific position in the stack. It traverses the linked list until reaching the desired position or the end.</p><pre>// Function to peek at element at a specific position in stack<br>int peek(int pos) {<br>    struct Stack *p = top;<br>    int i;<br><br>    // Traverse linked list until reaching desired position or end<br>    for (i = 0; p != NULL &amp;&amp; i &lt; pos - 1; i++) {<br>        p = p-&gt;next;<br>    }<br><br>    // Check if position is valid and return data of node at that position<br>    if (p != NULL) {<br>        return p-&gt;data;<br>    } else {<br>        return -1; // Return -1 indicating an invalid position or an empty stack<br>    }<br>}</pre><h4><strong>Time &amp; Space Complexity</strong></h4><ul><li>Time Complexity: O(n) — Linear time is required to traverse the linked list until the desired position</li><li>Space Complexity: O(1) — Constant space is used for the traversal</li></ul><h3>Returns the Top of Stack</h3><p>The stackTop function returns the data of the top element of the stack if it’s not empty.</p><pre>// Function to return top element of stack<br>int stackTop() {<br>    if (top) {<br>        // Return data of top node if the stack is not empty<br>        return top-&gt;data;<br>    } else {<br>        // Return -1 indicating an empty stack<br>        return -1;<br>    }<br>}</pre><h4><strong>Time &amp; Space Complexity</strong></h4><ul><li>Time Complexity: O(1) — Constant time is needed to access the data of the top node</li><li>Space Complexity: O(1) — No additional space is required</li></ul><h3>Check if Stack is Empty</h3><p>The isEmpty function checks if the stack is empty.</p><pre>// Function to check if stack is empty<br>int isEmpty() {<br>    // Return 1 if stack is empty, 0 otherwise<br>    return top ? 0 : 1;<br>}</pre><h4><strong>Time &amp; Space Complexity</strong></h4><ul><li>Time Complexity: O(1) — Constant time is needed to check if the top is NULL</li><li>Space Complexity: O(1) — No additional space is required</li></ul><h3>Check if Stack is Full</h3><p>The isFull function checks if the stack is full, although in a linked list implementation, the stack is not limited by a fixed size.</p><pre>// Function to check if stack is full<br>int isFull() {<br>    struct Stack* temp = (struct Stack*)malloc(sizeof(struct Stack));<br><br>    // Check if memory allocation for a new node is successful<br>    int result = temp ? 1 : 0;<br><br>    // Free allocated memory to avoid memory leaks<br>    free(temp);<br><br>    return result;<br>}</pre><h4><strong>Time &amp; Space Complexity</strong></h4><ul><li>Time Complexity: O(1) — Constant time is required for memory allocation and de-allocation</li><li>Space Complexity: O(1) — Constant space is used for the temporary node</li></ul><h3>Conclusion</h3><p>Implementing a stack using a linked list provides a flexible and efficient way to manage dynamic data structures. Each operation has its own time and space complexity, making it suitable for various applications where a Last In, First Out (LIFO) approach is beneficial. The linked list allows for dynamic resizing, making the stack adaptable to changing needs.</p><p>Happy coding 👩‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e7877500209" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of Stack using Array — Data Structures & Algorithms]]></title>
            <link>https://medium.com/@itsanuragjoshi/implementation-of-stack-using-array-data-structures-algorithms-41d7e04f15e9?source=rss-736e5a078bf6------2</link>
            <guid isPermaLink="false">https://medium.com/p/41d7e04f15e9</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Anurag Joshi]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 04:01:36 GMT</pubDate>
            <atom:updated>2024-01-29T07:32:17.391Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementation of Stack using Array — Data Structures &amp; Algorithms</h3><h3>Introduction</h3><p>When visualizing an array as a vertical structure, it becomes more intuitive to understand its application as a stack, especially when viewed from the top. In this implementation, we’ll explore the creation of a stack using an array and the fundamental operations associated with it.</p><h3>Stack Structure using Array</h3><p>Our stack implementation involves three essential components:</p><ol><li><strong>An array</strong> — dynamically created in the heap to store elements</li><li><strong>Size of array </strong>—<strong> </strong>defining the maximum capacity of the stack</li><li><strong>Top pointer </strong>—<strong> </strong>indicating the current topmost element in the stack</li></ol><p>We encapsulate these components in both C and C++ through structure and class definitions.</p><pre>// Structure definition in C and C++<br>struct Stack {<br>    int *s;   // Pointer to an array in heap memory<br>    int size;  // Size of array<br>    int top;   // Top pointer<br>};<br><br>// Class definition in C++<br>class Stack {<br>public:<br>    int *s;    // Pointer to an array in heap memory<br>    int size;  // Size of array<br>    int top;   // Top pointer<br>};</pre><h3>Representation of Stack using Array</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVKYIiFEaaV6GZrwCl5JAA.png" /><figcaption>Representation of Stack using Array</figcaption></figure><blockquote>When implementing a stack using an array, you perform insertions and deletions at one end of the array. Conventionally, the end where these operations happen is referred to as the “top” of the stack.</blockquote><h3>Create a Stack</h3><p>We initialize our stack using the create function, where users input the desired maximum size. The stack structure or class is appropriately set with the size and a top pointer initialized to -1.</p><pre>// Function to create a stack<br>void create(struct Stack *st) {<br>    printf(&quot;Enter the size of the stack: &quot;);<br>    scanf(&quot;%d&quot;, &amp;st-&gt;size);  // Take size as input from user<br>    st-&gt;top = -1;<br>    st-&gt;s = (int *)malloc(st-&gt;size * sizeof(int));<br>}</pre><p>Note:- In this function, the struct Stack is <strong>passed by reference</strong>, ensuring that modifications made inside the function affect the original structure. The arrow operator (-&gt;) is used to access structure elements in this context.</p><h4><strong>Time and Space Complexity</strong></h4><ul><li><strong>Time Complexity:</strong> O(1) — Allocating memory and initializing the stack’s metadata (size and top pointer) are constant-time operations.</li><li><strong>Space Complexity:</strong> O(1) — Only a fixed amount of memory is used for the stack structure and array.</li></ul><h3>Display Stack Elements</h3><p>The display function provides a clear view of the stack&#39;s contents, ensuring it&#39;s not empty before proceeding with the display.</p><pre>// Function to display elements of stack<br>void display(struct Stack st) {<br>    if (st.top == -1) {<br>        printf(&quot;Stack is empty.\n&quot;);<br>        return;<br>    }<br><br>    printf(&quot;Elements in the stack: &quot;);<br>    for (int i = 0; i &lt;= st.top; ++i) {<br>        printf(&quot;%d &quot;, st.s[i]);<br>    }<br>    printf(&quot;\n&quot;);<br>}</pre><p>Note:- In this function, the struct Stack is passed by value, meaning a copy of the structure is created when the function is called. Any modifications made inside the function won&#39;t affect the original structure. The original structure remains unchanged, making it a read-only operation. Elements are accessed using the dot operator (.) in this case.</p><h4><strong>Time and Space Complexity</strong></h4><ul><li><strong>Time Complexity:</strong> O(n) (where ’n’ is the number of elements in the stack) — Visiting each element in the stack to display them results in a linear time complexity.</li><li><strong>Space Complexity:</strong> O(1) — No additional space is used; it’s mainly about traversing the existing elements.</li></ul><h3>Push Operation</h3><p>The push operation adds an element to the top of the stack if space is available.</p><p>A “stack overflow” occurs when the available space in a stack data structure is exhausted, and an attempt is made to push more elements onto the stack than it can hold. In other words, it’s a situation where the stack is full, and there is no more room for additional elements.</p><pre>// Function to push an element onto stack<br>void push(struct Stack *st, int x) {<br>    // Check if stack is already full<br>    if (st-&gt;top == st-&gt;size - 1)<br>        printf(&quot;Stack Overflow&quot;);<br>    else {<br>        // Increment top pointer and add element to stack<br>        st-&gt;top++;<br>        st-&gt;s[st-&gt;top] = x;<br>    }<br>}</pre><p>Handling stack overflow situations is important in programming to prevent unexpected behavior or crashes. Developers need to ensure that the size of the stack is appropriately set based on the expected usage and requirements of the program.</p><p>Note:- In this function, the struct Stack is <strong>passed by reference</strong>, ensuring that modifications made inside the function affect the original structure. The arrow operator (-&gt;) is used to access structure elements in this context.</p><h4><strong>Time and Space Complexity</strong></h4><ul><li><strong>Time Complexity:</strong> O(1) — Incrementing the top pointer and adding an element to the array are constant-time operations.</li><li><strong>Space Complexity:</strong> O(1) — No extra space is used proportional to the size of the stack.</li></ul><h3>Pop Operation</h3><p>The pop operation removes and returns the element from the top of the stack.</p><p>A “<strong>stack underflow</strong>” occurs when an attempt is made to pop (remove) an element from an empty stack. In other words, it happens when there are no elements left in the stack, and a pop operation is requested.</p><pre>// Function to pop an element from stack<br>int pop(struct Stack *st) {<br>    int x = -1;<br>    // Check if stack is empty<br>    if (st-&gt;top == -1)<br>        printf(&quot;Stack Underflow&quot;);<br>    else {<br>        // Retrieve top element, decrement top pointer, and return element<br>        x = st-&gt;s[st-&gt;top];<br>        st-&gt;top--;<br>    }<br>    return x;<br>}</pre><p>Handling stack underflow situations is crucial to prevent accessing invalid memory locations and unexpected behavior. It’s a good practice to check for underflow conditions before performing pop operations to ensure the stack is not empty.</p><p>Note:- In this function, the struct Stack is <strong>passed by reference</strong>, ensuring that modifications made inside the function affect the original structure. The arrow operator (-&gt;) is used to access structure elements in this context.</p><h4><strong>Time and Space Complexity</strong></h4><ul><li><strong>Time Complexity:</strong> O(1) — Retrieving the top element, decrementing the top pointer, and returning the element are constant-time operations.</li><li><strong>Space Complexity:</strong> O(1) — No additional space is used for the pop operation.</li></ul><h3>Peek Operation</h3><p>The peek operation access/retrieves the element at a specific valid position without removing it.</p><h4><strong>Mapping Stack Position and Array Index</strong></h4><p>In the context of a stack, the top pointer represents the position of the topmost element. The index is essentially the distance from the top. When the stack is empty (top is -1), there is no element, so any index would be invalid.</p><p>The formula for mapping position (pos) and index is derived from the fact that the first position corresponds to the top of the stack. By observing a few examples, we can create a mapping table:</p><pre>pos     index(=top-pos+1)<br>1       3=3-1+1<br>2       2=3-2+1<br>3       1=3-3+1<br>4       0=3-4+1</pre><p>Hence, the general formula is established as:</p><blockquote><strong>index = top - pos + 1</strong></blockquote><p>This formula calculates the correct index based on the top position, allowing us to access the desired element in the stack.</p><h4><strong>Implementation of Formula to Peek function</strong></h4><p>In the Peek function, this formula is used to find the correct index, and the element at that index (st-&gt;s[st-&gt;top - pos + 1]) is then retrieved. The function ensures that the index is valid before attempting to access the element, preventing potential errors.</p><pre>// Function to peek at an element at a specific position in stack<br>int peek(struct Stack *st, int pos) {<br>    int x = -1;<br>    // Check if index is valid<br>    if (st-&gt;top - pos + 1 &lt; 0)<br>        printf(&quot;Invalid Index&quot;);<br>    else<br>        // Calculate index based on position and retrieve element<br>        x = st-&gt;s[st-&gt;top - pos + 1];<br>    return x;<br>}</pre><p>Note:- In this function, the struct Stack is <strong>passed by reference</strong>, ensuring that modifications made inside the function affect the original structure. The arrow operator (-&gt;) is used to access structure elements in this context.</p><h4><strong>Time and Space Complexity</strong></h4><ul><li><strong>Time Complexity:</strong> O(1) — Calculating the index and accessing the element are constant-time operations.</li><li><strong>Space Complexity:</strong> O(1) — The operation doesn’t use additional space proportional to the size of the stack.</li></ul><h3>Returns the Top of Stack</h3><p>The stackTop operation returns the topmost element of the stack.</p><pre>// Function to get the topmost element of stack<br>int stackTop(struct Stack st) {<br>    // Check if stack is empty<br>    if (st.Top == -1)<br>        return -1;<br>    else<br>        // Return top element<br>        return st.s[st.top];<br>}</pre><p>Note:- In this function, the struct Stack is passed by value, meaning a copy of the structure is created when the function is called. Any modifications made inside the function won&#39;t affect the original structure. The original structure remains unchanged, making it a read-only operation. Elements are accessed using the dot operator (.) in this case.</p><h4><strong>Time and Space Complexity</strong></h4><ul><li><strong>Time Complexity:</strong> O(1) — Directly accessing the top element is a constant-time operation.</li><li><strong>Space Complexity:</strong> O(1) — No additional space is used.</li></ul><h3>Check if Stack is Empty</h3><p>The isEmpty operation checks if the stack is empty.</p><pre>// Function to check if stack is empty<br>int isEmpty(struct Stack st) {<br>    // Return 1 if stack is empty, 0 otherwise<br>    return (st.top == -1) ? 1 : 0;<br>}</pre><p>Note:- In this function, the struct Stack is passed by value, meaning a copy of the structure is created when the function is called. Any modifications made inside the function won&#39;t affect the original structure. The original structure remains unchanged, making it a read-only operation. Elements are accessed using the dot operator (.) in this case.</p><h4><strong>Time and Space Complexity</strong></h4><ul><li><strong>Time Complexity:</strong> O(1) — Checking if the top pointer is -1 is a constant-time operation.</li><li><strong>Space Complexity:</strong> O(1) — No additional space is used.</li></ul><h3>Check if Stack is Full</h3><p>The isFull operation checks if the stack is full, reaching its maximum capacity.</p><pre>// Function to check if stack is full<br>int isFull(struct Stack st) {<br>    // Return 1 if stack is full, 0 otherwise<br>    return (st.top == st.size - 1) ? 1 : 0;<br>}</pre><p>Note:- In this function, the struct Stack is passed by value, meaning a copy of the structure is created when the function is called. Any modifications made inside the function won&#39;t affect the original structure. The original structure remains unchanged, making it a read-only operation. Elements are accessed using the dot operator (.) in this case.</p><h4><strong>Time and Space Complexity</strong></h4><ul><li><strong>Time Complexity:</strong> O(1) — Comparing the top pointer with the stack size is a constant-time operation.</li><li><strong>Space Complexity:</strong> O(1) — No additional space is used.</li></ul><h3>Conclusion</h3><p>This implementation provides a foundational understanding of creating and performing operations on a stack using an array, showcasing the versatility and simplicity of this fundamental data structure.</p><p>Happy coding 👩‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d7e04f15e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>