<?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 Sahil Darji on Medium]]></title>
        <description><![CDATA[Stories by Sahil Darji on Medium]]></description>
        <link>https://medium.com/@sahildarji16?source=rss-bada68918e77------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1wWjRKEwIjrHUvIoge5j0Q.jpeg</url>
            <title>Stories by Sahil Darji on Medium</title>
            <link>https://medium.com/@sahildarji16?source=rss-bada68918e77------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 21:20:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sahildarji16/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[Decoding the Frontend Engineer Interview Experience at Quizizz, 2023.]]></title>
            <link>https://medium.com/@sahildarji16/decoding-the-frontend-engineer-interview-experience-at-quizizz-2023-4d9342b07a3c?source=rss-bada68918e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d9342b07a3c</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[interview-experience]]></category>
            <dc:creator><![CDATA[Sahil Darji]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 08:01:59 GMT</pubDate>
            <atom:updated>2023-11-13T08:01:59.298Z</atom:updated>
            <content:encoded><![CDATA[<p>👋 Hello there!</p><p>I’m Sahil Darji, a Frontend Software Engineer with a bit over 2 years of hands-on experience. Recently, I had the fantastic opportunity to interview for a Frontend Engineering role at <a href="https://quizizz.com/">Quizizz</a>, and I’m truly grateful for the chance they gave me.</p><p>In this article, I’m excited to walk you through my Quizizz interview experience. I’ll be sharing the nitty-gritty details of the interview rounds and the types of questions that came my way. Let’s dive into the journey together!</p><figure><img alt="Thumbnail, quizziz frontend engineer interview exp" src="https://cdn-images-1.medium.com/max/1024/1*rdltDhh-aB1xvgFxvMrAFQ.png" /></figure><p><strong>Table of Contents!</strong><br>· <a href="#0502">Target Audience</a><br>· <a href="#fb37">How I Landed My Frontend Engineering Interview at Quizizz?</a><br>· <a href="#1f37">Overview of Interview Rounds (All elimination rounds)</a><br>· <a href="#eb4f">Round 1 — Frontend Screening Round (Online — 21st Sept, 2023)</a><br>· <a href="#45cb">Round 2 — Frontend Problem Solving Round (Online — 26th Sept, 2023)</a><br>· <a href="#87ab">Round 3 — Culture Fit &amp; Managerial Round (Onsite — 6th Oct, 2023)</a><br>· <a href="#c0d2">Last words</a></p><h3>Target Audience</h3><p>This article is crafted especially for those who are either newcomers to the field or have 1–2 years of experience in frontend engineering. 🌱 If you find yourself in this bracket and have a Quizizz interview on the horizon, you’re in for some valuable insights. 🚀 However, even if your interview is with a different company, fear not! 🌐 This recount of my frontend engineering interview at Quizizz can still be beneficial, as the interview style is commonly shared across various companies. 🎉</p><h3>How I Landed My Frontend Engineering Interview at Quizizz?</h3><p>Fresh out of college, I found myself in a challenging job market with limited offers in hand. 🎓 These were tough times, and I spent my days applying to numerous positions through LinkedIn and other job boards. Then, I stumbled upon a Frontend Engineer opening at Quizizz on LinkedIn. Fortunately, I had a connection working at Quizizz. I reached out to them, and they generously offered to lend a hand by referring my application to Quizizz Talent Acquisition! 🚀</p><p>Approximately two weeks later, I got a call from HR. She initiated with a request for my introduction, followed by some fundamental questions. After that, she provided an insightful overview of Quizizz — its mission, challenges, ongoing projects, and more. Following this, she delved into the specifics of my upcoming interview rounds and efficiently scheduled my initial interview for September 21, 2023.</p><h3>Overview of Interview Rounds (All elimination rounds)</h3><ol><li><strong>Round 1 — Frontend Screening Round (Online — 21st Sept, 2023)</strong></li><li><strong>Round 2 — Frontend Problem Solving Round (Online — 26th Sept, 2023)</strong></li><li><strong>Round 3 — Culture Fit &amp; Managerial Round (Onsite — 6th Oct, 2023)</strong></li></ol><h3>Round 1 — Frontend Screening Round (Online — 21st Sept, 2023)</h3><p>In Round 1, we kicked things off with introductions from both the interviewers and myself. The interviewer then directed the conversation towards some general JavaScript questions, including:</p><ol><li>Explaining the differences between let, const, and var.</li><li>Defining hoisting in JavaScript.</li><li>Elaborating on the concepts of event bubbling and event capturing.</li></ol><p><strong>Output-based JS Questions</strong></p><ol><li><strong>SetTimeout + Promises</strong></li></ol><pre>const promise = new Promise((resolve, reject) =&gt; {<br>  console.log(1);<br>  setTimeout(() =&gt; {<br>    console.log(&quot;timerStart&quot;);<br>    resolve(&quot;success&quot;);<br>    console.log(&quot;timerEnd&quot;);<br>  }, 0);<br>  console.log(2);<br>});<br>promise.then((res) =&gt; {<br>  console.log(res);<br>});<br>console.log(4);</pre><p><strong>2. This keyword</strong></p><pre>const object = {<br>  who: &#39;World&#39;,<br><br>  greet() {<br>    return `Hello, ${this.who}!`;<br>  },<br><br>  farewell: () =&gt; {<br>    return `Goodbye, ${this.who}!`;<br>  },<br>};<br><br>console.log(object.greet());<br>console.log(object.farewell());</pre><p><strong>3. Tricky output</strong></p><pre>let arr = [0, 0, 0, 0, 0];<br>for (var i = 0; i &lt; arr.length - 1; i++) {<br>  setTimeout(() =&gt; {<br>      ++arr[i];<br>      console.log(arr);<br>  }, 1000 * i);  <br>}</pre><pre>let arr = [0, 0, 0, 0, 0];<br>for (let i = 0; i &lt; arr.length - 1; i++) {<br>  setTimeout(() =&gt; {<br>      ++arr[i];<br>      console.log(arr);<br>  }, 1000 * i);  <br>}</pre><p><strong>Machine coding Round</strong></p><p>Next up was the machine coding round. I was tasked with opening CodeSandbox and selecting any framework of my choice to build an accordion component. You can take a look at my CodeSandbox project here: <a href="https://codesandbox.io/s/accordion-frqgjy">Accordion Component</a>.</p><p>This marked the conclusion of Round 1, and I received the good news — I had successfully advanced to Round 2!</p><h3><strong>Round 2 — Frontend Problem Solving Round (Online — 26th Sept, 2023)</strong></h3><p>In Round 2, I faced a 1-hour coding challenge presented in a Google Doc. The document outlined the specifics of the task, including features and other relevant details. My assignment was to create a visualizer for the Insertion Sort algorithm, complete with forward and backward buttons. Feel free to see the <a href="https://github.com/sahil-1602/insertion-visualization">code</a> and the <a href="https://insertion-viz.netlify.app/">deployed</a> version of my creation during that interview.</p><p>This marked the conclusion of Round 2, and I received the good news — I had successfully advanced to Round 3!</p><h3><strong>Round 3 — Culture Fit &amp; Managerial Round (Onsite — 6th Oct, 2023)</strong></h3><p>For this onsite round, Quizizz invited me from Mumbai to Bangalore. I took a flight a day before the interview, giving me a chance to explore a bit of Bangalore XD! The next morning, I arrived at the Quizizz office for the Culture Fit and Manager round, which was conducted by a Senior Engineering Manager.</p><p>The interview commenced with introductions, and the manager posed the following questions:</p><ol><li>Share your experience at Radicali (the internship mentioned on my resume).</li><li>Discuss techniques for performance optimization on the frontend.</li><li>Narrate a specific instance where you improved frontend performance.</li><li>Explain the decision not to join Houseware (my most recent internship) full-time.</li><li>Highlight a project that you take the most pride in.</li></ol><p>I encountered numerous questions related to my resume and frontend engineering skills during the interview. Apologies for any details I might have overlooked, as I’m recalling this experience while writing the article.</p><p>Everything had been going smoothly until this point, and my confidence was intact. However, the game-changer arrived — the SYSTEM DESIGN segment!</p><p>I was presented with a challenging variant of a system design question, similar to the one available at <a href="https://www.greatfrontend.com/questions/system-design/autocomplete">Great Frontend</a>. Since I hadn’t specifically prepared for system design scenarios, I found myself uncertain about how to approach such questions. Unfortunately, my response didn’t meet the interviewer’s expectations, resulting in my ultimate rejection. It was a valuable learning experience, highlighting the importance of preparing for a diverse range of interview scenarios.</p><h3>Last words</h3><p>Despite stumbling on a challenging System Design question that impacted my interview outcome, I chose to view it as a positive turning point. Since then, I’ve committed to practicing and honing my system design skills. Rejections are a natural part of life, serving as stepping stones toward success.</p><p>My advice for interviews is to bring your best self, focusing on your strengths rather than dwelling on what you may not know. Approach problems with confidence, ask thoughtful questions, and seek clarification before diving into solutions. Stay humble, be generous with your knowledge, and maintain a hunger for continuous learning. Best of luck to you in your upcoming interviews — may you shine and rock the interview stage!</p><p>Thank you,<br>Sahil Darji.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d9342b07a3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nailing the 20 Essential ReactJS Interview Questions]]></title>
            <link>https://medium.com/@sahildarji16/nailing-the-20-essential-reactjs-interview-questions-a5b48d78047e?source=rss-bada68918e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5b48d78047e</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Sahil Darji]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 08:21:03 GMT</pubDate>
            <atom:updated>2023-08-29T08:21:03.243Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello there! 👋</p><p>I’m Sahil Darji, and I work as a Frontend Engineer. I’ve spent more than 2 years diving into JavaScript and ReactJS, crafting cool stuff with them. I’ve been lucky to be a part of different startups, where I’ve tackled tricky features using React. I’m a bit of a React fanboy — I just love it! ❤️</p><p>Over time, I’ve gone through quite a few frontend interviews. And you know what? I’ve learned a lot from those experiences. So, I want to share something valuable with you. I’ve put together a list of the top 20 questions that can really help you shine in your next ReactJS interview. These questions are perfect if you’re aiming for junior to mid-level positions. 🚀</p><p>But wait, there’s more! It’s not just my brain working here. I’ve teamed up with some of my fellow frontend pals. They’re React wizards, seriously! 🧙‍♂️ We’ve pooled our thoughts to create a well-rounded set of questions that will give you a solid starting point. 🎯</p><p>So, let’s dive in and get you ready to rock that ReactJS interview! 🌟</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuWVJBRnGmg0TLSh8OPc5A.png" /></figure><p><strong>Table of Contents</strong></p><p><a href="#2413"><em>1. What is React and Why is it So Popular? What are the major features of React that sets it apart?</em></a><em><br></em><a href="#f535"><em>2. When to use a Class Component over a Function Component?</em></a><em><br></em><a href="#5d1d"><em>3. What is the difference between state &amp; props? Why should we not update the state directly?</em></a><em><br></em><a href="#6df4"><em>4. What is Virtual DOM? How Virtual DOM works?</em></a><em><br></em><a href="#34d7"><em>5. What are the different phases of component lifecycle? What are the lifecycle methods?</em></a><em><br></em><a href="#727b"><em>6. State the Advantages &amp; Limitations of React</em></a><em><br></em><a href="#388c"><em>7. What is prop drilling? How can we avoid prop drilling?</em></a><em><br></em><a href="#eeea"><em>8. What are error boundaries in React?</em></a><em><br></em><a href="#6b5c"><em>9. What are hooks ? What is the difference between useMemo &amp; useCallback ?</em></a><em><br></em><a href="#2e95"><em>10. What is Context API? What is Redux? Context API v/s Redux?</em></a><em><br></em><a href="#e388"><em>11. What is the difference between local storage &amp; session storage?</em></a><em><br></em><a href="#ee35"><em>12. What is React fragment?</em></a><em><br></em><a href="#2fe8"><em>13. Design a signup form using React</em></a><em> (coding round)<br></em><a href="#c0ba"><em>14. Why is there a need for using keys in list?</em></a><em><br></em><a href="#38d8"><em>15. Explain — Pure Component, Higher Order Component (HOC), Controlled Component, Uncontrolled Component, Stateful Component, Stateless Component.</em></a><em><br></em><a href="#fa68"><em>16. In your view, what are the most effective guidelines to follow when working with React?</em></a><em><br></em><a href="#b6e3"><em>17. What’s your recommended approach to organizing and structuring files within a React project?</em></a><em><br></em><a href="#a056"><em>18. What are synthetic events in React?</em></a><em><br></em><a href="#3f2b"><em>19. What is the use of ref?</em></a><em><br></em><a href="#f038"><em>20. Is it recommended to use CSS In JS technique in React?</em></a><em><br></em><a href="#3324"><em>Final Words</em></a></p><h3><strong>1. What is React and Why is it So Popular? What are the major features of React that sets it apart?</strong></h3><p>React is an <strong>open-source front-end JavaScript library</strong> that is used for building user interfaces, especially for single-page applications. React was created by <a href="https://github.com/jordwalke">Jordan Walke</a>, a software engineer working for Facebook. It’s popular because it simplifies the process of building complex interfaces, making it easier and faster to develop modern web applications. React’s approach to managing UI updates efficiently is one of the key reasons for its popularity.</p><p><strong>Major Features of React</strong></p><ol><li><strong>Virtual DOM</strong>: React uses a Virtual DOM, which is a lightweight copy of the actual DOM. This allows React to update only the parts of the UI that need to change, making updates faster and more efficient.</li><li><strong>Component-Based Architecture:</strong> React follows a component-based architecture, where UI elements are broken down into reusable components. This modular approach simplifies development, maintenance, and testing.</li><li><strong>Unidirectional Data Flow:</strong> React enforces a unidirectional data flow, meaning data moves in a single direction within the application. This makes it easier to understand how data changes affect the UI.</li><li><strong>JSX (JavaScript XML): </strong>JSX is a syntax extension that allows developers to write UI components using a syntax similar to HTML. It combines JavaScript logic with UI markup, making it more intuitive to work with UI elements.</li><li><strong>Developer Tools:</strong> React comes with powerful developer tools that help in debugging, inspecting component hierarchies, and analyzing performance bottlenecks.</li></ol><h3>2. When to use a Class Component over a Function Component?</h3><p><strong>Class Component:<br></strong>Use a class component when your component needs to manage state, use lifecycle methods, or handle complex logic that involves the component’s state.</p><pre>import React, { Component } from &#39;react&#39;;<br><br>class Counter extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { count: 0 };<br>  }<br><br>  increment = () =&gt; {<br>    this.setState({ count: this.state.count + 1 });<br>  };<br><br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;p&gt;Count: {this.state.count}&lt;/p&gt;<br>        &lt;button onClick={this.increment}&gt;Increment&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>export default Counter;</pre><p><strong>Functional Component<br></strong>Use a function component when you don’t need to manage state or use lifecycle methods, and your component’s role is primarily to render UI based on the input props.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function CounterFunction() {<br>  const [count, setCount] = useState(0);<br><br>  const increment = () =&gt; {<br>    setCount(count + 1);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default CounterFunction;</pre><p>In my view, with the introduction of React Hooks (starting from React 16.8), functional components are progressively aligning with the capabilities of class components. Many of the lifecycle methods now have corresponding hooks in functional components. Therefore, I recommend opting for functional components whenever possible. They are concise, succinct, easy to comprehend, and contribute to a smoother development experience.</p><p>But, if you’re working on a component that has complicated state stuff and needs all the different lifecycle methods that don’t have hooks equivalents, then it’s a good idea to go for class-based components.</p><h3>3. What is the difference between state &amp; props? Why should we not update the state directly?</h3><p><strong>State in React: </strong>Think of “state” as a storage area within a React component where you can keep track of dynamic data that can change over time. It’s like a box where you can put information that might be modified by user interactions or other factors. When state changes, React will automatically re-render the component to reflect the updated information.</p><p><em>For example, in a counter component, the number you’re counting would be stored in the component’s state. If the count changes, React will update the display accordingly.</em></p><p><strong>Props in React:</strong> “Props” (short for properties) are a way to pass data from a parent component to a child component. Imagine you have a component that represents a button. You might want to customize the button’s text, color, or behavior based on where it’s used. Props allow you to send specific data from the parent component to the child component, making it versatile and reusable.</p><p><em>For instance, if you’re creating a “User” component to display user details, you can send the user’s name and profile picture URL as props to that component.</em></p><p><strong>Props v/s State</strong><br>Both <em>props</em> and <em>state</em> are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component. Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.</p><p>In short, “state” is used to manage a component’s internal data that can change, while “props” are used to pass data from parent to child components for customization and configuration.</p><p><strong>Why should we not update the state directly?<br></strong>Updating state directly in React is discouraged because it can lead to unexpected behavior and issues with how components are rendered. React relies on a process called “reconciliation” to efficiently update the user interface based on changes in state. When you update state directly, you bypass React’s control over this process, which can result in UI inconsistencies and bugs.</p><p>Here’s why you shouldn’t update state directly:</p><ol><li><strong>Unpredictable Rendering:</strong> React may not immediately recognize the change in state if you update it directly. This can lead to the UI not updating as expected, causing confusion for users.</li><li><strong>Batched Updates:</strong> React batches state updates for efficiency. Directly updating state might interfere with this batching process, causing multiple updates to occur simultaneously and potentially leading to errors.</li><li><strong>Component Performance:</strong> React optimizes rendering by comparing the previous and new states. When you update state directly, React might miss these changes, leading to unnecessary re-renders or even failing to update the UI.</li><li><strong>Future Compatibility:</strong> React’s internal mechanisms and optimizations can change between versions. Directly manipulating state might lead to compatibility issues with future React releases.</li></ol><p><strong>Let me show this with a simple example:</strong><br>Suppose we have a simple counter like this</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function CounterFunction() {<br>  const [count, setCount] = useState(0);<br><br>  const increment = () =&gt; {<br>    // Directly updating state - not recommended!<br>    count += 1;<br>    // This won&#39;t trigger the expected re-render<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default CounterFunction;</pre><p>In this example, the increment function directly updates the count variable. However, this approach is problematic because the UI won&#39;t re-render as expected, even though the count value changes.</p><p>Here’s the corrected version using the useState hook:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function CounterFunction() {<br>  const [count, setCount] = useState(0);<br><br>  const increment = () =&gt; {<br>    // Correct way using the setCount function from useState<br>    setCount(count + 1);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default CounterFunction;</pre><p>By using the setCount function from useState, the state is updated correctly, and React is informed about the change, leading to the expected UI re-render when you click the &quot;Increment&quot; button. This ensures that React&#39;s rendering processes are properly managed.</p><h3>4. What is Virtual DOM? How Virtual DOM works?</h3><p>The Virtual DOM (VDOM) is a concept in React that improves the efficiency of updating the user interface (UI) in web applications. It’s a lightweight copy or representation of the actual Document Object Model (DOM) — the structure that represents the elements of a web page.</p><p><strong>Working of Virtual DOM</strong></p><ol><li>When you update state or data in your React application, the framework initiates a process of reconciliation to identify what parts of the UI need to be changed.</li><li>React compares the current version of the Virtual DOM (representing the UI) with the previous version. It determines which elements have changed, been added, or been removed.</li><li>Based on the differences identified, React generates a list of changes to be made in the real DOM. This list is often referred to as a “diff.”</li><li>The goal of reconciliation is to minimize the number of changes needed in the real DOM. React calculates the most efficient way to update the DOM by applying only the necessary changes.</li><li>Finally, React applies the changes to the real DOM, updating the user interface to match the new state or data.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*5Kxcm1V4TTOhXiZy.png" /></figure><h3>5. What are the different phases of component lifecycle? What are the lifecycle methods?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBj8qmhG_srZjvYuecLudQ.png" /><figcaption><a href="https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/">https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/</a></figcaption></figure><p>The component lifecycle has three distinct lifecycle phases:</p><ol><li><strong>Mounting:</strong> The component is ready to mount in the browser DOM. This phase covers initialization from constructor(), getDerivedStateFromProps(), render(), and componentDidMount() lifecycle methods.</li><li><strong>Updating:</strong> In this phase, the component gets updated in two ways, sending the new props and updating the state either from setState() or forceUpdate(). This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods.</li><li><strong>Unmounting:</strong> In this last phase, the component is not needed and gets unmounted from the browser DOM. This phase includes componentWillUnmount() lifecycle method.</li></ol><p>I strongly encourage you to grasp the concept of lifecycle methods, as they form the core of React’s functioning. They provide the groundwork for how React components operate. If you’re eager to delve deeper into this topic, here’s a <a href="https://www.freecodecamp.org/news/react-component-lifecycle-methods/">link to a resource</a> that offers further reading and insights!</p><h3>6. State the Advantages &amp; Limitations of React</h3><p>Here are some of the advantages of using React!</p><ol><li><strong>Component-Based Architecture:</strong> React’s component-based approach allows you to build complex UIs by breaking them down into smaller, reusable components. This enhances code reusability and maintainability.</li><li><strong>Virtual DOM:</strong> React uses a Virtual DOM to optimize UI updates. It updates the actual DOM only with the necessary changes, resulting in improved performance and a smoother user experience.</li><li><strong>Unidirectional Data Flow:</strong> React enforces a unidirectional data flow, making it easier to understand how data changes affect the UI. This helps prevent unexpected side effects and simplifies debugging.</li><li><strong>Large Ecosystem:</strong> React has a vast ecosystem of libraries, tools, and extensions that streamline development tasks and enhance productivity.</li><li><strong>Strong Community and Support:</strong> React has a large and active community, providing ample resources, tutorials, and solutions to common problems.</li><li><strong>SEO-Friendly:</strong> React’s server-side rendering (SSR) and support for dynamic rendering make it more SEO-friendly, improving search engine visibility.</li><li><strong>Easy Learning Curve:</strong> React’s simplicity and well-defined concepts make it relatively easy to learn, especially for developers familiar with JavaScript.</li><li><strong>JavaScript Ecosystem Integration:</strong> React plays well with other JavaScript libraries and frameworks, allowing you to integrate it into your preferred development stack.</li></ol><p>Here are the limitations of React</p><ol><li><strong>Boilerplate Code: </strong>React’s focus on modularity and reusability can lead to a larger amount of initial setup code, especially when configuring build tools and setting up projects.</li><li><strong>JSX Complexity:</strong> JSX, while powerful, can introduce complexity for developers new to the syntax, as it blends JavaScript logic with HTML-like markup.</li><li><strong>View Library:</strong> React primarily focuses on the UI layer, which means you’ll need to integrate it with other libraries or frameworks to create complete web applications.</li><li><strong>Big Bundle Size:</strong> As your project grows and you include various libraries and dependencies, the bundle size can become significant, affecting initial load times.</li><li><strong>Backward Compatibility:</strong> Upgrading between major versions of React can sometimes require adjustments to your code due to changes in APIs or deprecated features.</li><li><strong>External State Management: </strong>While React has its built-in state management (useState and useReducer), for more complex applications, you might need to rely on external state management libraries, which can introduce a learning curve.</li></ol><h3>7. What is prop drilling? How can we avoid prop drilling?</h3><p>Prop drilling, also known as “props drilling,” is a term used in React to describe a situation where props are passed through multiple layers of components to reach a deeply nested child component that needs the data. This can lead to code that becomes harder to manage and maintain as the application grows.</p><p>Here’s an example to illustrate prop drilling:</p><pre>// ParentComponent.js<br>import React from &#39;react&#39;;<br>import ChildComponent from &#39;./ChildComponent&#39;;<br><br>function ParentComponent() {<br>  const data = &quot;Hello, Prop Drilling!&quot;;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;ChildComponent data={data} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ParentComponent;</pre><pre>// ChildComponent.js<br>import React from &#39;react&#39;;<br>import GrandChildComponent from &#39;./GrandChildComponent&#39;;<br><br>function ChildComponent({ data }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;GrandChildComponent data={data} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ChildComponent;</pre><pre>// GrandChildComponent.js<br>import React from &#39;react&#39;;<br><br>function GrandChildComponent({ data }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;{data}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default GrandChildComponent;</pre><p>In this example, the data prop is being passed from ParentComponent through ChildComponent to GrandChildComponent. This can be manageable for small applications, but as your app grows and components become more deeply nested, passing props through each level can become cumbersome and make the code harder to maintain.</p><p>To mitigate prop drilling, you can use techniques like React context or state management libraries like Redux or MobX. These tools allow you to manage and share state across components without having to pass props explicitly through each level of the component tree. This can lead to cleaner and more maintainable code.</p><h3>8. What are error boundaries in React?</h3><p>Error boundaries are a React feature that allow you to gracefully handle errors that occur during rendering. They prevent the entire application from crashing when an error occurs in a component by catching the error and displaying a fallback UI. Error boundaries are implemented using special error handling lifecycle methods.</p><p>Here’s how error boundaries work:</p><ol><li><strong>Component with Error Boundary:</strong></li></ol><ul><li>You wrap a component (or a tree of components) with an error boundary component.</li><li>This error boundary component serves as a safety net to catch errors thrown by its child components.</li></ul><p>2. <strong>Error Boundary Lifecycle Methods:</strong></p><ul><li>Error boundaries define two methods: componentDidCatch(error, info) and getDerivedStateFromError(error).</li><li>When a child component throws an error during rendering, the error is caught by the error boundary’s componentDidCatch method</li></ul><p>3. <strong>Fallback UI:</strong></p><ul><li>Inside the componentDidCatch method, you can update the state to indicate an error occurred.</li><li>The error boundary then renders a fallback UI, which can be a user-friendly error message or another component.</li></ul><pre>import React, { Component } from &#39;react&#39;;<br><br>class ErrorBoundary extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { hasError: false };<br>  }<br><br>  componentDidCatch(error, info) {<br>    // Update state to indicate an error occurred<br>    this.setState({ hasError: true });<br>    // You can also log the error for debugging<br>    console.error(error, info);<br>  }<br><br>  render() {<br>    if (this.state.hasError) {<br>      return &lt;div&gt;Oops! Something went wrong.&lt;/div&gt;;<br>    }<br>    return this.props.children;<br>  }<br>}<br><br>class App extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Welcome to My App&lt;/h1&gt;<br>        &lt;ErrorBoundary&gt;<br>          {/* Component that might throw an error */}<br>          &lt;ChildComponent /&gt;<br>        &lt;/ErrorBoundary&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>class ChildComponent extends Component {<br>  render() {<br>    // Simulate an error by throwing an exception<br>    throw new Error(&#39;Oops, an error occurred!&#39;);<br>    return &lt;div&gt;Child Component&lt;/div&gt;;<br>  }<br>}<br><br>export default App;</pre><p>In this example, the ErrorBoundary component wraps the ChildComponent. If ChildComponent throws an error during rendering, the error will be caught by the ErrorBoundary&#39;s componentDidCatch method. The fallback UI (&quot;Oops! Something went wrong.&quot;) will be displayed instead of the entire app crashing. This allows you to provide a better user experience and identify errors during development.</p><h3>9. What are hooks ? What is the difference between useMemo &amp; useCallback ?</h3><p>Hooks are a feature introduced in React 16.8 that allow you to use state and other React features without writing class components. They provide a way to use React’s core features, such as state and lifecycle methods, in functional components, making them more powerful and expressive.</p><p>Hooks aim to simplify component logic and reduce the complexity of managing state and side effects. They also encourage the reuse of stateful logic across components.</p><p><strong>What is the difference between </strong><strong>useMemo &amp; </strong><strong>useCallback ?<br></strong>Both useCallback and useMemo are React hooks that aim to optimize performance by memoizing values and functions. However, they serve different purposes and are used in different scenarios.</p><p><strong>useCallback :<br></strong>The useCallback hook is used to memoize functions. It returns a memoized version of the function that only changes if one of its dependencies has changed. This can be especially useful when passing functions as props to child components to prevent unnecessary re-renders of those components.</p><pre>import React, { useState, useCallback } from &#39;react&#39;;<br><br>function ParentComponent() {<br>  const [count, setCount] = useState(0);<br><br>  const increment = useCallback(() =&gt; {<br>    setCount(count + 1);<br>  }, [count]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;ChildComponent increment={increment} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, the increment function is memoized using useCallback, ensuring that it remains the same as long as count doesn&#39;t change. This prevents unnecessary re-renders of ChildComponent when count changes.</p><p><strong>useMemo :<br></strong>The useMemo hook is used to memoize values. It takes a function and a list of dependencies, and it returns a memoized value that is recalculated only when one of the dependencies changes.</p><pre>import React, { useState, useMemo } from &#39;react&#39;;<br><br>function ParentComponent() {<br>  const [count, setCount] = useState(0);<br><br>  const doubledCount = useMemo(() =&gt; {<br>    return count * 2;<br>  }, [count]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;p&gt;Doubled Count: {doubledCount}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, the doubledCount value is memoized using useMemo, ensuring that it&#39;s only recalculated when count changes. This optimization can be useful when calculating expensive or time-consuming values.</p><p>In summary, useCallback is used for memoizing functions, and useMemo is used for memoizing values. Both hooks can improve performance by preventing unnecessary recalculations and re-renders in your React components.</p><h3>10. What is Context API? What is Redux? Context API v/s Redux?</h3><p><strong>React Context API:</strong><br>The Context API is a feature provided by React that allows you to manage global state in your application without having to pass props through every level of the component tree. It’s designed to solve the problem of “prop drilling,” where data needs to be passed down through multiple layers of components.<br>Context provides a way to share data between components without the need to explicitly pass props, making it especially useful for managing state that is shared across different parts of your application.</p><p><strong>Redux:<br></strong>Redux is a state management library for JavaScript applications, often used with React but not limited to it. It provides a centralized way to manage the state of your application, making it easier to handle complex data flows and interactions between different components.</p><p>Redux follows the principles of the Flux architecture and is built on three main concepts:</p><ol><li><strong>Store:</strong> The single source of truth for your application’s state. It holds the entire state tree of your application.</li><li><strong>Actions:</strong> Plain JavaScript objects that represent events or user interactions that trigger changes in the state. They are dispatched to the store.</li><li><strong>Reducers:</strong> Functions that specify how the state changes in response to actions. They take the current state and an action as input and return a new state.</li></ol><p>Redux also introduces the concept of middleware, which allows you to add extra functionality to the dispatch process, such as asynchronous actions or logging.</p><p><em>Redux DevTools is a browser extension that provides advanced debugging and monitoring capabilities for Redux state management, allowing developers to track and analyze state changes, actions, and more.</em></p><p><strong>React Context API v/s Redux</strong></p><p>Choosing between React’s Context API and Redux depends on the complexity and specific needs of your application.</p><p><strong>React Context API:</strong></p><ol><li><strong>Simple State Sharing:</strong> If your application has a relatively small amount of shared state that needs to be accessed by a few components, the Context API can be a good choice. It’s simpler to set up and doesn’t require additional libraries.</li><li><strong>Component Coupling</strong>: Context can be beneficial when the state you’re sharing is closely tied to a particular part of your component tree. It can help avoid prop drilling and make it easier to manage shared data within a specific context.</li><li><strong>Newer Projects:</strong> If you’re starting a new project and want a lightweight way to manage state without adding the complexity of a separate library like Redux, the Context API might be a better fit.</li></ol><p><strong>Redux:</strong></p><ol><li><strong>Complex State Management:</strong> For larger and more complex applications with a lot of shared state, Redux provides a structured and centralized approach to state management. It helps maintain a clear data flow and separation of concerns.</li><li><strong>Predictable State Changes:</strong> Redux’s strict unidirectional data flow and clear separation between actions and reducers make it easier to predict and debug state changes, which is particularly useful for applications with a lot of moving parts.</li><li><strong>Middleware and Advanced Features:</strong> Redux’s middleware system allows you to handle asynchronous actions, logging, and other complex behavior. If your application requires advanced features beyond just state management, Redux might be a better choice.</li><li><strong>Existing Projects: </strong>If your project is already using Redux and has grown to a significant size, it might make sense to continue using it for consistency and to leverage the familiarity of Redux concepts.</li></ol><p>In general, for smaller projects with relatively simple state management needs, the React Context API can be sufficient and easier to set up. However, as your application grows in size and complexity, Redux’s structured approach to state management becomes more beneficial. It’s important to evaluate the specific requirements of your project and choose the solution that aligns with your development goals and team’s expertise.</p><h3>11. What is the difference between local storage &amp; session storage?</h3><p>Both localStorage and sessionStorage are web storage mechanisms provided by modern web browsers to store key-value pairs on the client side. However, they differ in terms of their scope, lifespan, and usage.</p><p><strong>LocalStorage:</strong></p><ol><li>Scope: Data stored in localStorage has a broader scope. It&#39;s accessible across different browser tabs/windows within the same domain.</li><li>Lifespan: Data stored in localStorage persists even after the browser is closed and reopened. It remains available until explicitly removed by the user or the application.</li><li>Usage: localStorage is commonly used to store data that needs to be retained between sessions, such as user preferences, settings, or cached data.</li></ol><p><strong>SessionStorage:</strong></p><ol><li>Scope: Data stored in sessionStorage is limited to the tab or window that created it. It&#39;s not accessible from other tabs or windows, even if they belong to the same domain.</li><li>Lifespan: Data stored in sessionStorage remains available as long as the browser tab or window is open. It&#39;s automatically cleared when the tab or window is closed.</li><li>Usage: sessionStorage is often used to store temporary data that&#39;s only relevant within a single browsing session, such as form data or state that should be discarded after the user leaves the page.</li></ol><p>In summary, localStorage is suitable for storing long-term data that should persist across sessions, while sessionStorage is ideal for short-term data that should only be available within a single session.</p><h3>12. What is React fragment?</h3><p>A React Fragment is a built-in component in React that allows you to group multiple elements without adding an extra DOM element to the rendered output. Since a React component can only render a single element, it’s common to wrap components in a &lt;div&gt; to accommodate this requirement. Here are the typical usecases for React Fragment!</p><ol><li>Fragments help improve the structure and maintainability of your code, especially when you need to return multiple elements from a component without introducing unnecessary HTML elements in the rendered result.</li><li>Using a fragment avoids the need to add an extra wrapping &lt;div&gt; or other container element, which can be especially useful when you want to maintain a clean and concise DOM structure. (DOM inspector is less cluttered!)</li><li>Fragments are a bit faster and use less memory by not creating an extra DOM node. This only has a real benefit on very large and deep trees.</li><li>Some CSS mechanisms like <em>Flexbox</em> and <em>CSS Grid</em> have a special parent-child relationships, and adding divs in the middle makes it hard to keep the desired layout.</li></ol><pre>render() {<br>  return (<br>    &lt;&gt;<br>      &lt;ChildA /&gt;<br>      &lt;ChildB /&gt;<br>      &lt;ChildC /&gt;<br>    &lt;/&gt;<br>  )<br>}jsx</pre><h3>13. Design a signup form using React (Coding Round)</h3><p>Design a signup form using React that collects essential user information, including Name, Email, Password, and Confirm Password fields. Implement a feature that ensures password and confirm password fields match when the user clicks the signup button. If the passwords don’t match, provide a clear message to the user indicating the mismatch.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function SignupForm() {<br>  const [formData, setFormData] = useState({<br>    name: &#39;&#39;,<br>    email: &#39;&#39;,<br>    password: &#39;&#39;,<br>    confirmPassword: &#39;&#39;,<br>  });<br><br>  const [passwordMatchError, setPasswordMatchError] = useState(false);<br><br>  const handleChange = (e) =&gt; {<br>    const { name, value } = e.target;<br>    setFormData((prevData) =&gt; ({<br>      ...prevData,<br>      [name]: value,<br>    }));<br>  };<br><br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    if (formData.password !== formData.confirmPassword) {<br>      setPasswordMatchError(true);<br>    } else {<br>      // Passwords match, perform signup logic here<br>      setPasswordMatchError(false);<br>      // ...perform signup logic<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Sign Up&lt;/h2&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;label&gt;<br>          Name:<br>          &lt;input type=&quot;text&quot; name=&quot;name&quot; value={formData.name} onChange={handleChange} /&gt;<br>        &lt;/label&gt;<br>        &lt;br /&gt;<br>        &lt;label&gt;<br>          Email:<br>          &lt;input type=&quot;email&quot; name=&quot;email&quot; value={formData.email} onChange={handleChange} /&gt;<br>        &lt;/label&gt;<br>        &lt;br /&gt;<br>        &lt;label&gt;<br>          Password:<br>          &lt;input type=&quot;password&quot; name=&quot;password&quot; value={formData.password} onChange={handleChange} /&gt;<br>        &lt;/label&gt;<br>        &lt;br /&gt;<br>        &lt;label&gt;<br>          Confirm Password:<br>          &lt;input<br>            type=&quot;password&quot;<br>            name=&quot;confirmPassword&quot;<br>            value={formData.confirmPassword}<br>            onChange={handleChange}<br>          /&gt;<br>        &lt;/label&gt;<br>        &lt;br /&gt;<br>        {passwordMatchError &amp;&amp; &lt;p style={{ color: &#39;red&#39; }}&gt;Passwords do not match&lt;/p&gt;}<br>        &lt;button type=&quot;submit&quot;&gt;Sign Up&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default SignupForm;</pre><h3>14. Why is there a need for using keys in list?</h3><p>Using keys in lists in React is important for several reasons:</p><ol><li>Keys help React identify which items have changed, been added, or been removed in a list. This enables React to optimize updates by reusing existing DOM nodes and minimizing unnecessary re-renders.</li><li>When items in a list have keys, React can accurately determine whether an item’s position has changed. Without keys, reordering items might result in unexpected behavior or the loss of component state.</li><li>Keys provide a stable identity for each item in a list, even as the list changes. This is crucial when dealing with components that have internal state or rely on the order of items.</li><li>Properly using keys ensures that user interactions with list items, such as clicking, selecting, or editing, are maintained correctly, even as the list changes.</li></ol><p>To summarize, using keys in lists is essential for React’s performance optimization, maintaining component state, and ensuring a predictable rendering behavior when dealing with dynamic lists.</p><h3>15. Explain — Pure Component, Higher Order Component (HOC), Controlled Component, Uncontrolled Component, Stateful Component, Stateless Component.</h3><p><strong>Pure Component: </strong>A PureComponent is a class component provided by React that automatically implements a shallow comparison of props and state before re-rendering. This comparison helps prevent unnecessary re-renders when the data hasn&#39;t changed. It&#39;s particularly useful when the component&#39;s render output is solely determined by its props and state. Using PureComponent can optimize the performance of your application by reducing unnecessary updates.</p><p><strong>Higher Order Component (HOC):</strong> A Higher Order Component (HOC) is a function that takes a component and returns a new component with additional props or behaviors. HOCs allow you to reuse and share component logic across different parts of your application. They’re often used for tasks like managing authentication, logging, or abstracting away common functionality. HOCs don’t modify the original component; they create a new one by wrapping it.</p><p><strong>Controlled Component:</strong> A controlled component is a component in which the component’s state is controlled by React. The component’s value is bound to the state, and changes to the value are handled through onChange handlers. This allows React to manage the input&#39;s state, enabling predictable behavior and making it easier to implement features like validation and user interaction tracking.</p><p><strong>Uncontrolled Component:</strong> An uncontrolled component is a component in which the component’s state is managed by the DOM rather than by React. You typically use refs to access and manipulate the DOM directly. Uncontrolled components can be useful when integrating React with third-party libraries or when you want to leverage the built-in behavior of HTML form elements.</p><p><strong>Stateful Component:</strong> A stateful component, often referred to as a “container” or “smart” component, is a component that manages its own state. It’s a class component that can have its own state, lifecycle methods, and manage complex logic. Stateful components are responsible for the data and business logic in your application.</p><p><strong>Stateless Component:</strong> A stateless component, also known as a “functional component” or “dumb” component, is a component that doesn’t have its own state. It’s a JavaScript function that receives props as arguments and returns JSX elements. Stateless components are primarily focused on rendering UI based on the props they receive and don’t manage state or lifecycle methods.</p><h3>16. In your view, what are the most effective guidelines to follow when working with React?</h3><p><strong>1. Component Structure and Organization:</strong></p><ul><li>Keep components focused and single-responsibility.</li><li>Group related components into folders or directories.</li><li>Use meaningful and descriptive names for components.</li><li>Use component composition to build complex UI from smaller components.</li><li>Use React Fragments to avoid unnecessary wrapping elements.</li></ul><p><strong>2. State Management:</strong></p><ul><li>Use local component state for UI-specific state that doesn’t need to be shared.</li><li>Use React Context API for sharing state that needs to be accessed by multiple components.</li><li>Consider using a state management library like Redux for more complex global state management.</li></ul><p><strong>3. Props and Data Flow:</strong></p><ul><li>Pass only the necessary props to components to keep the interface clean.</li><li>Use default props to provide fallback values for optional props.</li><li>Avoid modifying props directly; they should be treated as immutable.</li><li>Use prop types to validate the types of props passed to components.</li></ul><p><strong>4. Lifecycle Methods and Hooks:</strong></p><ul><li>Prefer functional components with hooks over class components when possible.</li><li>Use the useState, useEffect, and other hooks to manage state and side effects.</li><li>Avoid side effects in render methods; use useEffect for that purpose.</li></ul><p><strong>5. Performance Optimization:</strong></p><ul><li>Use PureComponent or implement shouldComponentUpdate to optimize re-renders.</li><li>Memoize expensive calculations using useMemo or React.memo.</li><li>Optimize component rendering by breaking down complex UI into smaller components.</li></ul><p><strong>6. Styling and CSS:</strong></p><ul><li>Use CSS-in-JS libraries, CSS modules, or CSS preprocessors for component-scoped styles.</li><li>Use CSS frameworks or utility libraries for consistent styling if needed.</li><li>Avoid inline styles for complex styling; prefer external stylesheets or CSS-in-JS.</li></ul><p><strong>7. Error Handling:</strong></p><ul><li>Implement error boundaries to gracefully handle errors in components.</li><li>Use the try-catch block to handle exceptions when working with asynchronous code.</li></ul><p><strong>8. Testing:</strong></p><ul><li>Write unit tests using testing libraries like Jest and testing utilities provided by React.</li><li>Use tools like React Testing Library for writing component integration tests.</li><li>Test component behavior and user interactions rather than implementation details.</li></ul><p><strong>9. Documentation:</strong></p><ul><li>Document your components, their props, and usage patterns.</li><li>Use tools like PropTypes or TypeScript to provide type information for your components.</li></ul><h3>17. What’s your recommended approach to organizing and structuring files within a React project?</h3><p>Organizing and structuring files within a React project is crucial for maintaining a clean and scalable codebase. While there’s no one-size-fits-all approach, here’s a recommended file structure</p><pre>src/<br>|-- assets/<br>|   |-- images/<br>|   |-- styles/<br>|<br>|-- components/<br>|   |-- Header/<br>|   |   |-- Header.js<br>|   |   |-- Header.css<br>|   |<br>|   |-- Sidebar/<br>|   |   |-- Sidebar.js<br>|   |   |-- Sidebar.css<br>|   |<br>|   |-- ...<br>|<br>|-- containers/<br>|   |-- Home/<br>|   |   |-- Home.js<br>|   |   |-- Home.css<br>|   |<br>|   |-- Profile/<br>|   |   |-- Profile.js<br>|   |   |-- Profile.css<br>|   |<br>|   |-- ...<br>|<br>|-- context/<br>|   |-- AuthContext.js<br>|   |-- ThemeContext.js<br>|<br>|-- utils/<br>|   |-- api.js<br>|   |-- helpers.js<br>|<br>|-- App.js<br>|-- index.js<br>|-- index.css<br>|-- ...</pre><ol><li>assets/: This directory holds assets like images, fonts, and global styles.</li><li>components/: This directory contains reusable presentational components. Each component is typically housed in its own folder with its JavaScript and CSS files.</li><li>containers/: This directory houses container components that connect to state, manage data, and render UI components. Like components, each container usually has its own folder.</li><li>context/: This directory holds React Context providers and related files. Group context providers in their own files to manage global state.</li><li>utils/: This directory contains utility files that aren&#39;t components but offer helper functions, API calls, and other shared logic.</li><li>App.js: This is the entry point of your application, containing the main component structure and routing.</li><li>index.js: This is the entry point of the application that renders the React app into the DOM.</li><li>index.css: This is where global styles are imported.</li></ol><p>This structure provides a clear separation of concerns, allowing you to easily locate and manage different types of files. As your project grows, you can further organize components and containers into subdirectories based on features or routes. Remember, the key is to maintain consistency and make it easy for team members to find and contribute to code.</p><h3>18. What are synthetic events in React?</h3><p>Synthetic events in React are a wrapper around native browser events, providing a consistent cross-browser interface for handling events in React components. React’s synthetic events abstract away many of the differences and complexities between browser implementations, ensuring a uniform event handling experience across different browsers.</p><pre>import React from &#39;react&#39;;<br><br>class Button extends React.Component {<br>  handleClick = (event) =&gt; {<br>    console.log(&#39;Button clicked!&#39;);<br>    console.log(&#39;Target:&#39;, event.target);<br>  };<br><br>  render() {<br>    return &lt;button onClick={this.handleClick}&gt;Click me&lt;/button&gt;;<br>  }<br>}</pre><p>In this example, the onClick event handler receives a synthetic event object as an argument. You can access properties like event.target just as you would with native events.</p><p>Synthetic events simplify event handling in React components by providing a consistent API and abstracting away many of the intricacies of native browser events.</p><h3>19. What is the use of ref?</h3><p>In React, a ref is a way to directly access and interact with DOM elements or React components. Refs are used when you need to perform imperative actions, such as reading values from input fields, triggering animations, or managing focus, that are outside the scope of the typical React data flow.</p><p>There are two main use cases for refs:</p><ol><li><strong>Accessing DOM Elements:</strong> Refs allow you to access the underlying DOM elements of React components. This can be useful for reading or modifying values of input fields, triggering animations, or focusing elements.</li><li><strong>Accessing React Components:</strong> Refs can also be used to access the instance of a React component. This is particularly useful when you need to interact with methods or properties of a child component.</li></ol><p>It’s important to note that using refs should be avoided when possible. In most cases, you can achieve your goals using the React data flow and state management mechanisms. Refs should only be used for specific use cases that cannot be handled in the declarative React way.</p><h3>20. Is it recommended to use CSS In JS technique in React?</h3><p>Using CSS-in-JS (CSS in JavaScript) is a technique where you write your styles directly in your JavaScript code, often using libraries or frameworks that allow you to define styles as JavaScript objects. Whether it’s recommended to use CSS-in-JS in React depends on various factors and considerations. Here’s a breakdown:</p><p><strong>Advantages of CSS-in-JS:</strong></p><ol><li><strong>Scoped Styles:</strong> Styles defined using CSS-in-JS are typically scoped to the component they belong to, reducing the chances of style clashes and global namespace pollution.</li><li><strong>Component-Based: </strong>CSS-in-JS promotes a component-based approach to styling, which aligns well with React’s component-based architecture.</li><li><strong>Dynamic Styling:</strong> Since styles are defined using JavaScript, you can easily create dynamic styles based on component props and state.</li><li><strong>Performance: </strong>Some CSS-in-JS solutions generate styles at runtime, allowing you to optimize the styles loaded based on the components used in your application.</li><li><strong>Eliminate Dead Code:</strong> Some tools can eliminate unused styles during the build process, reducing the size of your CSS.</li></ol><p><strong>Considerations and Drawbacks:</strong></p><ol><li><strong>Build Size:</strong> Some CSS-in-JS solutions add extra JavaScript code to your bundle, which can increase the build size.</li><li><strong>Developer Preferences: </strong>Some developers prefer separating styles from the JavaScript code, and CSS-in-JS might not align with their preferred workflow.</li><li><strong>SEO and SSR:</strong> In some cases, server-side rendering (SSR) and search engine optimization (SEO) can be affected by inlined styles.</li></ol><p>In summary, the decision to use CSS-in-JS depends on your project’s requirements, team preferences, and trade-offs. If you value scoped styles, dynamic styling, and the benefits of a component-based approach, CSS-in-JS might be a good fit. However, if you prefer keeping styles separate from JavaScript or if your project is already set up with a traditional CSS workflow, sticking with that approach might be more appropriate.</p><p>Ultimately, it’s recommended to evaluate the pros and cons in the context of your specific project and team dynamics before deciding whether to adopt CSS-in-JS.</p><h3>Final Words</h3><p>You’ve come a long way, and that’s something to be really proud of! Keep in mind that the questions mentioned here aren’t the only ones you might encounter in a React interview. Think of this as a guide to how React questions can be presented and what kind of questions you might face. This guide will help you understand the right mindset and approach for answering these questions. Remember, it’s not just about knowing the answers; it’s about understanding concepts deeply.</p><p>To truly succeed, don’t just focus on memorizing questions and answers. Get hands-on experience with React by creating projects. Discover the common challenges and issues you might encounter. Try practice tests to simulate real interview scenarios, and solve as many interview-style questions as possible before your actual interview. Believe in yourself and your abilities!</p><p>Wishing you all the best for your interview! You’ve got this! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5b48d78047e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Asynchronous JavaScript: A Simplistic Guide to Callbacks, Promises, and Async/Await]]></title>
            <link>https://medium.com/@sahildarji16/mastering-asynchronous-javascript-a-simplistic-guide-to-callbacks-promises-and-async-await-54d520c6694a?source=rss-bada68918e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/54d520c6694a</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[callbacks-vs-promises]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <dc:creator><![CDATA[Sahil Darji]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 04:19:21 GMT</pubDate>
            <atom:updated>2023-08-19T04:19:21.389Z</atom:updated>
            <content:encoded><![CDATA[<p>👋 Hello there!</p><p>I’m Sahil Darji, a Frontend Software Engineer 🚀 with over 2 years of experience in this field. Throughout my journey, I’ve been an integral part of various startups, successfully managing intricate projects and spearheading the development of complex features.💡 Today, I’m excited to share my insights and guide you through the intricate world of Asynchronous JavaScript concepts. Let’s embark on this learning journey together!🚀🔗</p><p><strong>Before We Dive into Async JS: Familiarity with Basic JavaScript Syntax is Needed!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-uX-BGO-Q1BFiDfhMaYJQ.png" /></figure><p><strong>Table of Contents!</strong><br>1. <a href="#2548">Why do we even need Asynchronous JavaScript?🤔</a><br>2. <a href="#4adc">Introduction to Asynchronous Programming!</a><br>3. <a href="#1e70">Why is Async JS a Game Changer for Modern Web Magic?</a><br>4. <a href="#23cd">JavaScript’s Single-Threaded Nature and Asynchronous Marvel 🚀</a><br>5. <a href="#b553">Imagine a World without Async JS ⏳</a><br>6. <a href="#e6e4">The Event Loop 🔁</a><br>7. <a href="#3130">Callbacks: Unraveling Asynchronous Magic 🎩</a><br>8. <a href="#6d80">Why Are Callbacks Essential?</a><br>9. <a href="#6656">setTimeout ⏰</a><br>10. <a href="#674c">setInterval 🔄</a><br>11. <a href="#9880">Promises 🤝</a><br>12. <a href="#5a31">Promise Chaining 🔗</a><br>13. <a href="#9c08">Async / Await</a><br>14. <a href="#0c1f">Final Words 🎉</a></p><h3><strong>Why do we even need Asynchronous JavaScript?</strong>🤔</h3><p>Imagine you’re baking a cake 🎂.. While the cake is in the oven, you don’t just stand there waiting. You might start setting the table 🍽️, preparing the frosting, or checking your recipe book 📖 for the next steps. In a similar way, when your JavaScript code needs to do something that takes time ⏳, like fetching data from a server 🌐 or waiting for a user’s input 👤, you don’t want your whole program to freeze up and wait. That’s where async JS comes in.</p><p>Async JS lets your code do multiple things at once, like preparing the frosting while the cake is baking. <strong>This way, your program can keep working on other tasks without waiting for one thing to finish before starting another.</strong> It’s like having a bunch of mini-workers in your code 👷‍♂️👷‍♀️, each handling different tasks independently, and they all collaborate to get things done faster and more efficiently.</p><p>In short, async JS is like having a multitasking superpower for your code, making it more responsive and capable of handling many tasks without getting stuck.</p><h3><strong>Introduction to Asynchronous Programming!</strong></h3><p>Asynchronous programming is a programming paradigm that enables tasks to be executed independently of the main program flow. In simple terms, it allows your code to perform multiple tasks simultaneously 🚀, without waiting for each task to complete before moving on to the next.</p><p>Just like we talked about baking a cake 🎂, think of JavaScript as a multitasking chef. It can fetch data, handle clicks, and do animations all together, making websites feel smooth and snappy 🌟.</p><h3><strong>Why is Async JS a Game Changer for Modern Web Magic?</strong></h3><p>Without async programming, it’s like a traffic jam 🚗 on the web. Everything would wait in line, and users would tap their fingers, frustrated. But with async, tasks wait for their turn, like organized queues at a busy store 🛍️.</p><p>In a nutshell, async programming makes JavaScript web apps snappy and pleasant 🎉. It’s like magic that keeps things moving without any slowdowns, making users smile and developers happy 😄.</p><h3><strong>JavaScript’s Single-Threaded Nature and Asynchronous Marvel </strong>🚀</h3><p>JavaScript operates as a single-threaded language, meaning it executes one operation at a time in a linear fashion. However, it also presents challenges when dealing with tasks that take time, like network requests or computations.</p><p>Asynchronous programming comes to the rescue by allowing JavaScript to efficiently manage concurrent tasks. When a time-consuming task is encountered, like fetching data from a server, instead of waiting for it to complete, JavaScript delegates it to a background process and continues executing other tasks. Once the background task finishes, JavaScript gets a nudge, and everything fits together smoothly like pieces of a puzzle!</p><p>Let’s Simplify with Code Magic! ✨</p><pre>console.log(&#39;Welcome to ASYNC JS!&#39;);<br><br>console.log(&#39;Mocking an API Call!&#39;);<br><br>setTimeout(() =&gt; {<br>    console.log(&#39;Network Request Successfull!&#39;)<br>}, 1000);<br><br>console.log(&#39;Moving ahead with other task...&#39;)<br><br>/*<br><br>OUTPUT:<br>    Welcome to ASYNC JS!<br>    Mocking an API Call!<br>    Moving ahead with other task...<br>    Network Request Successfull!<br><br>*/</pre><p>In this piece of code, we’re mimicking a scenario where JavaScript needs to interact with the outside world (make an API call) 🌐. For now, we don’t need to worry about how it’s set up or how setTimeout works – we&#39;ll cover that later. Javascript started executing code line by line (single-threaded), when it comes across a task that it knows will take a while, like making an API call, it doesn’t halt the entire show. Instead, it delegates that task to a helper and keeps going with the rest of the script. Once the helper gets the information back, JavaScript smoothly blends it into the story, ensuring the performance stays engaging and seamless 🎭.</p><h3><strong>Imagine a World without Async JS ⏳</strong></h3><pre>console.log(&#39;What if we didn’t have async JS!&#39;);<br><br>console.log(&#39;Mocking an API Call that takes many hours!&#39;);<br><br>setTimeout(() =&gt; {<br>    console.log(&#39;Network Request Successful!&#39;)<br>}, 2 * 60 * 60 * 1000); // 2hrs waiting<br><br>console.log(&#39;Moving ahead with another task...&#39;)</pre><p>In this scenario, let’s pretend we followed a strict line-by-line approach, waiting for each step to finish before moving on. Sounds fine, right? But here’s the twist — imagine we stumble upon a mammoth task, like waiting for an API call for a whopping 2 hours! ⏳🙇‍♂️</p><p>Now, picture this: If we waited for those 2 hours before continuing, the whole code would stand still. It’s like freezing an entire scene in a movie just because one actor is taking a long coffee break ☕. The webpage would become a frozen painting, completely unresponsive, leaving users tapping their fingers impatiently.</p><p>That’s not a show we’d want to watch, and definitely not the experience we’d want for users. Thankfully, async JS swoops in like a hero, allowing tasks to tag team and keeping the action flowing. The show must go on!🚀🎬</p><h3><strong>The Event Loop 🔁</strong></h3><blockquote>I understand that the concept of Event Loops might seem a bit intricate at first glance. If you’re encountering this for the first time, it could feel a tad complex. However, I encourage you to revisit this section again after reading the entire article — you’ll likely find it much clearer and easier to grasp by then!</blockquote><p>Wonder how JS keeps track of all background Async Tasks? Thanks to the event loop which helps JS to remember all the background tasks and ensures JS seamlessly assembles these tasks into a cohesive puzzle! Let’s uncover the mechanics of this dynamic event loop and explore its core components:</p><p>1. <strong>Call Stack</strong>: This is where the code execution takes place. It’s a stack of tasks that need to be completed.</p><p>2. <strong>Callback Queue</strong>: Imagine this as the queue of tasks waiting for their turn. It holds functions that are ready to be executed after the current task in the call stack finishes.</p><p>3. <strong>Event Loop</strong>: The star of our show! It continuously watches the call stack and callback queue, making sure that tasks are executed one after another. The event loop scans the callback queue, and when the call stack becomes vacant, it pushes tasks from the callback queue into the call stack for execution.</p><figure><img alt="Visual representation of event queue" src="https://cdn-images-1.medium.com/max/1024/0*8XDZLAc7HqsV1Thb.png" /></figure><p>Let me walk you through with our previous code example!</p><pre>console.log(&#39;Welcome to ASYNC JS!&#39;);<br><br>console.log(&#39;Mocking an API Call!&#39;);<br><br>setTimeout(() =&gt; {<br>    console.log(&#39;Network Request Successfull!&#39;)<br>}, 1000);<br><br>console.log(&#39;Moving ahead with other task...&#39;)</pre><p>Before diving into executing this code, JS sets the stage by creating a call stack, also known as the JS Runtime. Each of these lines is neatly arranged on the JS Call Stack. One after another, JS plucks tasks from this Call Stack and begins their execution. 👨‍🎤</p><p>However, if it stumbles upon an async task, like making an API call or waiting for something time-consuming, JS doesn’t halt the entire process. Instead, it tucks these tasks into the Callback Queue, creating a waiting list. 🎯</p><p>Now, here’s where the event loop steps in. As soon as the Call Stack is free and ready for action, the event loop summons tasks from the Callback Queue onto the Call Stack, where they gracefully take the spotlight and begin their performance. 🎭</p><ol><li>console.log(&quot;Welcome to ASYNC JS!&quot;)<br>This line gets added to the call stack and executed. The message “Welcome to ASYNC JS!” is displayed.</li><li>console.log(&quot;Mocking an API Call!&quot;) <br>The next line joins the call stack and is executed. The message “Mocking an API Call!” appears.</li><li>setTimeout(()=&gt;{...}, 1000) <br>Now, a bit of a twist! This line involves an asynchronous task. The setTimeout function is placed on the call stack.<br>Inside setTimeout, the callback function is scheduled to execute after a 1000ms delay (1 second). However, before the callback executes, the setTimeout function itself is removed from the call stack.</li><li>console.log(&quot;Moving ahead with another task...&quot;) <br>Continuing our journey, this line adds to the call stack and is executed. The message “Moving ahead with another task…” is printed.</li></ol><p>At this point, the call stack is empty, and the event loop takes center stage:</p><p>Event Loop: Callback Queue ➡ Call Stack</p><ul><li>The event loop checks the callback queue, finds the scheduled console.log(&#39;Network Request Successful!&#39;) callback waiting there.</li><li>It then ushers this callback from the callback queue onto the call stack.</li></ul><p>console.log(&#39;Network Request Successful!)</p><ul><li>Now on the call stack, the console.log function is executed, and &quot;Network Request Successful!&quot; is displayed.</li></ul><h3><strong>Callbacks: Unraveling Asynchronous Magic </strong>🎩</h3><p>In the realm of JavaScript, functions hold a special status as “first-class citizens.” This implies that a function is treated just like any other variable. You can tuck a function inside a variable, hand it over to another function, or even have a function returning from within another. It’s like functions have been granted a VIP pass in the world of JavaScript! 🎩🎉</p><p>Callback function is a function that is passed to another function as a parameter then invoked by that other function! Still not clicking? No worries, let’s dive into a code example to make it crystal clear! 🕶️📝</p><pre>function callback() {<br>    console.log(&#39;Coming from callback&#39;);<br>}<br><br>function higherOrder(fn) {<br>    console.log(&#39;About to call callback&#39;);<br>    fn(); // callback function is invoked<br>    console.log(&#39;Callback function has been invoked&#39;);<br>}<br><br>higherOrder(callback)<br><br>/*<br>OUTPUT:<br>    About to call callback<br>    Coming from callback<br>    Callback function has been invoked<br>*/</pre><p>In this snippet, we have a duo: a <strong>callback</strong> function and a <strong>higher-order</strong> function.</p><p>A <strong>higher order function</strong> is a function that accepts callback as a paramter!</p><p>In this snippet, we are invoking higherOrder function and passing callback function as an argument. When the higherOrder function starts its execution, it initiates by displaying “About to call callback”, after that we invoke our callback function and from there our callback function starts executing and it displays “Coming from callback”.</p><p>After the callback has fulfilled its task, the control flows back to the higherOrder function. It then resumes its course, continuing with “Callback function has been invoked” and proceeding with the remaining instructions.</p><h3>Why Are Callbacks Essential?</h3><p>Imagine we’re on a quest to fetch precious data from the vast internet and present it to our eager user. But here’s the twist — we can’t predict when this data will arrive. It could be a lightning-fast 1 millisecond or a more leisurely 2 seconds, or maybe even an entire hour. That’s where callbacks step in, like trusty messengers.</p><p>In the world of asynchronous tasks, callbacks serve as a message to say, <strong>“Hey, when that data finally arrives, perform this action!”</strong> So, in our scenario, we can employ a callback to stand by, ready to reveal the fetched data to our users the moment it arrives, ensuring a seamless and responsive experience. 🚀📬</p><p><strong>So we need callbacks for all our asynchronous tasks like — Fetching Data, Timers, Event Handling, AJAX Requests, etc!</strong></p><p>Let’s Dive into Callbacks with setTimeout &amp; setInterval!</p><h3>setTimeout ⏰</h3><p>setTimeout is a built-in function in JavaScript that allows you to schedule a certain task to be executed after a specified amount of time has passed ⏳. It&#39;s like telling JavaScript, &quot;Hey, wait for this much time ⏰, and then do something.&quot;</p><p>Now, let’s leap right into action with an example:</p><pre>function callback() {<br>    console.log(&#39;Callback called!&#39;);<br>}<br><br>setTimeout(callback, 1000) // wait for 1s<br><br>console.log(&#39;We are exploring setTimeout!&#39;);<br><br>/*<br><br>OUTPUT<br>    We are exploring setTimeout!<br>    Callback called!<br><br>*/</pre><p>Here’s the breakdown:</p><ul><li>setTimeout takes two friends along: a callback function and the time to wait (in milliseconds).</li><li>In our case, after 1000 milliseconds (1 second), it says, “Wake up, callback!” And so, it does.</li></ul><p>In short, setTimeout gives JavaScript a little nap, and when it&#39;s time, the callback gets a gentle nudge. 🌙💤</p><p>Let me share one more example of setTimeout , in this example we will use anonymous function!</p><pre>setTimeout(() =&gt; {<br>    console.log(&#39;Anonymous callback function called!&#39;)<br>}, 1000) // wait for 1s<br><br>console.log(&#39;We are exploring setTimeout!&#39;);<br><br>/*<br><br>OUTPUT<br>    We are exploring setTimeout!<br>    Anonymous callback function called!<br><br>*/</pre><p>Now, I’ll leave you to unravel more of setTimeout’s enchantment on your own! 🎩</p><h3>setInterval 🔄</h3><p>setInterval is another built-in function in JavaScript that works hand-in-hand with time. Just like setTimeout, it allows you to schedule a task. But there&#39;s a twist – with setInterval, the task keeps repeating at a specified interval, creating a rhythmic loop.</p><p>It’s like having a drummer who beats the drum at a consistent rhythm, playing the same tune over and over again.</p><p>In short, setInterval is perfect for creating regular, repeated actions like animations, updates, or checks. 🥁🔄</p><p>Now, let’s leap right into action with an example:</p><pre>setInterval(() =&gt; {<br>    console.log(&#39;Hello, I love JS!&#39;)<br>}, 1000) // displays after every 1sec<br><br>console.log(&#39;We are exploring setInterval!&#39;);<br><br>/*<br><br>OUTPUT<br>    We are exploring setTimeout!<br>    Hello, I love JS!<br>    Hello, I love JS!<br>    Hello, I love JS!<br>    Hello, I love JS!<br>    .<br>    .<br>    .<br><br>*/</pre><p>In this example, the callback function is set to execute every 1000 milliseconds (1 second) using setInterval. So, every second, you&#39;ll see the message &quot;Hello, I love JS!&quot; printed in the console. 🕰️👋</p><p><strong>Assignment time! I want you to go ahead and explore </strong><strong>setInterval &amp; </strong><strong>setTimeout and also see how you can cancel a </strong><strong>setInterval &amp; </strong><strong>setTimeout ! </strong>🕵️‍♂️🚀</p><h3>Promises 🤝</h3><p>A promise in JavaScript is like a commitment made by a piece of code. It’s a way of saying, “Hey, I promise to give you a result when I’m done with my task, whether it’s successful or not.”</p><p>Promises help you manage asynchronous operations in a more organized and structured way. They’re like a reliable messenger that delivers the outcome of a task when it’s ready. 💌✨</p><p>Time to Get Hands-On! Let’s Shift to Code! I’ll kick off with straightforward examples to help you grasp how promises operate. After nailing the basics, we’ll spice things up with more intricate scenarios! 🚀💻</p><pre>let p1 = new Promise(function (resolve, reject) {<br>    resolve({<br>        success: true,<br>        data: [1, 2, 3],<br>    });<br>});<br><br>p1.then((data) =&gt; {<br>    // if success<br>    console.log(&#39;inside then&#39;);<br>    console.log(data);<br>}).catch((err) =&gt; {<br>    // if error<br>    console.log(&#39;inside catch&#39;);<br>    console.log(err);<br>});<br><br>/*<br><br>OUTPUT:<br>inside then<br>{ success: true, data: [ 1, 2, 3 ] }<br><br>*/</pre><p>Let’s break down this code step by step:</p><p>Sure thing! Let’s break down this code step by step:</p><ol><li>We create a “promise” named p1. It&#39;s like making a deal – we&#39;re promising to provide something (a result) later.</li><li>Inside the promise, we have two options: “resolve” or “reject.” In this case, we “resolve” with a success message and some data.</li><li>Now comes the exciting part! We execute p1 and use .then() to declare what to do when the promise is fulfilled successfully. It&#39;s like saying, &quot;When the promise is kept, do this!&quot;</li><li>Inside .then(), we receive the data from the resolved promise (the success message and data), and we display it using console.log.</li><li>But wait, there’s more! We’re also prepared for things not going as planned. We use .catch() to handle errors. If the promise breaks its promise, we catch the error and show it.</li></ol><p>Let’s modify this same example to see how we can handle errors!</p><pre>let p1 = new Promise(function (resolve, reject) {<br>    reject({<br>        success: false,<br>        error: &#39;Something went wrong:(&#39;<br>    });<br>});<br><br>p1.then((data) =&gt; {<br>    // if success<br>    console.log(&#39;inside then&#39;);<br>    console.log(data);<br>}).catch((err) =&gt; {<br>    // if error<br>    console.log(&#39;Inside catch&#39;);<br>    console.log(err);<br>});<br><br>/*<br><br>OUTPUT<br>Inside catch<br>{ success: false, error: &#39;Something went wrong:(&#39; }<br><br>*/</pre><p>Here’s the breakdown:</p><ol><li>We initiate a “promise” named p1, just like before. But this time, it&#39;s a bit gloomy – it&#39;s being &quot;rejected.&quot; It&#39;s like saying, &quot;Oops, something went wrong, and I can&#39;t fulfill my promise.&quot;</li><li>Inside the promise, we “reject” with an error message and details.</li><li>We’re ready for action! We use .then() as usual to declare what to do if the promise keeps its word. But guess what? In this case, it didn&#39;t. So, we swiftly move to the next line.</li><li>Here comes the hero — .catch()! It&#39;s our safety net, always prepared to handle errors. When the promise hits a snag, we dive into .catch(), showing the error message and details.</li></ol><p>And there you have it! Since our promise took the path of rejection, we see the “Inside catch” message along with the error details in the output. Promises ensure we’re ready for the best outcomes and the trickiest turns along the coding journey.</p><p>Let’s look at another example with randomly generating error!</p><pre>let p1 = new Promise(function (resolve, reject) {<br>    const randomNumber = Math.floor(Math.random() * 100) + 1;<br>    if (randomNumber % 2 === 0) {<br>        resolve({<br>            success: true,<br>            data: randomNumber,<br>        });<br>    } else {<br>        reject({<br>            success: false,<br>            error: &#39;Something went wrong&#39;,<br>        });<br>    }<br>});<br><br>p1.then((data) =&gt; {<br>    // if success<br>    console.log(&#39;inside then&#39;);<br>    console.log(data);<br>}).catch((err) =&gt; {<br>    // if error<br>    console.log(&#39;Inside catch&#39;);<br>    console.log(err);<br>});<br><br>/*<br><br>OUTPUT<br>inside then<br>{ success: true, data: 42 }<br><br>OR<br><br>OUTPUT<br>Inside catch<br>{ success: false, error: &#39;Something went wrong&#39; }<br><br>*/</pre><p>Here’s the play-by-play:</p><ol><li>We’ve got a “promise” named p1, and inside it, we&#39;re creating some randomness. If the randomly generated number is even, the promise is &quot;resolved&quot; with success and the number. If it&#39;s odd, the promise is &quot;rejected&quot; with an error message.</li><li>We’re prepared for both scenarios. Using .then(), we declare what to do when the promise is fulfilled successfully. If it&#39;s resolved, we see &quot;Inside then&quot; and the success message along with the data.</li><li>And there’s a safety net! If the promise breaks its promise and gets rejected, .catch() swings into action. We see &quot;Inside catch&quot; and the error details.</li></ol><p>So, when the code runs, it’s a 50–50 chance — either the promise succeeds and we get the success message and data, or it stumbles and we see the error message. Promises, just like life, are full of surprises! 🎉🎭</p><h3>Promise Chaining 🔗</h3><p>Promise chaining is a technique in JavaScript that allows you to link multiple asynchronous operations together using promises. It provides a more organized and readable way to handle a sequence of asynchronous tasks. It eliminates deep nesting and improves error handling, making it easier to follow the sequence of operations.✨🔗🔄</p><p>Let’s jump right into code!</p><pre>let p1 = new Promise(function (resolve, reject) {<br>    resolve(6);<br>});<br><br>p1.then((data) =&gt; {<br>    // if success<br>    console.log(&#39;inside then&#39;);<br>    return data * 10;<br>}).then((data) =&gt; {<br>    console.log(&#39;inside chain!&#39;);<br>    return data + 10;<br>}).then((result) =&gt; {<br>    console.log(result);<br>}).catch((err) =&gt; {<br>    // if error<br>    console.log(&#39;Inside catch&#39;);<br>    console.log(err);<br>});<br><br><br>/*<br><br>OUTPUT<br>inside then<br>inside chain!<br>70<br><br>*/</pre><ol><li>We create a “promise” named p1. It&#39;s like saying, &quot;I promise to give you a result: 6.&quot;</li><li>We’re all set for success! Inside the first .then() handler, we see &quot;inside then.&quot; We return the result of doubling the data (which is 6) and move to the next step.</li><li>The next .then() handler is ready to rock. It says &quot;inside chain!&quot; and adds 10 to the doubled data, which is now 60.</li><li>Almost there! The final .then() handler receives the result (70) and showcases it in the output.</li><li>The whole journey went smoothly, so the .catch() section stays quiet.</li></ol><p>And that’s how we end up with “inside then,” “inside chain!,” and the number 70 in the output. Promise chaining makes it easy to line up tasks in a neat sequence!</p><p><strong>Let’s delve into another aspect of promises — the </strong><strong>finally() method</strong></p><p>The finally() method is used in JavaScript promises to specify a function that will be executed regardless of whether the promise is resolved or rejected. It provides a way to perform cleanup or finalization tasks after the promise settles, whether it&#39;s fulfilled or rejected.</p><pre>somePromise<br>    .then((result) =&gt; {<br>        // Code for handling the resolved promise<br>    })<br>    .catch((error) =&gt; {<br>        // Code for handling the rejected promise<br>    })<br>    .finally(() =&gt; {<br>        // Code that will be executed regardless of the outcome<br>        // This is where you can perform cleanup tasks<br>    });</pre><p>I encourage you to give the finally method a shot with the examples provided above! It&#39;s a task worth exploring. Go ahead and see how it enhances your promise-handling experience! 🚀🔧🔗</p><h3><strong>Async / Await</strong></h3><p>By using <strong><em>async</em></strong>, you can <strong>create functions that operate asynchronously</strong> while maintaining a flow that appears synchronous. With the <strong><em>await</em></strong> keyword, you can <strong>call asynchronous functions inside an </strong><strong>async function</strong> and pause execution until the awaited task is complete.</p><p>Let’s jump into code examples!</p><pre>// A function that simulates fetching data from an API<br>function fetchData() {<br>    return new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve(&#39;Data from API&#39;);<br>        }, 1000);<br>    });<br>}<br><br>// An async function that uses await to fetch data<br>async function fetchAndDisplayData() {<br>    try {<br>        const data = await fetchData();<br>        console.log(&#39;Fetched:&#39;, data);<br>    } catch (error) {<br>        console.log(&#39;Error:&#39;, error);<br>    }<br>}<br><br>// Calling the async function<br>fetchAndDisplayData();</pre><p>In this example:</p><ol><li>The fetchData function returns a promise that resolves after a simulated delay of 1 second, representing data fetched from an API.</li><li>The fetchAndDisplayData function is marked as async, allowing the use of await inside it. It calls fetchData using await and then logs the fetched data.</li><li>The try...catch block is used to handle any errors that might occur during the await operation.</li><li>When fetchAndDisplayData is called, it fetches data from the API and logs it if successful, or logs an error if something goes wrong.</li></ol><p>The async and await keywords make the asynchronous code appear more like synchronous code, enhancing readability and making the flow easier to understand. 📦🕰️🌐</p><p>Here’s an example that demonstrates the importance of using async/await compared to a version without it. We&#39;ll simulate fetching user data from an API:</p><p><strong>Without </strong><strong>async/await:</strong></p><pre>// Simulating fetching user data from an API (without async/await)<br>function fetchUserDataWithoutAsync() {<br>    return new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve(&#39;User Data&#39;);<br>        }, 1000);<br>    });<br>}<br><br>// Fetch and display user data<br>function fetchAndDisplayUserDataWithoutAsync() {<br>    fetchUserDataWithoutAsync()<br>        .then((data) =&gt; {<br>            console.log(&#39;Fetched:&#39;, data);<br>        })<br>        .catch((error) =&gt; {<br>            console.log(&#39;Error:&#39;, error);<br>        });<br>}<br><br>// Calling the function<br>fetchAndDisplayUserDataWithoutAsync();</pre><p><strong>With </strong><strong>async/await:</strong></p><pre>// Simulating fetching user data from an API (with async/await)<br>function fetchUserDataWithAsync() {<br>    return new Promise((resolve, reject) =&gt; {<br>        setTimeout(() =&gt; {<br>            resolve(&#39;User Data&#39;);<br>        }, 1000);<br>    });<br>}<br><br>// Fetch and display user data using async/await<br>async function fetchAndDisplayUserDataWithAsync() {<br>    try {<br>        const data = await fetchUserDataWithAsync();<br>        console.log(&#39;Fetched:&#39;, data);<br>    } catch (error) {<br>        console.log(&#39;Error:&#39;, error);<br>    }<br>}<br><br>// Calling the async function<br>fetchAndDisplayUserDataWithAsync();</pre><p>In both examples, we simulate fetching user data from an API after a delay of 1 second. However, the second example using async/await is more concise and easier to read. It resembles synchronous code, which can improve code maintainability and reduce the complexity introduced by chaining .then() calls.</p><p>The importance of async/await becomes even more apparent as the codebase grows and the number of asynchronous operations increases. It simplifies error handling and makes the code structure cleaner and more understandable. 📦🕰️🌐🔧</p><h3>Final Words 🎉</h3><p>Congratulations on reaching this point! 🌟 Your dedication and progress are truly commendable. We’ve delved deep into the realm of asynchronous JavaScript, focusing on establishing a solid foundation. By mastering these fundamental concepts, you’ve equipped yourself with essential skills that are not only valuable for acing interviews but also for crafting real-world projects that shine.</p><p>Technology is an expansive universe, and continuous learning is its essence. If you encounter any unfamiliar aspects of asynchronous JS in the future, feel empowered to explore online resources and grasp them through examples. Your robust understanding of async JS will serve as a guiding light.</p><p>As you continue on your coding journey, remember that every line of code is a step toward mastery. ⚡ I extend my best wishes to you for all your coding endeavors!</p><p>With gratitude, Sahil Darji✨</p><p>Feel free to reach me out — sahildarji16@gmail.com :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54d520c6694a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimalistic HTML Essentials: Your Ultimate Guide to the Only Tags You’ll Ever Need]]></title>
            <link>https://medium.com/@sahildarji16/minimalistic-html-essentials-your-ultimate-guide-to-the-only-tags-youll-ever-need-afaf87a61c3a?source=rss-bada68918e77------2</link>
            <guid isPermaLink="false">https://medium.com/p/afaf87a61c3a</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[minimalism]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Sahil Darji]]></dc:creator>
            <pubDate>Sun, 13 Aug 2023 06:33:39 GMT</pubDate>
            <atom:updated>2023-08-13T06:33:39.742Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Minimalistic HTML Essentials: Your Ultimate Guide to the Only Tags You’ll Ever Need</strong></p><p>Hello there!</p><p>I’m Sahil Darji, a Frontend Software Engineer with over 2 years of experience in this field. I’ve been part of startups and have handled intricate projects and features. So, it’s likely I can help you grasp some HTML concepts!</p><p>Whether you’re a beginner venturing into Frontend Development or aspiring to dive into Full Stack Development, you’re in the right spot!</p><p>Three years ago, I embarked on my journey in this field by learning HTML, just like you probably did! I still recall dedicating over two weeks to master HTML. But was it really worth it? The simple answer is NO! You don’t need to become an HTML expert. Chances are, you won’t be writing HTML code extensively in your job. Instead, you’ll likely be using a framework or library that generates HTML, CSS, and JS for you. From my experience, you only need a day or two to grasp HTML basics.</p><p>Grasping the basics is crucial, as HTML, CSS, and JS form the foundation of web development. In this article, we’ll focus on mastering the fundamentals of HTML, which are essential for understanding frameworks and libraries in the future! <strong>HTML is straightforward; adopt a minimalist approach and learn only what’s necessary.</strong> Let me guide you through this process in the following article &amp; help you become that HTML hacker 🐱‍💻</p><p><strong>What is HTML?</strong></p><p>HTML stands for Hyper Text Markup Language, HTML is the standard markup language used to create and structure content on the World Wide Web. <em>HTML is not a programming language, it’s a markup language!</em></p><p>In simpler terms, HTML provides a way to describe the different parts of a web page, such as headings, paragraphs, images, links, forms, and more. Each HTML element is represented by a tag, enclosed in angle brackets, like &lt;tagname&gt;.</p><p><strong>Tags are used to define the structure and content of a webpage, and they can contain text, other tags, or a combination of both.</strong></p><p>Okay, let’s put the theory aside for now and actually use HTML to see these tags in action. It’s a good idea to follow along as you read this article because that’s the best way to learn.</p><p><strong>Installing VS Code</strong></p><p>To begin with HTML, you can use a simple text editor, but personally, I prefer and recommend using VS Code. Don’t worry if you prefer a different text editor; you can use that too. But if you’re following along with this article, I highly suggest getting VS Code. <a href="https://code.visualstudio.com/">Install VS Code from here!</a></p><p>Start by creating a new folder in the directory where you want to keep your files. Then, open this folder using VS Code.</p><p>Also, it’s a good idea to add the <a href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer">Live Server Extension</a> to VS Code. This will save you the hassle of manually refreshing your browser each time you make changes to your HTML code.</p><figure><img alt="Installing Live Server from VS Code Marketplace" src="https://cdn-images-1.medium.com/max/1024/1*V_pZC4FHsTkN6eajb94wUA.png" /></figure><p><strong>Let’s write some code!</strong></p><p>Create an HTML file &lt;file_name&gt;.html , an HTML file consist of the structure of a web page, think of HTML like a blueprint of a house, with CSS being the interior decoration and JS being electrical and plumbing systems that make a house smart.</p><figure><img alt="Difference between roles of HTML &amp; CSS" src="https://cdn-images-1.medium.com/max/1024/1*T9uW5WLpm0gcV9-GTrWc6w.png" /></figure><p>HTML tags are not case-sensitive. You can use uppercase or lowercase letters interchangeably for HTML tags.</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;Document&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;!-- content goes here --&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Alright, the code you’re looking at is like a starting template for HTML5. Many web pages on the internet use this same starting point. Now, let’s break down and understand what this template is all about!</p><figure><img alt="Opening with Live server" src="https://cdn-images-1.medium.com/max/870/1*y8S0VStUKuYFcm7RdIPMoQ.png" /></figure><p><strong>&lt;!DOCTYPE html&gt;</strong></p><p>By including “DOCTYPE HTML” at the beginning of your HTML document, you’re specifying that you’re using the latest version of HTML, which is HTML5 at the moment.</p><p><strong>What’s an Opening Tag &amp; a Closing Tag?</strong></p><p>Opening tags and closing tags are fundamental elements in HTML that work together to define and enclose content within a specific element. They are used to mark the beginning and end of an element, indicating where the element’s effect starts and where it ends.</p><p>&lt;html&gt; — HTML opening tag, &lt;/html&gt; — HTML closing tag, this means all of our HTML will be wrapped or enclose within this tag!</p><p>Here’s a handy tip: Many tags work in pairs with an opening tag, like &lt;tagname&gt;, and a closing tag, like &lt;/tagname&gt; (the closing tag has a /). But, there&#39;s a cool exception! Some tags are like quick visitors – they come and go without a closing tag. For example, &lt;img&gt; is one of these tags. Don&#39;t worry; we&#39;ll learn more about these special tags too!</p><p>So remember, opening and closing tags team up to define where your HTML’s effects begin and end. It’s like putting everything inside a big, cozy hug! 🤗</p><p><strong>&lt;head&gt; : </strong>It holds important information about the webpage that isn’t directly shown to the audience. Things like the title of the webpage, links to styles (CSS), and other meta information live in the &lt;head&gt; tag. You’ll likely spend less time here unless you’re an SEO specialist.</p><p><strong>&lt;meta&gt;</strong>It helps search engines and browsers understand details like the title of the page, keywords, character encoding, and more.</p><p><strong>&lt;title&gt;</strong> : This title appears in the browser tab when you open a webpage. Just as a book title gives you an idea of what the book is about, the title tag tells you what the webpage contains.</p><figure><img alt="Title tag image" src="https://cdn-images-1.medium.com/max/252/1*q8ivq5VdwvPCOKUX_1COzw.png" /></figure><p>Okay, what we’ve covered so far are the basic tags you’ll often start with. You might not need to focus on these tags for long, but it’s good to have an understanding of them.</p><p><strong>&lt;body&gt;</strong> : Everything you see on a web page is like the body of a document. It’s where you put the main structure of your webpage. How your page appears is determined by what you put in this part. Let’s dive into the important tags that go into the body and shape your webpage!</p><p><strong>Headings! H1, H2, H3, H4……</strong></p><p>These tags are used to create different levels of headings, where h1 is the highest and most important level, and h4 is a lower level heading.</p><p>In simpler terms:</p><ul><li>h1 is like the main title of a webpage.</li><li>h2 is like a subheading under the main title.</li><li>h3 is like a subheading under h2, and so on.</li><li>h4 is another level down, providing a smaller subheading.</li></ul><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><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;My title&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>    &lt;h1&gt;This is H1&lt;/h1&gt;<br>    &lt;h2&gt;This is H2&lt;/h2&gt;<br>    &lt;h3&gt;This is H3&lt;/h3&gt;<br>    &lt;h4&gt;This is H4&lt;/h4&gt;<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*CPoUFNUdrimn2PD1D1VD1A.png" /></figure><p><strong>&lt;p&gt; The paragraph text!</strong></p><pre>&lt;body&gt;<br>    &lt;h1&gt;This is Paragraph Tag&lt;/h1&gt;<br>    &lt;p&gt;Lorem ipsum dolor sit amet consectetur, adipisicing elit. Aliquid dolores eum accusantium beatae temporibus non<br>        saepe. Dolore, fugiat pariatur? Assumenda, veritatis aspernatur consequuntur a eaque perferendis eum ut? Quia,<br>        eveniet.<br>    &lt;/p&gt;<br>    &lt;p&gt;Lorem ipsum dolor sit amet consectetur, adipisicing elit. Aliquid dolores eum accusantium beatae temporibus non<br>        saepe. Dolore, fugiat pariatur? Assumenda, veritatis aspernatur consequuntur a eaque perferendis eum ut? Quia,<br>        eveniet.<br>    &lt;/p&gt;<br>&lt;/body&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pon5abbBvTl00AjmsvImJA.png" /></figure><p><strong>Let’s Talk about Anchor tag — </strong><strong>&lt;a&gt;</strong></p><p>It’s used in HTML to create clickable links that take you from one webpage to another or from one part of a webpage to another part. You can create links to other html pages or to navigate to different parts of your webpage or to redirect to some other webpage!</p><p>Before we continue, there’s one more thing to grasp. Each HTML tag comes with special details called <strong>“attributes”.</strong> These add extra information to the tag. You can even make your own custom details to carry useful data, but let’s keep things simple for now.</p><p>For example, the &lt;a&gt; tag uses an attribute called &quot;href.&quot; This attribute is like a pointer and holds the link to another webpage, maybe a different webpage or a specific part of the current one. It works like this: &lt;a href=&quot;https://google.com&quot;&gt;Link to Google&lt;/a&gt;. When you click &quot;Link to Google,&quot; you&#39;ll go to the web address mentioned in the &quot;href&quot; attribute.</p><pre>&lt;body&gt;<br>    &lt;h1&gt;This is Anchor Tag&lt;/h1&gt;<br>    &lt;a href=&quot;https://github.com/sahil-1602&quot;&gt;Link to my github&lt;/a&gt;<br>&lt;/body&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*Ecmx3nnvbrG72yrr93jCrg.png" /></figure><p><strong>&lt;button&gt;</strong> : The &lt;button&gt; tag in HTML is like a virtual button on a webpage. It&#39;s used to create interactive elements that users can click on. Just like a button you press in real life, the &lt;button&gt; tag triggers actions or events on a webpage when clicked.</p><p>In simpler terms, the &lt;button&gt; tag is like a click-able command. It&#39;s a way to tell the webpage, &quot;Hey, when someone clicks on this, do something!&quot; This could be submitting a form, opening a pop-up, or any other action you want to happen when a user interacts with your webpage.</p><p>Let’s take a simple example to understand this!</p><pre>&lt;body&gt;<br>    &lt;h1&gt;This is Button Tag&lt;/h1&gt;<br>    &lt;button onclick=&quot;alert(&#39;you clicked button!&#39;)&quot;&gt;Click me!&lt;/button&gt;<br>&lt;/body&gt;</pre><p>This code piece makes a button. When you see the button, it says “Click me!” The button has something special called an “onclick” attribute. This tells the button what to do when someone clicks it.</p><p>Usually, you’d use this for things like sending a form (which we’ll cover soon) or opening a small window. Often, you’d involve JavaScript (JS) to make buttons do cool stuff. Now, JS is a bit advanced for this article, but here, I’ve used a simple trick. When you click, a message pops up saying “You clicked the button!” It’s a quick way to see the button doing something. You can copy this and try it out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*A05qwTakVmH7l1d_NHH4og.png" /></figure><p><strong>Images: The Visual Magic of Webpages! 🌄✨Let’s dive into the art of adding images to your webpage and watch your content come to life!</strong></p><p>&lt;img&gt; — Remember when we discussed about self-closing tags, img tag is one of the self closing tag, that has an attribute called “src”, which is short for source. With its ‘src’ attribute (source), you choose where your image comes from — a link online or a local gem. We’re diving into both options, so get ready to make your page pop with pictures!</p><pre>&lt;body&gt;<br>    &lt;h1&gt;Adding Images!!&lt;/h1&gt;<br>    &lt;img src=&quot;https://picsum.photos/200&quot; alt=&quot;Random lorem image&quot;&gt;<br>&lt;/body&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*E0r-oDG_bhO18ZbBEVaF9w.png" /></figure><p>The “alt” attribute on an image is like a safety net for accessibility. It’s a short text description you add to an image using HTML. This description is read aloud by screen readers for people who can’t see the image, like those with visual impairments.</p><p>Think of it as a way to provide context and meaning to the image. If the image doesn’t load or someone can’t see it, the “alt” text steps in to explain what’s missing. This makes your webpage more inclusive and ensures everyone gets the full picture, even if they can’t actually see the image.</p><p>Using Local Images? Here’s How: Imagine you want images right from your computer. Make a folder called ‘img’ in your main folder where all your HTML stuff lives. Drop your image in there. We’ll show you how to connect it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*hg2xZvfwb6Pzmk3pb3-BoA.png" /></figure><p>Once you have your image let’s connect it!</p><pre>&lt;body&gt;<br>    &lt;h1&gt;Adding local Images!!&lt;/h1&gt;<br>    &lt;img src=&quot;./img/my-local-image.jpg&quot; alt=&quot;Using local images&quot;&gt;<br>&lt;/body&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*bOe-nG09ERqA5CAMOLrpzA.png" /></figure><p><strong>Changing width &amp; height of images! Attributes have made our lives easy, there’s an attribute called “width” &amp; an attribute called “height” to change the dimensions of your image</strong></p><pre>&lt;body&gt;<br>    &lt;h1&gt;Adding local Images!! Width - 300px &amp; Height - 400px&lt;/h1&gt;<br>    &lt;img src=&quot;./img/my-local-image.jpg&quot; width=&quot;300&quot; height=&quot;350&quot; alt=&quot;Using local images&quot;&gt;<br>&lt;/body&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsfuE7rCbH7o-2C-4XmhnQ.png" /></figure><p><strong>Let’s learn about </strong><strong>&lt;div&gt; — Division tag! The tag that divides and conquers like a master organizer</strong></p><p>Before jumping into &lt;div&gt;&#39;s , we must understand the concept of <strong>“block”</strong> elements and <strong>“inline”</strong> elements</p><p><strong>Block-Level Elements</strong>: They’re like big building blocks that stack on top of each other to make the structure of your page. Stuff like headings and paragraphs are block-level.</p><p><strong>Inline Elements</strong>: Think of them as little puzzle pieces that fit into a sentence. Links and bold text are inline. They’re like the structure builders and word enhancers of your webpage! 🏰🔤</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kiiOXtswC3qUhgWp.jpeg" /></figure><p>The &lt;div&gt; tag is like a versatile container in HTML. It&#39;s used to group and organize other elements together, a bit like putting things in a box. This makes styling and arranging content easier. Think of it as a magic box that helps you keep your webpage neat and tidy! 🎁📦</p><p>You’ll encounter &lt;div&gt; tags frequently in web development. They&#39;re incredibly useful for organizing elements and also play a significant role in styling your webpage, ensuring both structure and appearance are well-managed!</p><pre>&lt;body&gt;<br>    &lt;h1&gt;Organizing content with div&#39;s - The magic container!&lt;/h1&gt;<br>    &lt;div style=&quot;border: 2px solid #333333; margin: 5px; padding: 5px;&quot;&gt;<br>        &lt;h2&gt;Large Pizza!&lt;/h2&gt;<br>        &lt;p&gt;Large pizza serves 4 people - &lt;b&gt;Rs 600/-&lt;/b&gt;&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div style=&quot;border: 2px solid #333333; margin: 5px; padding: 5px;&quot;&gt;<br>        &lt;h2&gt;Medium Pizza!&lt;/h2&gt;<br>        &lt;p&gt;Large pizza serves 2 people - &lt;b&gt;Rs 400/-&lt;/b&gt;&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;div style=&quot;border: 2px solid #333333; margin: 5px; padding: 5px;&quot;&gt;<br>        &lt;h2&gt;Small Pizza!&lt;/h2&gt;<br>        &lt;p&gt;Small pizza serves 1 people - &lt;b&gt;Rs 200/-&lt;/b&gt;&lt;/p&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Te48zsYnWBnoB06P5YFmDA.png" /></figure><p>In this code, we’ve used &lt;div&gt; elements to act like magical containers. Each &lt;div&gt; groups together specific information. For instance, the first &lt;div&gt; holds details about a &quot;Large Pizza,&quot; with its serving size and price. The second &lt;div&gt; does the same for a &quot;Medium Pizza,&quot; and the third for a &quot;Small Pizza.&quot;</p><p>Notice how everything is neatly organized? It’s like placing each pizza description in its own special box. And hey, just so you know, the “style” part you see is like giving each box a particular look. I’ve used borders and spacing to show how divs act as containers, but in real web pages, CSS helps make them look really cool! 🍕📦💨</p><p><strong>Congratulations for reaching this point! 🎉 Now, let’s take one more step and learn about forms — the final piece of the puzzle before we’re all set!</strong></p><p><strong>&lt;input&gt;</strong> : Need user input? Meet the &lt;input&gt; tag – your go-to hero! It&#39;s like a magical gateway for various tasks. Whether it&#39;s passwords, answering questions, making to-do lists, or choosing options with checkboxes and radio buttons, &lt;input&gt; has your back! 💪🔤🗳️</p><pre>&lt;body&gt;<br>    &lt;h1&gt;Let&#39;s understand inputs!&lt;/h1&gt;<br>    &lt;div style=&quot;border: 2px solid #333333; margin: 5px; padding: 5px;&quot;&gt;<br>        &lt;h2&gt;Text input&lt;/h2&gt;<br>        &lt;input placeholder=&quot;Enter text&quot; type=&quot;text&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;div style=&quot;border: 2px solid #333333; margin: 5px; padding: 5px;&quot;&gt;<br>        &lt;h2&gt;Password&lt;/h2&gt;<br>        &lt;input placeholder=&quot;Enter your password&quot; type=&quot;password&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;div style=&quot;border: 2px solid #333333; margin: 5px; padding: 5px;&quot;&gt;<br>        &lt;h2&gt;Pick a date!&lt;/h2&gt;<br>        &lt;input type=&quot;date&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;div style=&quot;border: 2px solid #333333; margin: 5px; padding: 5px;&quot;&gt;<br>        &lt;h2&gt;checkbox&lt;/h2&gt;<br>        &lt;input type=&quot;checkbox&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;div style=&quot;border: 2px solid #333333; margin: 5px; padding: 5px;&quot;&gt;<br>        &lt;h2&gt;Radio&lt;/h2&gt;<br>        &lt;input type=&quot;radio&quot;&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LP_OAf3W5bQkd3681h2Ilg.png" /></figure><p>In this code snippet, I’ve included the main types of inputs you’ll often use! Each input has a special ‘type’ attribute that defines what kind of input it is. They also have a ‘placeholder’ attribute, like a little hint to tell users what goes there.</p><p>After filling in these inputs, there’s usually a form submission. This sends the entered data to do something behind the scenes. Now, let’s explore how to send this info using a form!</p><pre>&lt;body&gt;<br>    &lt;h1&gt;Let&#39;s build a simple form!&lt;/h1&gt;<br>    &lt;form onsubmit=&quot;login(event)&quot;&gt;<br>        &lt;h2&gt;Login form&lt;/h2&gt;<br>        &lt;div style=&quot;margin-bottom: 5px;&quot;&gt;<br>            &lt;input name=&quot;email&quot; placeholder=&quot;Enter your email&quot; type=&quot;email&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>            &lt;input name=&quot;password&quot; placeholder=&quot;Enter password&quot; type=&quot;password&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Login!&lt;/button&gt;<br>    &lt;/form&gt;<br>    &lt;script&gt;<br>        function login(event) {<br>            event.preventDefault();<br>            alert(`<br>                Email - ${event.target.email.value}<br>                Password - ${event.target.password.value}<br>            `)<br>        }<br>    &lt;/script&gt;<br>&lt;/body&gt;</pre><p>Hey, no worries if this looks a bit puzzling at first! Let’s break it down:</p><ol><li><strong>Building a Form</strong>: We’re starting by building a form. Think of it like a container for gathering information.</li><li><strong>Login Form</strong>: Inside this form, we’re making a login form. It has two sections: one for your email and one for your password.</li><li><strong>Input Fields</strong>: See the email and password boxes? You can type your email and password here. The placeholder text guides you on what to enter.</li><li><strong>Submit Button</strong>: Below, there’s a button with “Login!” written on it. When you click this button, the form gets submitted.</li><li><strong>The Magic of “onsubmit”</strong>: The onsubmit attribute is like a signal. It says, &quot;Hey, when the form is submitted, call this function named &#39;login&#39;.&quot; It&#39;s a way to handle what happens when you hit that login button.</li><li><strong>The JavaScript Part</strong>: Don’t worry if the JavaScript part seems a bit mysterious. The login function takes the event (when you submit the form), stops the form from doing its default thing (that&#39;s the event.preventDefault(); part), and then it shows you an alert with the email and password you entered.</li></ol><p>So, this code lets you build a basic login form and understand how the pieces fit together. It might look like a lot, but each part has its role, just like actors in a play! 🎭📝🔒</p><p><strong>Bonus: Let’s become HTML hacker with browser inspect!</strong></p><p>“Embrace the Inspector: Your Debugging Ally! 🕵️‍♂️ Embracing the fact that even pros make mistakes, as a Frontend or Full-stack developer, you’ll find yourself using the ‘inspector’ tool for code troubleshooting. It’s like peeking backstage to see what’s really happening.</p><p>Today, let’s dip our toes into the world of inspector. It’s a powerful tool with many tricks. Open any website, right-click, and choose ‘inspect.’ Click on the ‘elements’ tab that pops up. You’ll be greeted with the website’s HTML code. Guess what? You can even edit it right there! Your browser updates instantly. It’s like a magician’s wand for fixing stuff!” 🧙🔍✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Kox6QuqZRr8A0qMYR1T2Ug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUTgLo8J5M4J4h5dq5-WnA.png" /></figure><p>I’ll Let You Explore From Here! Best of Luck! 😄 Feel free to embark on a simple project. No need to stress about it looking perfect or having fancy features just yet. Start by creating the layout using HTML. Later, when you learn CSS and JS, you can sprinkle in colors and functions. Have fun on your coding journey!” 🚀🎉</p><p><strong>Final Words!</strong></p><p>Fantastic Job on Reaching This Far! 🎉 Congratulations, you’ve mastered the fundamental building blocks of HTML. Don’t fret if you stumble upon something new — you’ve got the basics down. Just explore further on the internet, and you’ll crack it. Remember, you don’t need to be a walking encyclopedia of tech. Tech is vast, and there’s always something new, even for experts. Focus on the foundation, and don’t hesitate to look up unfamiliar things online.</p><p>That’s a Wrap from Me! Until Next Time, Good Luck on Your Coding Adventures! 🚀👋</p><p>Feel free to reach out at — sahildarji16@gmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afaf87a61c3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>