<?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"><channel><title><![CDATA[Shah x Code]]></title><description><![CDATA[Shah x Code]]></description><link>https://shahxcode.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 09 Nov 2026 02:39:05 GMT</lastBuildDate><atom:link href="https://shahxcode.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Adding Operations in a Linked List]]></title><description><![CDATA[In this article, I will explore the topic of adding a node to a linked list, building upon the concepts discussed in my previous article on the subject…]]></description><link>https://shahxcode.hashnode.dev/adding-operations-in-a-linked-list</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/adding-operations-in-a-linked-list</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[data structures]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[Javascript library]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Sun, 26 Feb 2023 18:40:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677435928537/1e37ba43-05a7-4bbc-899d-4db0029bf358.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, I will explore the topic of adding a node to a linked list, building upon the concepts discussed in my <a target="_blank" href="https://shahxcode.hashnode.dev/what-are-linked-lists">previous article</a> on the subject. The focus will be on a Javascript implementation. We will delve deeper into the different operations of adding a node, providing a more detailed and comprehensive understanding of this fundamental operation in linked list data structures.</p>
<h2 id="heading-adding-operations">Adding Operations</h2>
<p>When it comes to adding nodes to a linked list, there are several types of operations that one can perform.</p>
<p>The most basic of these is known as <strong>appending</strong>, which involves adding a new node to the end of the linked list. This is typically done by iterating through the list until the last node is reached, and then adding the new node to the end.</p>
<p>Another common operation is known as <strong>prepending</strong>, which involves adding a new node to the beginning of the list. This is done by simply setting the new node as the head of the linked list, and updating its next pointer to point to the previous head node.</p>
<p>Other types of adding operations can include <strong>inserting a node at a specific position</strong> in the list, or <strong>concatenating</strong> two separate linked lists together.</p>
<h2 id="heading-visualising-adding-operations">Visualising Adding Operations</h2>
<p>From my experience, having the ability to visualize addition operations is crucial to fully understand how they function. This stands true for any other linked list operations as well. By learning how to visualize operations, you can do any linked list manipulations confidently.</p>
<p>In the interest of brevity and clarity, I will focus solely on the visualization of inserting a node at the nth position in a doubly linked list. Once you grasp this concept, you will find it easy to execute operations such as appending, prepending, and concatenating on any type of linked list without encountering much difficulty.</p>
<h3 id="heading-addition-illustration">Addition Illustration</h3>
<p>Consider the following doubly linked list:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677425019365/adf4d5fb-4ca5-44a7-9e8a-3c55257aa073.png" alt class="image--center mx-auto" /></p>
<p>We are going to be inserting (adding) a new node at index 1.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677426742305/1dc44371-f68f-4e71-a4fb-eb73e3b717fd.png" alt class="image--center mx-auto" /></p>
<p>To add a new node (represented by a purple node with value 9) at index 1 in the linked list, we would have to traverse the linked list to reach index 1 and then break the existing link between index 0 and index 1.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677427641628/6b3d33d1-b870-4758-a548-a82e0394be43.png" alt class="image--center mx-auto" /></p>
<p>Then we would have to create a new link that accommodates the new node. I think of it like rewiring components in an electrical circuit.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677428611344/0bb6a155-95ad-48ed-88ff-96c5d3e38351.png" alt class="image--center mx-auto" /></p>
<p>After relinking, our new node will be inserted in the linked list at index 1, while the node previously at index 1 will now be at index 2. This concludes the addition operation.</p>
<h2 id="heading-code">Code</h2>
<p>Now that we are able to visualize what happens during the addition operation, creating the code for it is going to be relatively simpler.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//implementing nth index addition function in doubly linked lists</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LinkedList</span> </span>{
    <span class="hljs-keyword">constructor</span>(){
        <span class="hljs-built_in">this</span>.head = <span class="hljs-built_in">this</span>.tail = <span class="hljs-literal">null</span>
    }

    nthInsertion(value,index){
    <span class="hljs-keyword">let</span> currentIndex = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">let</span> currentNode = <span class="hljs-built_in">this</span>.head;
    <span class="hljs-keyword">while</span>(currentNode){
        <span class="hljs-keyword">if</span>(currentIndex === index){
            <span class="hljs-keyword">let</span> oldNode = currentNode <span class="hljs-comment">//node with value 3 </span>
            <span class="hljs-keyword">let</span> oldNodePrev = currentNode.prev <span class="hljs-comment">//node with value 1   </span>
            currentNode = <span class="hljs-keyword">new</span> Node(value) <span class="hljs-comment">//purple node with value 9</span>
            oldNodePrev.next = currentNode 
            oldNode.prev = currentNode
            currentNode.next = oldNode
            currentNode.prev = oldNodePrev 
            <span class="hljs-keyword">return</span> currentNode
        }
        <span class="hljs-keyword">else</span>{
            currentIndex++
            currentNode = currentNode.next
        }
        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span> <span class="hljs-comment">//if index invalid </span>
    }
    }


}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Node</span> </span>{
    <span class="hljs-keyword">constructor</span>(value, prev, next){
        <span class="hljs-built_in">this</span>.value = value
        <span class="hljs-built_in">this</span>.prev = prev || <span class="hljs-literal">null</span> <span class="hljs-comment">//default value of null</span>
        <span class="hljs-built_in">this</span>.next = next || <span class="hljs-literal">null</span> <span class="hljs-comment">//default value of null</span>
    }
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Whether you're appending a node to the end of a linked list, inserting a node at a specific position, or prepending a node to the beginning of a linked list, understanding the mechanics of adding nodes is vital. With a solid understanding of adding nodes to a linked list, you can easily manipulate the list to suit your needs and build more complex data structures as well. In the upcoming articles, I will be diving into other types of operations, like delete and search operations, that can be performed on linked lists.</p>
]]></content:encoded></item><item><title><![CDATA[What are Linked Lists?]]></title><description><![CDATA[Linked lists are a fundamental data structure used to represent a collection of elements in a sequence. They are referred to as a sequential data…]]></description><link>https://shahxcode.hashnode.dev/what-are-linked-lists</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/what-are-linked-lists</guid><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Sun, 19 Feb 2023 15:37:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676820997139/5d410915-63aa-45da-86f8-76af35703b57.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Linked lists are a fundamental data structure used to represent a collection of elements in a sequence. They are referred to as a <em>sequential data structure</em>, with each element in a link list referred to as a <em>node</em>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676816846441/4d14d795-b577-41e1-8cc6-0c54dbd7fb85.png" alt="A node is made up of a value and a pointer to next node" class="image--center mx-auto" /></p>
<p>A node consists of a value and a pointer to the next value (or two pointers pointing to the next value as well as the previous value in the case of doubly linked lists). Referring to the illustration above, we can see that there are three nodes in the linked list. The first node has a value of 5 and points to the second node which has a value of 9 and points to the third node. Since each node points to the next, we can move from one node to the adjacent one sequentially.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676817462562/beba0e75-8eb1-47b0-9b8d-612fe698392e.png" alt class="image--center mx-auto" /></p>
<p>Now that we know that each element in a linked list is called a node and that each node consists of a value and a pointer to the next node, let's discuss two special nodes in a linked list: head node and tail node.</p>
<p>The first node in a linked list is referred to as a head node or the head. The last node in a linked list is referred to as a tail node or simply as the tail. While the head points to the second node, the tail points to null to indicate the end of the linked list. The previous illustration has been updated with head and tail labels.</p>
<p>Until now, what we have discussed is in reference to a single linked list. With the knowledge of node, head, and tail in mind, let's explore other types of linked lists.</p>
<h2 id="heading-doubly-linked-list">Doubly Linked List</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676819118477/ff63d5d5-98ae-4691-9e71-fce49714b33d.png" alt class="image--center mx-auto" /></p>
<p>In a doubly linked list, a node has two pointers that point to the previous and the next nodes. This means that at any point in a doubly linked list, one can move forward or backward to reach a specific node.</p>
<p>Unlike in a single linked list, the head node in a doubly linked list points to null as a previous value.</p>
<h2 id="heading-circular-linked-list">Circular Linked List</h2>
<p>A circular linked list is another type of linked list where the last node needs to point back to the first node, hence allowing for a circular traversal of the linked list.</p>
<p>A circular linked list can be either single or doubly linked. In a singly linked circular linked list, each node only has a single pointer to the next node in the list, and the last node points back to the first node to form a cycle. In a doubly linked circular linked list, each node has both a forward and a backward pointer, so each node points to the next and previous nodes in the list. Like the singly linked circular linked list, the last node points back to the first node to form a cycle.</p>
<h2 id="heading-use-cases">Use Cases</h2>
<ul>
<li><p>Single linked lists: These are often used in situations where data only needs to be accessed in a forward direction, such as in a queue or a stack. For example, a printer spooler may use a single linked list to store a queue of print jobs, where each new job is added to the end of the list and the first job is printed first.</p>
</li>
<li><p>Doubly linked lists: These are useful in situations where data needs to be accessed in both directions, such as in a music playlist where the user may want to go back and forth between songs. Another example is a web browser's history list, where each page is stored as a node and the user can navigate forward and backward through their browsing history.</p>
</li>
<li><p>Circular linked lists: These can be useful in situations where the last node needs to point back to the first node, such as in a round-robin scheduling algorithm. For example, in a tournament where every team plays against each other, a circular linked list can be used to determine the order of the matches, where each node represents a team and the last node points back to the first node to create a cycle.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Linked lists are a fundamental data structure in software development with a wide range of applications. This article aims to provide you with an initial understanding of what they are. In the future, I will delve into why linked lists are used, as well as provide information on implementing them in code.</p>
]]></content:encoded></item><item><title><![CDATA[HTML enterkeyhint Attribute]]></title><description><![CDATA[I recently learned about the enterkeyhint HTML attribute and found it to be a pretty cool feature that we should all know about. It is a relatively new…]]></description><link>https://shahxcode.hashnode.dev/html-enterkeyhint-attribute</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/html-enterkeyhint-attribute</guid><category><![CDATA[HTML5]]></category><category><![CDATA[HTML]]></category><category><![CDATA[forms]]></category><category><![CDATA[form]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Sun, 12 Feb 2023 18:59:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676354838899/450c4ed0-b3b5-4778-8dbf-ace0f235663e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I recently learned about the <code>enterkeyhint</code> HTML attribute and found it to be a pretty cool feature that we should all know about. It is a relatively new addition to HTML forms, and it offers a way for developers to provide hints to browsers about what the default action of the "Enter" key should be for a specific input element. You have most likely encountered it while browsing on your mobile. It can improve the overall user experience and accessibility of a form by making it more clear what will happen when a user presses the Enter key.</p>
<h2 id="heading-how-to-use-it">How to Use It</h2>
<p>To use the <code>enterkeyhint</code> attribute, simply add it to an or element, and give it a value of either "enter", "go", "next", "previous", "search", "send", or "done".</p>
<p>For example:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">enterkeyhint</span>=<span class="hljs-string">"search"</span>&gt;</span>
</code></pre>
<p>The <code>enterkeyhint</code> attribute provides a hint to the browser about what the default action of the Enter key should be for this input element. For example, if the <code>enterkeyhint</code> attribute is set to "search", the browser may display a search icon on the Enter key of the virtual keyboard.</p>
<h2 id="heading-support">Support</h2>
<p>It's important to note that the <code>enterkeyhint</code> attribute may not be supported by all browsers yet.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, the <code>enterkeyhint</code> attribute is a useful tool for improving the user experience and accessibility of your forms. It provides a simple way to provide hints to browsers about what the default action of the Enter key should be for a specific input element, and can make it more clear what will happen when a user presses the Enter key.</p>
]]></content:encoded></item><item><title><![CDATA[Implementing Queue Data Structure In Javascript]]></title><description><![CDATA[A queue is a linear data structure, similar to the Stack data structure. However, unlike a stack, a queue follows the First-In-First-Out (FIFO) principle…]]></description><link>https://shahxcode.hashnode.dev/implementing-queue-data-structure-in-javascript</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/implementing-queue-data-structure-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[arrays]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[js]]></category><category><![CDATA[Javascript library]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Sun, 12 Feb 2023 18:39:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676354459826/4d808f56-75d7-4bb9-89c2-a5e31e24113e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A queue is a linear data structure, similar to the <a target="_blank" href="https://shahxcode.hashnode.dev/implementing-stack-data-structure-in-javascript">Stack</a> data structure. However, unlike a stack, a queue follows the First-In-First-Out (FIFO) principle. This means that the first item to be added to the queue is the first item to be removed, and the last item added is the last item to be removed. Queues are commonly used in computer science for tasks such as task scheduling, data processing, and communication between processes.</p>
<h2 id="heading-basics-of-a-queue">Basics of a Queue</h2>
<p>The queue data structure is similar to a real-life queue. For instance, imagine a queue of people waiting to buy tickets at a theme park. The first person in line is the first one to get a ticket, and the last person in line is the last one to get a ticket, following the FIFO principle.</p>
<p>A queue has two basic operations: enqueue and dequeue. Enqueue is the process of adding an item to the end of the queue, while dequeue is the process of removing the item from the front of the queue.</p>
<p>Let's take an example to understand the working of a queue using the theme park analogy:</p>
<ol>
<li><p>Initially, the queue is empty.</p>
</li>
<li><p>When the first person arrives, they are added to the queue (enqueued). The first person is also the last in this case.</p>
</li>
<li><p>When the second person arrives, they join the queue behind the first person (enqueued).</p>
</li>
<li><p>This process continues until all people have joined the queue.</p>
</li>
<li><p>When it's time for the tickets to be sold, the first person in line (at the front of the queue) gets their ticket (dequeued).</p>
</li>
<li><p>The next person in line now becomes the first person and they get their ticket (dequeued).</p>
</li>
<li><p>This process continues until all people have gotten their tickets.</p>
</li>
</ol>
<p>In this example, the queue ensures that everyone gets a ticket in the order they arrive, without any confusion or cutting in line.</p>
<h2 id="heading-array-implementation">Array Implementation</h2>
<p>The Array object in JavaScript can be used to implement a queue using inbuilt array methods. Arrays have a push() method which allows us to add elements to the end of the array (enqueue) and a shift() method which allows us to remove the first element from the array (dequeue).</p>
<p>For example, let's consider the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> queue = []
queue.push(<span class="hljs-number">1</span>) <span class="hljs-comment">//enqueue 1</span>
queue.push(<span class="hljs-number">2</span>) <span class="hljs-comment">//enqueue 2</span>
queue.push(<span class="hljs-number">3</span>) <span class="hljs-comment">//enqueue 3</span>
<span class="hljs-built_in">console</span>.log(queue) <span class="hljs-comment">//[1,2,3]</span>
queue.shift() <span class="hljs-comment">//dequeue 1</span>
queue.shift() <span class="hljs-comment">//dequeue 2</span>
queue.shift() <span class="hljs-comment">//dequeue 3</span>
<span class="hljs-built_in">console</span>.log(queue) <span class="hljs-comment">// []</span>
</code></pre>
<p>As you can see, we have implemented a basic queue using an array in Javascript. The array or the queue was initially empty. Then three values, 1, 2, and 3, are enqueued to the queue using the push() method. The console.log statement shows the contents of the queue array which is [1,2,3]. Then, three dequeue operations are performed using the shift() method which removes the values from the front of the queue. The first call to shift() removes 1, the second call removes 2, and the third call removes 3. After these three dequeue operations, the queue array is empty, as seen from the output of the second console.log statement which is [].</p>
<h2 id="heading-class-based-implementation">Class-based Implementation</h2>
<p>In addition to using arrays, queues can also be implemented as classes in JavaScript. A class-based implementation provides a more object-oriented approach and can be used to encapsulate the data and behavior of a queue. This can be especially useful in larger projects where you want to maintain a clear separation between different components.</p>
<p>Here's an example of how you can implement a stack as a class in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Queue</span></span>{
    <span class="hljs-keyword">constructor</span>(){
    <span class="hljs-built_in">this</span>.storage= {};
    <span class="hljs-built_in">this</span>.head = <span class="hljs-number">0</span>
    <span class="hljs-built_in">this</span>.tail = <span class="hljs-number">0</span>
    }
    <span class="hljs-comment">//enqueue</span>
    enqueue(element){
    <span class="hljs-built_in">this</span>.storage[<span class="hljs-built_in">this</span>.tail] = element
    <span class="hljs-built_in">this</span>.tail++
    }
    <span class="hljs-comment">//dequeue</span>
    dequeue(){
    <span class="hljs-keyword">const</span> returnVal = <span class="hljs-built_in">this</span>.storage[<span class="hljs-built_in">this</span>.head]
    <span class="hljs-keyword">delete</span> <span class="hljs-built_in">this</span>.storage[<span class="hljs-built_in">this</span>.head]
    <span class="hljs-built_in">this</span>.head++
    <span class="hljs-keyword">return</span> returnVal
    }
}

<span class="hljs-keyword">const</span> ticketLine = <span class="hljs-keyword">new</span> Queue()
ticketLine.enqueue(<span class="hljs-string">"Alex"</span>)
ticketLine.enqueue(<span class="hljs-string">"Jack"</span>)
ticketLine.enqueue(<span class="hljs-string">"James"</span>)
<span class="hljs-built_in">console</span>.log(ticketLine) <span class="hljs-comment">//{storage: {0:"Alex",1:"Jack",2:"James"}, head: 0, tail: 3}</span>
ticketLine.dequeue()
ticketLine.dequeue()
ticketLine.dequeue()
<span class="hljs-built_in">console</span>.log(ticketLine) <span class="hljs-comment">//{storage: { }, head: 3, tail: 3}</span>
</code></pre>
<h2 id="heading-use-case">Use Case</h2>
<p>Queues are often utilized in a variety of real-life applications and systems where a first-come-first-serve order needs to be maintained.</p>
<p>For instance, a queue can be used to manage print jobs in a printer where the first job sent will be printed first and the ones sent later will follow suit. In operating systems, queues are used for task scheduling where tasks added first will be executed first and the ones added later will follow. Queues can also be used for resource sharing, such as network connections or CPU time, where when a resource is requested, the request is added to the end of the queue and when the resource becomes available, it is assigned to the request at the front of the queue.</p>
<p>The ability to process data in a specific order makes queues a valuable tool in a wide range of applications.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>A queue is a useful data structure for tasks that require items to be processed in the order they are received. In this article, we have discussed the simplest implementation of the queue data structure. There are many ways to extend and refine our implementation. I recommend continuing to explore implementations and adapting them to your need.</p>
]]></content:encoded></item><item><title><![CDATA[Implementing Stack Data Structure in Javascript]]></title><description><![CDATA[A stack is a linear data structure that follows the Last In First Out (LIFO) or the First In Last Out (FILO) principle. This means that the last element…]]></description><link>https://shahxcode.hashnode.dev/implementing-stack-data-structure-in-javascript</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/implementing-stack-data-structure-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[data structures]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Sun, 05 Feb 2023 13:01:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675557472470/b3b826ea-6537-4106-bbd3-4020f6c74765.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A stack is a linear data structure that follows the Last In First Out (LIFO) or the First In Last Out (FILO) principle. This means that the last element added to the stack will be the first one to be removed. Stacks are used in a variety of applications, including but not limited to memory management, expression evaluation, and web page history navigation. In this article, we will be discussing the implementation of stacks in JavaScript.</p>
<h2 id="heading-basics-of-a-stack">Basics of a Stack</h2>
<p>The stack data structure is similar to a real-life stack. For instance, think of a stack as a tall tower of plates. When you want to add a plate, you put it on top of the tower. When you want to take a plate, you only take the one that is on the top.</p>
<p>When we add something to a stack, we call it "pushing" the item into the stack. When we take something from the stack, we call it "popping" the item out of the stack. When we want to check what is the top most (last) item in the stack, we call it "peeking" into the stack.</p>
<h2 id="heading-array-implementation">Array Implementation</h2>
<p>JavaScript has built-in support for stacks through the Array object. Arrays in JavaScript have a conveniently named push() method which allows us to add elements to the end of the array, and a pop() method which allows us to remove the last element from the array. While there is no peek() method built in, we can use our understanding of javascript arrays to access the last element through the length property.</p>
<p>For example, let's consider the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> stack = [];
<span class="hljs-comment">//push</span>
stack.push(<span class="hljs-number">1</span>);
stack.push(<span class="hljs-number">2</span>);
stack.push(<span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(stack); <span class="hljs-comment">// Output: [1, 2, 3]</span>
<span class="hljs-comment">//pop</span>
stack.pop();
<span class="hljs-built_in">console</span>.log(stack); <span class="hljs-comment">// Output: [1, 2]</span>
<span class="hljs-comment">//peek</span>
stack[stack.length<span class="hljs-number">-1</span>]
<span class="hljs-built_in">console</span>.log(stack[stack.length<span class="hljs-number">-1</span>]) <span class="hljs-comment">//2</span>
</code></pre>
<p>As you can see, we have implemented a basic stack using an array and its push() and pop() methods. Following the LIFO principle, we push 1, 2 and 3 into the array and then pop out the last value. Here is a quick illustration to visualize this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675560806590/ccfe0b4e-1954-48e3-9271-4948bcb2cd1e.png" alt="&quot;A visual representation of JavaScript code demonstrating the use of a stack data structure. The code shows how to push elements onto the stack, pop elements off the stack, and retrieve the top element using the peek operation." class="image--center mx-auto" /></p>
<h2 id="heading-class-based-implementation">Class-Based Implementation</h2>
<p>In addition to using arrays, stacks can also be implemented as classes in JavaScript. A class-based implementation provides a more object-oriented approach and can be used to encapsulate the data and behavior of a stack. This can be especially useful in larger projects where you want to maintain a clear separation between different components.</p>
<p>Here's an example of how you can implement a stack as a class in JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Stack</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.items = [];
    }
    push(element) {
        <span class="hljs-built_in">this</span>.items.push(element);
    }
    pop() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.items.pop();
    }
    peek() {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.items[<span class="hljs-built_in">this</span>.items.length - <span class="hljs-number">1</span>];
    }
}
</code></pre>
<p>In this example, we've defined a Stack class with a constructor that initializes an empty array for storing elements. We've also added push(), pop(), and peek() methods to the class, allowing us to perform basic stack operations. This implementation gives us the flexibility to create multiple instances of the Stack class, each with its own separate data and behavior.</p>
<p>By using classes, we can also add additional functionality to our stacks as needed, such as methods for printing the contents of the stack or checking the size of the stack. Additionally, we can create subclasses that inherit from our Stack class and extend its behavior in new and interesting ways.</p>
<h3 id="heading-class-based-implementation-with-objects">Class-based Implementation with Objects</h3>
<p>In JavaScript, we can also have a class-based implementation of a stack using objects to store values instead of an array.</p>
<p>Here is an example of creating a class-based stack data structure using object data type for storage:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Stack</span></span>{
  <span class="hljs-keyword">constructor</span>(){
    <span class="hljs-built_in">this</span>.storage = {}
    <span class="hljs-built_in">this</span>.size = <span class="hljs-number">0</span>
  }

  push(element){
    <span class="hljs-built_in">this</span>.size++
    <span class="hljs-built_in">this</span>.storage[<span class="hljs-built_in">this</span>.size] = element
  }

  pop(){
    <span class="hljs-keyword">const</span> returnVal = <span class="hljs-built_in">this</span>.storage[<span class="hljs-built_in">this</span>.size]
    <span class="hljs-keyword">delete</span> <span class="hljs-built_in">this</span>.storage[<span class="hljs-built_in">this</span>.size]
    <span class="hljs-built_in">this</span>.size--
    <span class="hljs-keyword">return</span> returnVal
  }

  peek(){
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.storage[<span class="hljs-built_in">this</span>.size]
  }
} 

<span class="hljs-keyword">const</span> fruitStack = <span class="hljs-keyword">new</span> Stack
fruitStack.push(<span class="hljs-string">"Orange"</span>) <span class="hljs-comment">//{ '1': 'Orange' }</span>
fruitStack.push(<span class="hljs-string">"Grapes"</span>) <span class="hljs-comment">//{ '1': 'Orange', '2': 'Grapes' }</span>
fruitStack.push(<span class="hljs-string">"Apple"</span>) <span class="hljs-comment">//{ '1': 'Orange', '2': 'Grapes', '3': 'Apple' }</span>
fruitStack.pop() <span class="hljs-comment">//Apple</span>
fruitStack.pop() <span class="hljs-comment">//Grapes</span>
fruitStack.push(<span class="hljs-string">"Apple"</span>) <span class="hljs-comment">//{ '1': 'Orange', '2': 'Apple' }</span>
fruitStack.peek() <span class="hljs-comment">//Apple</span>
</code></pre>
<h2 id="heading-use-cases">Use Cases</h2>
<p>Stacks are commonly used in web development, particularly in the context of web page navigation. Whenever you click a link on a web page, your browser pushes the URL of the new page onto the stack. When you press the back button, your browser pops the last URL from the stack and navigates back to the previous page. This is just one example of how stacks can simplify your code by allowing you to manage a list of elements in a straightforward way.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>A stack is a powerful and versatile data structure that can simplify your code in a variety of applications. It provides an elegant solution that is easy to implement and understand. If you haven't already, give it a try in your next JavaScript project and see how it can simplify your code.</p>
]]></content:encoded></item><item><title><![CDATA[Tip: console.table()]]></title><description><![CDATA[In this article, I am going to discuss a javascript console method called console.table(). I find it useful for casual debugging and don't see much about…]]></description><link>https://shahxcode.hashnode.dev/tip-consoletable</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/tip-consoletable</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[Google Chrome]]></category><category><![CDATA[Javascript library]]></category><category><![CDATA[js]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Sat, 04 Feb 2023 00:28:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675470444793/15156cfc-a5fc-43db-9d67-7638b62f59bb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, I am going to discuss a javascript console method called <code>console.table()</code>. I find it useful for casual debugging and don't see much about it online so I figured I'd share it.</p>
<h2 id="heading-what-is-consoletable">What is console.table()</h2>
<p><code>console.table()</code> is a method that allows you to log arrays and objects as a table in the browser's console. This can be incredibly helpful when dealing with large amounts of data, as it makes it easier to read and understand. Unlike <code>console.log()</code>, <code>console.table()</code> presents data in a more organized and structured way, making it easier to identify patterns and relationships in your data.</p>
<h2 id="heading-example">Example</h2>
<p>Here's an example of how to use <code>console.table()</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> employees = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">"Developer"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Jane Doe"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">27</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">"Designer"</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Jim Smith"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">35</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">"Manager"</span> }
];
<span class="hljs-built_in">console</span>.table(employees);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675469178606/adbe5586-888b-4a9c-b79d-56023a27f8fc.png" alt="A screenshot of the browser's dev tools console displaying data stored in employees array as a table using console.log.  " class="image--center mx-auto" /></p>
<p>In this code, the employees array will be logged as a table in the console, with each object displayed as a row. The properties of each object are displayed as columns, making it easy to see the data at a glance.</p>
<p>Another great feature of <code>console.table()</code> is the ability to filter the data that is displayed. This can be useful when you only want to see a specific subset of your data. You can do this by passing an array of column names as the second argument to <code>console.table()</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.table(employees, [<span class="hljs-string">"name"</span>, <span class="hljs-string">"age"</span>]);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675469335038/ddd6c6b9-f33f-47e3-ac4b-a928d834f365.png" alt="A screenshot of the browser's dev tools console displaying data stored in employees array as a table using console.log. " class="image--center mx-auto" /></p>
<p>In this example, only the name and age properties will be displayed in the table.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, <code>console.table()</code> is a convenient way to display your data in the browser's dev tools. Its presentation of arrays and objects as a table makes it easier to comprehend and spot patterns in your data. Instead of relying solely on <code>console.log()</code>, give <code>console.table()</code> a shot the next time you need to debug your code.</p>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/console/table">Link to the MDN doc</a>.</p>
]]></content:encoded></item><item><title><![CDATA[How To Use Multiple Submit Buttons In An HTML5 Form (No Javascript)]]></title><description><![CDATA[HTML form element makes it easy to take an action when a button is clicked through its `action` attribute. However, if you have tried to create a…]]></description><link>https://shahxcode.hashnode.dev/how-to-use-multiple-submit-buttons-in-an-html5-form-no-javascript</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/how-to-use-multiple-submit-buttons-in-an-html5-form-no-javascript</guid><category><![CDATA[HTML5]]></category><category><![CDATA[forms]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Fri, 27 Jan 2023 15:23:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674830385165/1f972002-ebcf-4ece-becd-d1ea83bb9e04.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>HTML form element makes it easy to take an action when a button is clicked through its `action` attribute. However, if you have tried to create a multi-button form that takes specific actions based on which button is clicked, you would have realized that things don't work as you'd want them to work i.e. clicking any button leads to the same action that is defined in the form element's action attribute. You can counter this situation by using Javascript. That is what people used to do before HTML5 (many still do), but HTML5 has given us a native attribute for button and input elements, which makes using multiple submit buttons in a form much easier.</p>
<h2 id="heading-the-formaction-attribute">The Formaction Attribute</h2>
<p>The formaction (pronounced: form action) attribute is used in HTML5 forms to specify the URL of the page that will handle the form data when submitted. This attribute is used in conjunction with the element's type attribute, which is set to "submit" or "image". The formaction attribute overrides the action attribute of the form element, allowing for specific actions to be taken based on the button that was clicked.</p>
<p>For example, consider a form with three submit buttons, one labeled "Submit", one labeled "Save" and the other labeled "Delete".</p>
<pre><code class="lang-javascript">&lt;form action=<span class="hljs-string">"/submit"</span>&gt;
    <span class="hljs-comment">//clicking on Submit button leads to "/submit" route</span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
    <span class="hljs-comment">//clicking on Save button leads to "/save" route</span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">formaction</span>=<span class="hljs-string">"/save"</span>&gt;</span>Save<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
    <span class="hljs-comment">//clicking on Delete button leads to "/delete" route</span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">formaction</span>=<span class="hljs-string">"/delete"</span>&gt;</span>Delete<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span> 
&lt;/form&gt;
</code></pre>
<p>In the example scenario, clicking on the Submit button will trigger the default form action which is the "/submit" route. However, clicking on the Save and Delete buttons will trigger their respective routes. Notice the latter buttons have a formaction attribute that defines their action and overrides the default action of the form.</p>
<h2 id="heading-use-image-as-a-submit-button">Use Image As A Submit Button</h2>
<p>The formaction attribute can also be used with the element's type attribute set to "image", which allows for an image to be used as the submit button. In this case, the formaction attribute specifies the URL that the form data will be sent to when the image is clicked.</p>
<h2 id="heading-compatibility">Compatibility</h2>
<p>It's important to note that the formaction attribute is only supported in HTML5 and is not supported in previous versions of HTML. Additionally, the formaction attribute is not supported in some web browsers, so it's important to test your forms in multiple browsers to ensure compatibility.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The formaction attribute is useful for creating more dynamic and interactive forms. It allows for different actions to be taken based on which button is clicked, without the need to write javascript to manage actions, making it a valuable addition to any web developer's toolkit.</p>
]]></content:encoded></item><item><title><![CDATA[Do You Know The ~~ Shorthand?]]></title><description><![CDATA[I've been working on coding challenges daily for a while now, and I'm always discovering new ways to solve problems, new tricks, and shorthand techniques…]]></description><link>https://shahxcode.hashnode.dev/do-you-know-the-shorthand</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/do-you-know-the-shorthand</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Codewars ]]></category><category><![CDATA[webdev]]></category><category><![CDATA[javascript framework]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Tue, 24 Jan 2023 20:27:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674591629572/8417c896-5be9-460a-8c89-e9023bb7677b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I've been working on <a target="_blank" href="https://github.com/shahx95/coding-challenges">coding challenges daily</a> for a while now, and I'm always discovering new ways to solve problems, new tricks, and shorthand techniques. Recently, I came across this handy shorthand for Math.floor() and it totally, wait for it, floored me. (Lol)</p>
<h2 id="heading-what-is-the-shorthand">What is the Shorthand</h2>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log( <span class="hljs-built_in">Math</span>.floor(<span class="hljs-number">123.456789</span>) ) <span class="hljs-comment">//123</span>
<span class="hljs-built_in">console</span>.log( ~~<span class="hljs-number">123.456789</span> ) <span class="hljs-comment">//123</span>
</code></pre>
<p>So in JavaScript, the <code>~~</code> can be used as a shorthand for <code>Math.floor()</code> which is used to round down a decimal number to the nearest integer. The <code>~~</code> operator is actually a double bitwise NOT operator, which essentially performs two NOT operations on the number, effectively returning the same result as <code>Math.floor()</code>.</p>
<h3 id="heading-huh-the-not-operator-you-say">"Huh? The NOT operator, you say?"</h3>
<p>The NOT operator (<code>~</code>) inverts the bits of a number, effectively flipping all the bits from 0 to 1 and vice versa. When you apply the NOT operator twice (<code>~~</code>), it reverts the bits back to their original state, effectively returning the original number.</p>
<p>It is commonly used as a faster alternative to <code>Math.floor()</code> method because the bitwise operator is generally faster than the <code>Math.floor()</code> method, so it can be a good option for performance-critical code.</p>
<h3 id="heading-shorthand-for-number-too">Shorthand for Number() too</h3>
<p>Since the ~~ effectively returns the floored number, it can also be used when you want to convert a string value to an integer.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log( <span class="hljs-built_in">Number</span>(<span class="hljs-string">"10"</span>) ) <span class="hljs-comment">//10</span>
<span class="hljs-built_in">console</span>.log( ~~<span class="hljs-string">"10"</span> ) <span class="hljs-comment">//10</span>
</code></pre>
<h2 id="heading-caution">Caution</h2>
<p>~~ can be used as a quick shorthand for Math.floor() for <em>positive</em> numbers. Keep in mind, though, that it doesn't give the same results for negative numbers. It simply truncates the decimal part as shown below:</p>
<pre><code class="lang-javascript">~~<span class="hljs-number">5.5</span>    <span class="hljs-comment">// =&gt; 5  (same as Math.trunc(5.5) and Math.floor(5.5))</span>
~~(<span class="hljs-number">-5.5</span>) <span class="hljs-comment">// =&gt; -5 (same as Math.trunc(-5.5) but NOT the same as Math.floor(-5.5), which would give -6 )</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>While it's cool to learn about the ~~ shorthand and have it in the knowledge bank, it's important to also consider the readability of your code when using it. As a developer, I prefer to have my code easy to read and understand, even if it takes a couple more lines (or words in the case of Math.floor()). In my experience, this saves a lot of pain while maintaining the code. Therefore, I don't see myself making much use of this shorthand.</p>
<p>P.S. The coding challenge where I discovered the shorthand: <a target="_blank" href="https://www.codewars.com/kata/57c15d314677bb2bd4000017">https://www.codewars.com/kata/57c15d314677bb2bd4000017</a></p>
]]></content:encoded></item><item><title><![CDATA[The Shocking Truth About Backend Frameworks: Which One is Right for You?]]></title><description><![CDATA[Choosing a backend framework can be an overwhelming task for developers, especially for those just starting out in their careers. With so many options…]]></description><link>https://shahxcode.hashnode.dev/the-shocking-truth-about-backend-frameworks</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/the-shocking-truth-about-backend-frameworks</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[backend]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[framework]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Sun, 22 Jan 2023 19:35:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674414077729/79aaa267-ba5a-4461-9c1b-0f0c707a6919.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Choosing a backend framework can be an overwhelming task for developers, especially for those just starting out in their careers. With so many <a target="_blank" href="https://radixweb.com/blog/best-backend-frameworks">options</a> available, it can be difficult to know where to begin and which framework is the best fit for their career prospects.</p>
<p>Recently, on a popular programming subreddit, a user asked for advice on which backend framework to choose to kickstart their career. After providing my thorough perspective on the topic, I realized that my comment was substantial enough to warrant creating a blog post out of it, and that's how I ended up creating this post.</p>
<h2 id="heading-so-whats-the-magic-framework">So what's the magic framework</h2>
<p>There is none. Becoming a backend developer is a challenging and rewarding journey, but it's important to remember that the framework you choose to work with is just a tool. The real goal is to learn the fundamentals of backend development, such as routing, templating, middleware, and database communication. These concepts are not disjoint and are applicable across multiple frameworks.</p>
<p>It's easy to get caught up in the hype of a particular framework and frame yourself as a "Node/Express" developer, for example. But what happens when you need to write code in Django? If your understanding of the fundamentals is solid, you'll be able to adapt to the new framework with ease.</p>
<p>Think of it like a woodworker. A skilled woodworker doesn't just know how to use a hammer, they understand how to use all the tools in their toolbox. They know when to use a hammer, when to use a mallet, and how to use each tool to achieve the desired outcome. Similarly, as a backend developer, it's important to understand the concepts, not just the tools.</p>
<p>So, don't get too caught up in the framework choice. Start with something that you're comfortable with and focus on learning the basics. Once you have a solid understanding of the fundamentals, you'll be able to adapt to any framework and write clean, efficient, and maintainable code.</p>
<h2 id="heading-i-still-need-to-pick-a-framework-to-start-with">I still need to pick a framework to start with...</h2>
<p>Right. So let's discuss how to go about making that choice.</p>
<p>Consider the job market in your location as a way to decide on the framework to pursue. Different regions may have varying demands for certain frameworks. For example, if you are looking for a job in a startup in Silicon Valley, you may find that there is a high demand for Node.js and Express.js developers, whereas if you are looking for a job in a government organization in Washington, D.C. you may find that Java and Spring are more in demand.</p>
<p>It's important to be aware of the job market and job requirements in your area and to have a good understanding of the locally in-demand framework to increase your chances of finding a job that fits your skills and interests.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In short, the framework is a means to an end, not an end in itself. The goal is to learn the basics of backend development and become a skilled developer who can adapt to any tool. '<a target="_blank" href="https://medium.com/@jgratereaux/why-is-it-important-to-be-agnostic-in-software-development-5f9d5394f573">Tech agnostic</a>' is the term proficient developers like to use these days. Remember, the true measure of a developer's proficiency is not the tool they use but the quality of their code and ability to solve problems.</p>
]]></content:encoded></item><item><title><![CDATA[Breaking down CORS]]></title><description><![CDATA[With CORS, a website cannot use Javascript to request data from another origin unless the web server at that other origin explicitly permits it.]]></description><link>https://shahxcode.hashnode.dev/breaking-down-cors</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/breaking-down-cors</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[CORS]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Mon, 13 Jun 2022 17:13:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1655139826318/p1ME18fx_.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>CORS or Cross Origin Resource Sharing can seem frustrating when you're first starting out with client side development, but fundamentally it exists to protect information and give server owners greater control over how their stuff is used.</p>
<p>To understand Cross Origin Resource Sharing, let's first break it down and understand the individual parts that make it up.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1655138926270/jB1gzRoJ1.png" alt="breaking-down-cors.png" /></p>
<h2 id="heading-origin">Origin</h2>
<p>Origin refers to a URL's scheme (HTTP or HTTPS), its full hostname (domain or subdomain), and its port (by default the port for HTTP is 80 and for HTTPS is 443. These ports do not need to be explicitly mentioned). </p>
<p>For example, let us consider Hashnode's URL: "https:// www. hashnode.com:443". The URL has a scheme of HTTPS, "www. hashnode.com" as the hostname and 443 as its port. </p>
<p>Two URLs are said to be of the same origin when they both have the same scheme, the same full hostname, and the same port.</p>
<p>This means that "https://hashnode.com/n/javascript" and "https://hashnode.com/n/reactjs" have the same origin - they have the same scheme (HTTPS), the same full hostname (www.hashnode.com), and the same port (an implicit port 443). The different paths to javascript and reactjs do not matter.</p>
<p>However, if any of the aforementioned three attributes differ for two URLs, they are considered to have different origins. Again, using Hashnode's URLs as examples: "https:// www. shahxcode.hashnode.dev/" and "https:// www. julia.hashnode.dev/" are of different origins because they have different subdomains which makes the full hostnames different. The schemes and ports for both domains are still the same.</p>
<p>When working locally, local servers running on different ports are of different origins.</p>
<p>Now that we understand what origin refers to, let's focus on the Resource part of CORS.</p>
<h2 id="heading-resource">Resource</h2>
<p>A resource is what the web server responds back with when it receives a request. The resource can be an HTML file, a JSON object, an image file, or anything else that you can request from a web server. </p>
<p>For example, a web server receives a request when you enter a URL in the browser, click on an embedded link or request a URL through the fetch method in the client-side code. When "https://hashnode.com/" is entered in the browser, Hashnode's server responds with a resource which is the HTML file used for rendering Hashnode's homepage.</p>
<h2 id="heading-putting-it-together">Putting it Together</h2>
<p>Keeping in mind what Origin and Resource mean from the above sections, one can begin to understand what Cross Origin Resource Sharing means.  It's about sharing resources - sending and receiving - across origins - between two origins that are different from one another.</p>
<h2 id="heading-why-do-we-need-cors">Why do we need CORS</h2>
<p>When we are using websites, our browser is storing cookies that are used for session information and authentication by the respective websites. Every single time we make a call to the domain of the website we are using, our browser sends the respective domain's cookies as part of the request to the web server. This helps the web server identify us and verify our session, among other things.</p>
<p>For instance, when we log into "https://hashnode.com/", we have a cookie stored for our browsing session. You can view the cookies stored for Hashnode by visiting your browser's dev tool, going to the Application tab, and dropping down the menu for Storage.</p>
<p>However, this leaves us susceptible to vulnerability. </p>
<p>When accessing URLs through a browser, we as users can be tricked into making a request which we do not intend to make. A common way of doing this is by making a fetch request through the client-side JS when you visit a website. The website itself may seem innocuous and as a user, you will not even know that a fetch request has been made to a different URL unless you keep an eye on your network access tab. The browser will send the fetched website's session information in the request header, as it normally does for all requests. The web server which receives this sneaky fetch request cannot realize that it was sent without your permission and assumes you are a normal user requesting the URL resource. Between this transfer of data, the cookies sent in the request header can be sniffed and stored independently. The stored cookies can be used to access information while posing as a routine session of yours.</p>
<p>Let's consider an example. Suppose you click on a link shared in a Reddit comment and that link takes you to a website. When this website loads, a fetch request is sneakily made through the client-side Javascript to Reddit.com. You will not note this request being made. Your session information and other cookies are sent with this request to the Reddit web server. The Reddit web server assumes that it is a routine request made by you; it cannot figure out that this is a sneaky fetch request made without your consent. The session information from that request could be sniffed and sent to another computer from where it can be used to access your Reddit account as you.</p>
<p><strong>With CORS, a website cannot use Javascript to request data from another origin unless the web server at that other origin explicitly permits it.</strong> This can be done by including a header in the response called Access-Control-Allow-Origin, which can be used to specify other origins which are allowed to request that specific resource. </p>
<p>Simply said, every web server has its own origin. If a request is sent from anywhere except for this origin, it will not be able to access the resource unless the web server explicitly allows it to.   </p>
<p>If a URL is sending a request to a web server, but it does not have the same origin as that of the web server then it will not be able to access the server's response. In this case, you will get an error in the console and if you check the Network tab of your developer tool, you will notice the response headers don't include Access-Control-Allow-Origin.</p>
<p>Access-Control-Allow-Origin gives the web server control over which website can access the server. "Access-Control-Allow-Origin: *" in the response header will allow all and any origin to access the server. "Access-Control-Allow-Origin: https://reddit.com" will only allow Reddit to access the resource sent by the web server.</p>
<p>To learn more about the technical details of CORS and the functionality of the response headers, check out the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">MDN page about CORS</a>.</p>
<h2 id="heading-why-does-the-server-respond-back-with-a-resource-at-all">Why does the server respond back with a resource at all?</h2>
<p>When a request comes from an origin that is not whitelisted by the server, the server still responds back with the resource to the browser. This often leads to the question that why would a resource be sent at all? </p>
<p>For a browser, there is no way to differentiate requests. Whether you enter a URL in the browser, click on a link or get a sneaky fetch request running on your end, the browser sends the same request to the web server. Similarly, on the web server end, there is no way to tell if the request was initiated maliciously or intentionally.</p>
<p>The only point at which you can tell the difference is in the browser where the request came from, so that's why the web server responds back with the resource and its Access-Control-Allow-Origin list in the response header. If the origin is different/not permitted, the browser prevents the client-side Javascript from accessing the resource and throws an error.</p>
<h2 id="heading-ending-with-an-analogy">Ending with an analogy</h2>
<p>The majority of developers will deal with CORS issues at some point. However, when they do face CORS issues, they focus on bypassing the problems by trying different solutions listed on StackOverflow. While this approach may do the job, by doing this many developers remain unaware of what is happening, or rather, why certain things are happening. Hopefully, this article helps paint a big picture in your mind. Like with most things in tech, there are still many things within CORs that you can deep dive into. </p>
<p>Let's end the article with the Visa and Passport Control Analogy I came up with to remember how CORS works: </p>
<p>Mr. Request wants to go on a vacation, but the country he wants to visit requires a visa. So Mr. Request submits a visa application (request) at the embassy (web server). The visa officer takes Mr. Request's case and hands him the decision letter (response). When Mr. Request goes to the airport, the passport control checks the decision letter (checks Access-Control-Allow-Origin) to decide if Mr. Request can fly to the country (access the resource) or not.</p>
]]></content:encoded></item><item><title><![CDATA[Reflections: My journey of learning to code]]></title><description><![CDATA[This is an article about my journey through the 100Devs BootCamp. At the time of publishing, I am 1/3rd of the way through this program. March 14, 2022…]]></description><link>https://shahxcode.hashnode.dev/reflections-my-journey-of-learning-to-code</link><guid isPermaLink="true">https://shahxcode.hashnode.dev/reflections-my-journey-of-learning-to-code</guid><category><![CDATA[#beginners #learningtocode #100daysofcode]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[bootcamp]]></category><dc:creator><![CDATA[Shah]]></dc:creator><pubDate>Mon, 21 Mar 2022 23:58:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1647907041962/lCFbwM3Ab.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>This is an article about my journey through the <a target="_blank" href="https://leonnoel.com/100devs">100Devs BootCamp</a>. At the time of publishing, I am 1/3rd of the way through this program.</strong></p>
<hr />
<p>March 14, 2022. 5:34 AM.</p>
<p>I collapsed in my chair, massaged my eyes, and took a sigh of relief. “We had the logs, and we carried them all,” I muttered under my breath - proud of myself for managing through the 9.5 hours of the super review session. </p>
<p>This is a different me. A couple of months ago, I’d be asleep by this time. Hoping to wake up early and have a productive day, yet knowing that it was unlikely to happen. A raging introvert content with where life was taking me. While I knew I wanted a change, I had no real drive, purpose, or motivation to plan out my path.</p>
<p>The present me does not wake up like an accident. My days are more deliberate now. I have a six-hour block fixed in my daily schedule on Trello - divided into 40/20 Pomodoro sessions. My day revolves around this six-hour block. </p>
<p>I am privileged that I have a remote job at the moment. I work as a freelance content creator and am able to maintain a healthy balance between my work, study, and life.</p>
<p>Realization of my privileges, and the lack of, is one of the many things I have learned in this journey. It is something that Leon, my teacher at 100Devs, reinforces. The concept of everyone not being equally lucky in terms of their learning capacity, knowledge, time, and wealth is one that we all have at the back of our minds, but for me, it was not until the last two months that I was consciously putting to use. </p>
<p>Now when I come across a social media post about a cool project or about landing a job, I don’t get discouraged or feel envious. I am not aware of the privileges they had resulting in their success. I take their achievements as goals that I can achieve as well, and until I do, I am happy to cheer for them. </p>
<p>I understand that as long as I am honest with myself and do justice to my privileges, chances are high that I will be successful.    </p>
<p>Over the last two months, I have gone through the grind of learning HTML, CSS, and now, some Javascript. We have focused on nailing the fundamentals down. In the process, I have created multiple websites that are now a part of my portfolio, which will be used to get a freelance client by the end of the month. The pieces are coming together. </p>
<p>This super review was a flashback of how far we have come. I have learned almost every single day. And when I have not, I have relaxed - deliberately. I say deliberately because I have approached my breaks from learning as a chance to re-energize and come back to it with the same valor I had on day one.</p>
<p>What started as a journey to become a full-stack web developer, has become a journey of discovering myself and overcoming my weaknesses. </p>
<p>I mentioned the realization of privileges earlier. There is so much more to add. The journey has influenced the way I learn, the way I go about my day, the way I meet people, and even the way I sleep. </p>
<p>It has forced me to get out of my comfort zone and tasked me with challenges that seemed insurmountable just a few weeks ago. One such challenge was networking with other people in tech. As an introvert, networking was my worst nightmare. Yet here I am a month into networking and I have had 24 meetings already, with my calendar full until the end of April.</p>
<p>I certainly didn’t expect this change when I started on this journey. However, these are the skills that will, perhaps, be my most important takeaways no matter where this journey takes me. </p>
<p>The cornerstone of my growth in this journey has been the 100Devs community. Everyone who has gone through a struggle and has experienced failing will know how important a support base is. This is true when it comes to learning to code as well. </p>
<p>The community has people from all walks of life and all ages, who are willing to give their input and help others out, with empathy and kindness. It made me realize that I am not alone. That there are many that are in the same muck as me and that there are many who have made it out and are now successful in their career. </p>
<p>I try to hang out and jump in to help as much as I can as well. Even when I don't feel like actively participating, just going through the discussions and resonating with them provides me with encouragement.  </p>
<p>Not every day will be my day. There are days when nothing works and then there are days when I don’t even feel like trying. At such times, I have to use every ounce of my mental strength to get myself in line with my daily schedule. And yet, there has been a day when I was unable to. </p>
<p>I tell myself that this is okay and ensure that I give myself the grace to fail and to get up again. Throughout the day, I make use of positive affirmations and remind myself of my small wins. And when I feel low, I visit the celebrations channel of our community and browse through the success stories to remind myself why I am doing this. And why I need this.  </p>
<p>I fear that if I let my discipline go loose, I will fall back into the abyss from which I have given my heart and soul to come out. I have promised myself that I will land a job in the industry by the end of the year. There is no way that I know what will happen by then.  Maybe my dream is too far off the horizon. But all I can do is try and believe.</p>
<p>As I write the conclusion of this post, we have had our Sunday office hours. It’s been a week since that super review session. I have set up my Trello for the upcoming week and will now head to the bed, knowing that it’s already made - my guaranteed win of the day.</p>
<p>Until next time.</p>
]]></content:encoded></item></channel></rss>