<?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 Atul jha on Medium]]></title>
        <description><![CDATA[Stories by Atul jha on Medium]]></description>
        <link>https://medium.com/@atuljha2402?source=rss-d100b49c8be3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*J4oyrr8DiqiFQcBbis4LUw.jpeg</url>
            <title>Stories by Atul jha on Medium</title>
            <link>https://medium.com/@atuljha2402?source=rss-d100b49c8be3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:55:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atuljha2402/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[Cloudflare, Lava Lamps, and the Science of Keeping Your Data Safe]]></title>
            <link>https://medium.com/@atuljha2402/cloudflare-lava-lamps-and-the-science-of-keeping-your-data-safe-d25e9b9e8348?source=rss-d100b49c8be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d25e9b9e8348</guid>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[cloudflare]]></category>
            <dc:creator><![CDATA[Atul jha]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 17:30:50 GMT</pubDate>
            <atom:updated>2025-12-19T17:32:14.625Z</atom:updated>
            <content:encoded><![CDATA[<p>When we hear the word <strong>encryption</strong>, most people imagine complex math, hackers, or government secrets.<br>But one of the world’s largest internet security companies, <strong>Cloudflare</strong>, uses something surprisingly simple <strong>lava lamps</strong> to help keep the internet safe.</p><p>Sounds unbelievable?<br>Let’s break it down step by step.</p><h3>1. What Problem Is Cloudflare Trying to Solve?</h3><h3>1.1. The core problem: randomness</h3><p>At the heart of encryption lies one critical requirement:</p><blockquote><strong><em>Encryption keys must be unpredictable</em></strong></blockquote><p>If someone can <em>guess</em> or <em>predict</em> your encryption key, then:</p><ul><li>Passwords can be stolen</li><li>Messages can be read</li><li>Bank transactions can be manipulated</li></ul><h3>Example</h3><p><strong>Student:</strong> But computers are super fast. Can’t they just generate random numbers?</p><p><strong>Teacher:</strong> Computers are fast, but they are <em>not random</em>. They follow instructions.</p><p>Computers are deterministic machines.<br>If you give the same input, you get the same output.</p><p>That’s dangerous for encryption.</p><h3>2. Why Poor Randomness Breaks Encryption</h3><h3>2.1. Real-world failures caused by bad randomness</h3><p>History has shown us that <strong>weak randomness destroys security</strong>:</p><ul><li>Debian OpenSSL bug (2008)</li><li>Sony PlayStation private key leak</li><li>Early Bitcoin wallet hacks</li></ul><p>In all these cases:</p><ul><li>The encryption algorithm was correct</li><li><strong>Random number generation was flawed</strong></li></ul><p>So Cloudflare asked a simple question:</p><blockquote><em>“How do we generate randomness that computers can’t predict?”</em></blockquote><h3>3. Enter Lava Lamps 🌋</h3><h3>3.1. Why lava lamps?</h3><p>Lava lamps are chaotic systems:</p><ul><li>Fluid motion</li><li>Heat convection</li><li>Air pressure</li><li>Tiny environmental changes</li></ul><p>No two lava lamp movements are ever identical.</p><p>That’s <strong>real-world physical randomness</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNhmHItxqDyXQNZyVwp10g.jpeg" /></figure><h3>4. How Cloudflare Uses Lava Lamps (Step-by-Step)</h3><h3>4.1. Capturing chaos</h3><p>Cloudflare has:</p><ul><li>A wall of ~100 lava lamps</li><li>A camera continuously capturing images</li></ul><p>Each image is made of <strong>millions of pixels</strong>.</p><h3>4.2. Images are already numbers</h3><p>Each pixel contains:</p><pre>Red:   0–255<br>Green: 0–255<br>Blue:  0–255</pre><p>So an image becomes a massive list of numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWBfVPiP7a2wVe6TX_LRBQ.jpeg" /></figure><h3>5. From Image to Random Numbers</h3><h3>5.1. Raw data is not enough</h3><p>Camera images can have:</p><ul><li>Bias</li><li>Sensor noise patterns</li><li>Lighting artifacts</li></ul><p>So Cloudflare does <strong>not</strong> use pixel data directly.</p><h3>5.2. Cryptographic hashing (the magic step)</h3><p>The pixel data is passed through cryptographic hash functions like:</p><ul><li>SHA-256</li><li>SHA-512</li></ul><p>This process:</p><ul><li>Removes bias</li><li>Destroys patterns</li><li>Produces uniformly random output</li></ul><p>Even a <strong>1-pixel change</strong> creates a completely different result.</p><h3>6. Lava Lamps Are Not the Only Source of Randomness</h3><p>This is a very important point.</p><h3>6.1. Defense in depth</h3><p>Cloudflare <strong>never relies on one source</strong>.</p><p>They mix lava lamp entropy with:</p><ul><li>CPU hardware RNGs (Intel RDRAND, RDSEED)</li><li>OS entropy pools</li><li>Network timing jitter</li><li>Disk and system noise</li></ul><p>Conceptually:</p><pre>Final Randomness = Hash(<br>  LavaLampEntropy +<br>  HardwareRNG +<br>  OSNoise +<br>  TimingJitter<br>)</pre><h3>Example</h3><p><strong>Student:</strong> “What if someone hacks the camera?”</p><p><strong>Teacher:</strong> “Even then, the system stays secure because lava lamps are only one ingredient.”</p><h3>7. What Is This Randomness Actually Used For?</h3><h3>7.1. Lava lamps do NOT encrypt your data</h3><p>This is a common misconception.</p><p>Lava lamps are used to:</p><ul><li>Generate <strong>strong encryption keys</strong></li><li>Seed cryptographically secure random generators</li></ul><p>They do <strong>not</strong>:</p><ul><li>Encrypt messages</li><li>Decrypt traffic</li><li>Store keys</li></ul><h3>7.2. What encryption protects</h3><p>Cloudflare’s encryption protects:</p><ul><li>Passwords</li><li>Credit card details</li><li>API traffic</li><li>Cookies and sessions</li><li>Data integrity (no tampering)</li></ul><h3>8. HTTPS, Cloudflare, and Your Browser</h3><h3>8.1. How HTTPS fits in</h3><p>When you visit a website:</p><ul><li>Your browser negotiates encryption keys</li><li>Data travels through an encrypted tunnel</li><li>Cloudflare helps manage this securely</li></ul><p>Cloudflare sits between:</p><pre>User ↔ Cloudflare ↔ Website Server</pre><p>Cloudflare can see <strong>encrypted traffic</strong>, but encryption ensures:</p><ul><li>Attackers can’t read it</li><li>Data can’t be modified</li></ul><h3>9. How This Differs from WhatsApp End-to-End Encryption</h3><h3>9.1. HTTPS vs E2EE</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*jgT-yI34YV7gfzurgCEljg.png" /></figure><p>WhatsApp uses <strong>Signal Protocol</strong>, where:</p><ul><li>Keys are generated on phones</li><li>Servers never see plaintext</li></ul><p>Same goal: <strong>privacy</strong><br>Different architecture.</p><h3>10. Simple Analogy (For Non-Tech Readers)</h3><p>Imagine:</p><ul><li>Encryption keys are locks</li><li>Data is a box</li><li>Randomness decides how strong the lock is</li></ul><p>Using predictable randomness is like:</p><blockquote><em>Using a lock whose pattern repeats</em></blockquote><p>Using lava lamps is like:</p><blockquote><em>Designing a lock using natural chaos</em></blockquote><p>That lock cannot be copied.</p><h3>11. Why This Matters to You</h3><p>Even if you never think about encryption:</p><ul><li>Every login</li><li>Every payment</li><li>Every API request</li><li>Every private message (indirectly)</li></ul><p>Depends on <strong>unpredictable randomness</strong>.</p><p>Cloudflare’s lava lamps are a reminder that:</p><blockquote><em>Sometimes, the safest digital systems depend on the physical world.</em></blockquote><h3>12. Final Thoughts</h3><p><strong>Cloudflare didn’t invent encryption.</strong><br>They simply made one invisible part visible.</p><p>Lava lamps don’t secure the internet by themselves they <strong>strengthen the foundation</strong> encryption is built on.</p><p>And that is how you can be assured about <strong>safe data</strong> 🔐</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d25e9b9e8348" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Context and API Abstraction to Simplify Auth in Large React Apps]]></title>
            <link>https://medium.com/@atuljha2402/using-context-and-api-abstraction-to-simplify-auth-in-large-react-apps-f66497c6e268?source=rss-d100b49c8be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f66497c6e268</guid>
            <category><![CDATA[context-api]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[abstraction]]></category>
            <dc:creator><![CDATA[Atul jha]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 18:44:23 GMT</pubDate>
            <atom:updated>2025-06-22T18:46:16.302Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Context and API Abstraction to Simplify Auth in Large sites</h3><p>In large React apps, managing authentication can feel like trying to serve chai (Tea) in a leaky kulhad — just when you think it’s sorted, the token or user info starts spilling out in some random component. And let’s be real: copy-pasting the same fetch() headers or passing user props down ten levels feels like doing jugaad in a system that badly needs a proper solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9HoLhwUuQwDJVQgIJEANWQ.png" /></figure><p>So, what’s the solution?</p><p><strong>React Context + API abstraction.</strong> Together, they form a superhero duo that makes your auth logic centralized, reusable, and clean.</p><h3>The Pain: Auth in Large Projects</h3><p>Before diving into the solution, let’s paint a picture of the chaos:</p><ul><li>You keep duplicating login/logout logic in multiple components.</li><li>Props like token, user, and workspace are being passed down like hot potatoes.</li><li>Every API call requires manually adding Authorization headers.</li><li>Token expires and you’re force-logging out users like it’s 2009.</li></ul><p>Sounds familiar? Been there. Done that.</p><h3>The Solution: Centralizing Auth with Context</h3><p>React’s Context API lets us share state (like tokens or user info) across the app using Auth context.</p><p>The AuthContext pattern centralizes authentication logic and state into a single, reusable context that can be accessed anywhere in your React component tree — no matter how deeply nested.</p><p>Instead of:</p><ul><li>Manually storing the user or token in multiple components</li><li>Manually passing token, user, login(), logout() down via props</li><li>Rewriting API logic everywhere…</li></ul><p>…you define everything once inside AuthProvider, then consume it anywhere with useAuth().</p><h3>Setting up the Auth System</h3><p>To get started, you’ll need the following:</p><h3>1. Environment Variables (typically on your server/backend):</h3><pre>AUTH_SECRET=your_jwt_secret<br>REFRESH_SECRET=your_refresh_token_secret<br>TOKEN_EXPIRES_IN=15m<br>REFRESH_EXPIRES_IN=7d</pre><h3>2. Data you’ll receive from login API:</h3><p>A typical /login response looks like:</p><pre>{<br>  &quot;token&quot;: &quot;access.jwt.token&quot;,<br>  &quot;refreshToken&quot;: &quot;refresh.jwt.token&quot;,<br>  &quot;user&quot;: {<br>    &quot;id&quot;: &quot;123&quot;,<br>    &quot;name&quot;: &quot;Atul&quot;,<br>    &quot;roles&quot;: [&quot;admin&quot;, &quot;user&quot;]<br>  }<br>}</pre><h3>The OG: AuthContext in Action</h3><p>To set up centralized auth state, first create a context and provider. We define an AuthContext with createContext(), and an AuthProvider component that uses React state internally (often via useState or useReducer) to store the current user, token, and roles. For example:</p><pre>import { createContext, useState, useContext, useEffect } from &#39;react&#39;;<br><br>// Create the AuthContext with default empty value<br>const AuthContext = createContext();<br><br>/**<br> * AuthProvider wraps the app and provides auth state to children.<br> * It holds the user object, token, and login/logout functions.<br> */<br>export const AuthProvider = ({ children }) =&gt; {<br>  // Initialize token from storage (if any) to persist login after refresh<br>  const [token, setToken] = useState(() =&gt; localStorage.getItem(&#39;token&#39;) || &#39;&#39;);<br>  const [user, setUser] = useState(() =&gt; JSON.parse(localStorage.getItem(&#39;user&#39;)) || null);<br>   <br>  // Login action: call API, set token &amp; user, and save them<br>  const login = async (username, password) =&gt; {<br>    const res = await fetch(&#39;/api/auth/login&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>      body: JSON.stringify({ username, password })<br>    });<br>    const data = await res.json();<br>    setToken(data.token);<br>    setUser(data.user);<br>    localStorage.setItem(&#39;token&#39;, data.token);<br>    localStorage.setItem(&#39;user&#39;, JSON.stringify(data.user));<br>    localStorage.setItem(&#39;refreshToken&#39;, data.refreshToken);<br>  };<br><br>  // Logout action: clear state and storage, then redirect or clean up<br>  const logout = () =&gt; {<br>    setToken(&#39;&#39;);<br>    setUser(null);<br>    localStorage.clear();<br>  };<br><br>  return (<br>    &lt;AuthContext.Provider value={{ token, user, login, logout }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>};<br><br>// Hook for child components to access auth context easily<br>export const useAuth = () =&gt; useContext(AuthContext);</pre><p>In this setup, AuthProvider manages all authentication data and methods. It holds the token and user info (including roles) and exposes them via AuthContext.Provider. Any component wrapped by this provider can call our custom useAuth() hook to read or update auth state. <br>For example, the above code will allow any component to do: <br>const { user, token, login, logout } = useAuth() to get the current user and methods. Wrapping your &lt;App&gt; with &lt;AuthProvider&gt; (as above) makes the context available throughout</p><h3>Login Flow Architecture (Diagram)</h3><p>Here’s a simplified flow of how login works with Context and REST APIs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*ainW8SqKTiY4GCp2sULaag.png" /></figure><p>This is how you log in <strong>once</strong> and every part of the app gains access.</p><h3>The reliable son: fetchAuthenticated()</h3><p>Here’s where we bring in our trusty sidekick: a function/wrapper to standardize API calls with the token included.</p><pre>/**<br> * Helper to make API calls with the Authorization header.<br> * It reads the token (from context or storage) and attaches it.<br> */<br>async function fetchAuthenticated(url, options = {}) {<br>  // Get token from storage (or context, if you prefer useAuth inside a hook)<br>  const authToken = localStorage.getItem(&#39;token&#39;) || &#39;&#39;;<br>  const headers = new Headers(options.headers || {});<br>  if (authToken) {<br>    headers.set(&#39;Authorization&#39;, `Bearer ${authToken}`);<br>  }<br>  // Example default to JSON:<br>  if (!headers.has(&#39;Content-Type&#39;)) {<br>    headers.set(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>  }<br>  const response = await fetch(url, { ...options, headers });<br>  if (!response.ok) {<br>    // Optional: handle 401/403 (token expired)<br>    throw new Error(response.statusText || &#39;Request failed&#39;);<br>  }<br>  return await response.json();<br>}</pre><p>Now your API calls are cleaner than a fresh install:</p><pre>const data = await fetchAuthenticated(&#39;/api/data&#39;);</pre><p>With this wrapper, making an authenticated API call becomes simpler: for example await fetchAuthenticated(&#39;/api/data&#39;). Internally it takes care of headers and JSON parsing. This pattern is common in React apps. <br>The core idea is to factor out the Authorization: Bearer &lt;token&gt; header logic so every component needn’t repeat it.</p><p>You could also handle expired tokens here: if the response is a 401 Unauthorized, you might call a <strong>refresh endpoint</strong> and retry (see next section). For basic scenarios, throwing on non-OK responses (as above) is fine; you can catch errors at the call site or improve the wrapper to handle 401 specially.</p><p>We have talked about refresh endpoint a lot, so lets understand it now:</p><h3>What is a Refresh Token?</h3><ul><li>A <strong>refresh token</strong> is a long-lived token that helps you get a new access token <strong>without forcing the user to log in again</strong>.</li><li>Access tokens are short-lived (10–15 mins), while refresh tokens last longer (7–30 days).</li><li>When your access token expires (typically shown as a 401 error), use the refresh token to get a new one from /auth/refresh.</li><li>Store refresh tokens securely — <strong>preferably in HttpOnly cookies</strong>. For this blog, we use localStorage for simplicity.</li></ul><pre>const fetchWithRefresh = async (url, options = {}) =&gt; {<br>  try {<br>    return await fetchAuthenticated(url, options); //For fetching auth token<br>  } catch (err) {<br>    if (err.message === &#39;401&#39;) {<br>      const refreshToken = localStorage.getItem(&#39;refreshToken&#39;);<br>      const res = await fetch(&#39;/api/auth/refresh&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>        body: JSON.stringify({ token: refreshToken })<br>      });<br>      const data = await res.json();<br>      localStorage.setItem(&#39;token&#39;, data.token);<br>      return await fetchAuthenticated(url, options);<br>    }<br>  }<br>};</pre><h3>Real-Life Usage: Role-Based UI</h3><p>Let’s say your user <strong>object</strong> looks like this:</p><pre>{<br>  name: &quot;Atul&quot;,<br>  roles: [&quot;admin&quot;]<br>}</pre><p>Boom. Role-based access is now a one-liner:</p><pre>const { user } = useAuth();<br>{user?.roles.includes(&#39;admin&#39;) &amp;&amp; &lt;AdminPanel /&gt;}</pre><p>Want to show/hide navigation items?</p><pre>{user ? (<br>  &lt;button onClick={logout}&gt;Logout&lt;/button&gt;<br>) : (<br>  &lt;Link href=&quot;/login&quot;&gt;Login&lt;/Link&gt;<br>)}</pre><p>Now lets understand this using a in-depth real life example of login page where we will get user’s role from server and based upon that we will route user to internal page</p><ul><li>Authenticates the user</li><li>Immediately uses the login response to route based on roles (admin or user)</li></ul><pre>// components/LoginPage.jsx<br>import { useState } from &#39;react&#39;;<br>import { useAuth } from &#39;../context/AuthContext&#39;;<br>import { useRouter } from &#39;next/router&#39;;<br><br>export default function LoginPage() {<br>  const { login } = useAuth(); <br>  const router = useRouter();<br>  const [username, setUsername] = useState(&#39;&#39;);<br>  const [password, setPassword] = useState(&#39;&#39;);<br>  const [error, setError] = useState(&#39;&#39;);<br><br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    try {<br>      // login() now returns the user <br>      const loggedInUser = await login(username, password);<br><br>      // Safely check roles and redirect accordingly<br>      if (loggedInUser.roles.includes(&#39;admin&#39;)) {<br>        router.push(&#39;/admin/dashboard&#39;);<br>      } else {<br>        router.push(&#39;/user/home&#39;);<br>      }<br>    } catch (err) {<br>      setError(&#39;Invalid credentials&#39;);<br>    }<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit} className=&quot;space-y-4 max-w-md mx-auto&quot;&gt;<br>      &lt;h2 className=&quot;text-xl font-bold&quot;&gt;Login&lt;/h2&gt;<br><br>      &lt;input<br>        type=&quot;text&quot;<br>        value={username}<br>        onChange={(e) =&gt; setUsername(e.target.value)}<br>        placeholder=&quot;Username&quot;<br>        className=&quot;border p-2 w-full&quot;<br>      /&gt;<br><br>      &lt;input<br>        type=&quot;password&quot;<br>        value={password}<br>        onChange={(e) =&gt; setPassword(e.target.value)}<br>        placeholder=&quot;Password&quot;<br>        className=&quot;border p-2 w-full&quot;<br>      /&gt;<br><br>      {error &amp;&amp; &lt;p className=&quot;text-red-500&quot;&gt;{error}&lt;/p&gt;}<br><br>      &lt;button type=&quot;submit&quot; className=&quot;bg-blue-600 text-white px-4 py-2&quot;&gt;<br>        Login<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>When the user logs in, we inspect their roles array and push them to the appropriate dashboard. This could also be handled server-side with route guards. This second example returns the user directly from the login() function and uses it immediately — making the flow more realistic for role based routing.</p><h3>Why Context API is better?</h3><ul><li><strong>No more prop drilling</strong></li><li><strong>Reusable API calls</strong></li><li><strong>Centralized security</strong></li><li><strong>Cleaner UI code</strong></li><li><strong>Less cognitive overhead</strong></li></ul><p>Whether you’re building a SaaS dashboard, eCommerce admin, or anything complex — Context + API abstraction is the blueprint to scale your app’s authentication layer without chaos.</p><h3>Conclusion:</h3><p>Don’t treat authentication like a one-off problem. It’s the backbone of any real-world app. If it’s messy, everything becomes harder. <strong>Use Context. Abstract your APIs. Sleep better.</strong></p><blockquote>If you found this content helpful and informative, I would greatly appreciate your support by following my profile. By following, you can stay updated with my future articles and gain more valuable insights into Salesforce &amp; Web development and other related topics. Your support means a lot to me, and I look forward to sharing more useful content with you in the future. Thank you for your time and consideration!</blockquote><p>If you enjoyed what you read &amp; found it insightful, please consider supporting me <a href="https://buymeacoffee.com/atuljha24"><strong>here</strong> Your support is greatly appreciated!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f66497c6e268" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React’s useContext Hook]]></title>
            <link>https://medium.com/@atuljha2402/reacts-usecontext-hook-e11c831ff714?source=rss-d100b49c8be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e11c831ff714</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[usecontext]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Atul jha]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 11:05:51 GMT</pubDate>
            <atom:updated>2024-09-01T11:05:51.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgPJnkd5WiGnuTIqjZ-jZA.png" /></figure><blockquote>Unlock Simplified State Management for Web and App Development</blockquote><p>In the ever-evolving scenario of web and app development, managing state across components can often become a challenging task, especially in larger applications. React, one of the most popular JavaScript libraries, offers several hooks to simplify this process. Among them, the useContext hook stands out as a powerful tool for managing global state in simpler way compared to traditional methods like prop drilling. In this article we will explore the useContext hook in detail, its advantages, and how it can be utilised in both web and app development with two practical examples.</p><blockquote>Best thing about <strong>useContext</strong> is that its implementation is same for both Web development using React &amp; App development using React Native</blockquote><h3>Understanding the useContext Hook</h3><p>React’s useContext hook allows developers to access and share state across the entire component tree without passing props down manually at every level. Introduced in React 16.8, useContext works alongside the Context API, which was introduced earlier in React 16.3. While the Context API itself allows you to create a global state that can be accessed by any component, useContext simplifies the way this state is consumed.</p><p>When you create a context using React.createContext(), you can think of it as creating a global state container. Components that need access to this state can subscribe to it using the useContext hook. This approach eliminates the need for &quot;prop drilling,&quot; where you pass data through multiple layers of components, making your code cleaner and more maintainable. <strong>Now lets understand different scenario in which developers generally use useContext:</strong></p><h3>Real-Life Use Cases of useContext in Web and App Development</h3><p>The useContext hook shines in various real-life scenarios in both web and app development. Below are some practical use cases where useContext can make state management easier and more efficient.</p><h4>1. Theming</h4><p>One of the most common use cases of useContext is theming. Suppose you have a web or mobile app that supports light and dark themes. Managing this across multiple components can quickly become tedious if you rely on passing theme data through props. With useContext, you can set up a global theme context that all components can access.</p><h4>2. Passing / Accessing common states all over Website or App</h4><p>Generally we use to useContext to pass fetched data from API to all the components &amp; then consume or perform CRUD operation on retrieved data. Managing data across multiple components can quickly become tedious if you rely on passing theme data through props or calling API on different components. With useContext, you can set up a global data context that all components can access. This is particularly useful in larger apps where components might need to react to the same state changes, such as updating a user profile across different sections of a dashboard.</p><h4>3. Authentication</h4><p>Authentication state is another area where useContext proves to be highly useful. Whether you&#39;re developing a web application or a mobile app, managing user authentication and providing user-specific data across different components can be complex. useContext allows you to centralize the authentication logic and make it easily accessible throughout the app.</p><h4>4. Localization</h4><p>If your app supports multiple languages, you’ll likely need to manage and access localised content across different components. useContext can be used to create a global context for the current language and localisation functions, making it easier to switch languages and update content dynamically without prop drilling.</p><h3>Code-Based Example: Using useContext for Theming</h3><p>Let’s walk through a simple example to illustrate how useContext can be used to manage themes in a React application. This example will cover both web and app development using React and React Native.</p><h4>Step 1: Creating the Context</h4><p>First, we need to create a context that will hold our theme data.</p><pre>import React, { createContext, useState } from &#39;react&#39;;<br><br>export const ThemeContext = createContext();<br><br>export const ThemeProvider = ({ children }) =&gt; {<br>    const [theme, setTheme] = useState(&#39;light&#39;);<br><br>    const toggleTheme = () =&gt; {<br>        setTheme((prevTheme) =&gt; (prevTheme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;));<br>    };<br><br>    return (<br>        &lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;<br>            {children}<br>        &lt;/ThemeContext.Provider&gt;<br>    );<br>};</pre><p>In this code, we create a ThemeContext using createContext() and a ThemeProvider component that holds the theme state and a function to toggle between light and dark modes.</p><h4>Step 2: Consuming the Context</h4><p>Next, we use the useContext hook to consume the theme data in any component that needs it. Here&#39;s an example of how this would look in a simple component:</p><pre>import React, { useContext } from &#39;react&#39;;<br>import { ThemeContext } from &#39;./ThemeProvider&#39;;<br><br>const ThemedComponent = () =&gt; {<br>    const { theme, toggleTheme } = useContext(ThemeContext);<br><br>    return (<br>        &lt;div style={{ <br>            backgroundColor: theme === &#39;light&#39; ? &#39;#fff&#39; : &#39;#333&#39;, <br>            color: theme === &#39;light&#39; ? &#39;#000&#39; : &#39;#fff&#39;, <br>            padding: &#39;20px&#39;,<br>            textAlign: &#39;center&#39; <br>        }}&gt;<br>            &lt;p&gt;The current theme is {theme}&lt;/p&gt;<br>            &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default ThemedComponent;</pre><p>In this ThemedComponent, the useContext hook allows us to access the current theme and toggle function directly. This component will render differently based on the theme and provide a button to switch themes.</p><h4>Step 3: Integrating with React Native (App Development)</h4><p>The process for React Native is nearly identical, with minor adjustments for styling. Here’s how you might implement the same theme toggle in a React Native app:</p><pre>import React, { useContext } from &#39;react&#39;;<br>import { View, Text, Button, StyleSheet } from &#39;react-native&#39;;<br>import { ThemeContext } from &#39;./ThemeProvider&#39;;<br><br>const ThemedComponent = () =&gt; {<br>    const { theme, toggleTheme } = useContext(ThemeContext);<br><br>    return (<br>        &lt;View style={[<br>            styles.container, <br>            { backgroundColor: theme === &#39;light&#39; ? &#39;#fff&#39; : &#39;#333&#39; }<br>        ]}&gt;<br>            &lt;Text style={{ color: theme === &#39;light&#39; ? &#39;#000&#39; : &#39;#fff&#39; }}&gt;<br>                The current theme is {theme}<br>            &lt;/Text&gt;<br>            &lt;Button title=&quot;Toggle Theme&quot; onPress={toggleTheme} /&gt;<br>        &lt;/View&gt;<br>    );<br>};<br><br>const styles = StyleSheet.create({<br>    container: {<br>        flex: 1,<br>        justifyContent: &#39;center&#39;,<br>        alignItems: &#39;center&#39;,<br>        padding: 20,<br>    },<br>});<br><br>export default ThemedComponent;</pre><p>In this example, ThemedComponent behaves similarly to the web example but uses View and Text components from React Native, and the styles are handled using StyleSheet.</p><h3>Code-Based Example: Using useContext for State Management</h3><p>In this example, we will be passing common values fetched from Example API among different component using useContext hook. This example assumes that our DataTables are populated with data from an API endpoint.</p><h4>Step 1: Setting Up the Context</h4><p>First, we will create a context that will hold the shared state (common values) between the two pages.</p><pre>import React, { createContext, useState, useEffect } from &#39;react&#39;;<br><br>// Create a context for the common values<br>export const DataTableContext = createContext();<br><br>export const DataTableProvider = ({ children }) =&gt; {<br>    const [commonValues, setCommonValues] = useState([]);<br><br>    // Fetch common values from an API (This API call can be customized)<br>    useEffect(() =&gt; {<br>        const fetchCommonValues = async () =&gt; {<br>            try {<br>                const response = await fetch(&#39;https://api.example.com/common-values&#39;);<br>                const data = await response.json();<br>                setCommonValues(data);<br>            } catch (error) {<br>                console.error(&#39;Failed to fetch common values&#39;, error);<br>            }<br>        };<br><br>        fetchCommonValues();<br>    }, []);<br><br>    return (<br>        &lt;DataTableContext.Provider value={{ commonValues, setCommonValues }}&gt;<br>            {children}<br>        &lt;/DataTableContext.Provider&gt;<br>    );<br>};</pre><p>In this DataTableProvider, the commonValues state is fetched from a hypothetical API (https://api.example.com/common-values) and stored in a context. This will allow both pages to access and utilize the same data.</p><h4>Step 2: Creating the DataTables</h4><p>Now, let’s create two pages, each with its DataTable component that consumes the shared commonValues from the context.</p><p><strong>Page 1: DataTable Component</strong></p><pre>import React, { useContext, useEffect, useState } from &#39;react&#39;;<br>import { DataTableContext } from &#39;./DataTableProvider&#39;;<br>import DataTable from &#39;react-data-table-component&#39;; // Assuming you&#39;re using a library like react-data-table-component<br><br>const DataTablePage1 = () =&gt; {<br>    const { commonValues } = useContext(DataTableContext);<br>    const [data, setData] = useState([]);<br><br>    // Fetch data for this DataTable<br>    useEffect(() =&gt; {<br>        const fetchData = async () =&gt; {<br>            try {<br>                const response = await fetch(&#39;https://api.example.com/data1&#39;);<br>                const data = await response.json();<br>                setData(data);<br>            } catch (error) {<br>                console.error(&#39;Failed to fetch data&#39;, error);<br>            }<br>        };<br><br>        fetchData();<br>    }, []);<br><br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;DataTable Page 1&lt;/h1&gt;<br>            &lt;DataTable<br>                columns={[ /* Define your columns here */ ]}<br>                data={data}<br>            /&gt;<br>            &lt;h3&gt;Common Values&lt;/h3&gt;<br>            &lt;ul&gt;<br>                {commonValues.map((value, index) =&gt; (<br>                    &lt;li key={index}&gt;{value}&lt;/li&gt;<br>                ))}<br>            &lt;/ul&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default DataTablePage1;</pre><p>In DataTablePage1, the table-specific data is fetched from another API (https://api.example.com/data1), and the common values are displayed below the table using the commonValues from the context.</p><p><strong>Page 2: DataTable Component</strong></p><pre>import React, { useContext, useEffect, useState } from &#39;react&#39;;<br>import { DataTableContext } from &#39;./DataTableProvider&#39;;<br>import DataTable from &#39;react-data-table-component&#39;;<br><br>const DataTablePage2 = () =&gt; {<br>    const { commonValues } = useContext(DataTableContext);<br>    const [data, setData] = useState([]);<br><br>    // Fetch data for this DataTable<br>    useEffect(() =&gt; {<br>        const fetchData = async () =&gt; {<br>            try {<br>                const response = await fetch(&#39;https://api.example.com/data2&#39;);<br>                const data = await response.json();<br>                setData(data);<br>            } catch (error) {<br>                console.error(&#39;Failed to fetch data&#39;, error);<br>            }<br>        };<br><br>        fetchData();<br>    }, []);<br><br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;DataTable Page 2&lt;/h1&gt;<br>            &lt;DataTable<br>                columns={[ /* Define your columns here */ ]}<br>                data={data}<br>            /&gt;<br>            &lt;h3&gt;Common Values&lt;/h3&gt;<br>            &lt;ul&gt;<br>                {commonValues.map((value, index) =&gt; (<br>                    &lt;li key={index}&gt;{value}&lt;/li&gt;<br>                ))}<br>            &lt;/ul&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default DataTablePage2;</pre><p>Similarly, DataTablePage2 fetches its own data from another API (https://api.example.com/data2) and displays the same commonValues under the table.</p><h3>Step 3: Integrating the Provider and Routing</h3><p>Finally, you’ll need to wrap your application with the DataTableProvider so that the context is available throughout your app.</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import { BrowserRouter as Router, Route, Switch } from &#39;react-router-dom&#39;;<br>import { DataTableProvider } from &#39;./DataTableProvider&#39;;<br>import DataTablePage1 from &#39;./DataTablePage1&#39;;<br>import DataTablePage2 from &#39;./DataTablePage2&#39;;<br><br>const App = () =&gt; {<br>    return (<br>        &lt;DataTableProvider&gt;<br>            &lt;Router&gt;<br>                &lt;Switch&gt;<br>                    &lt;Route path=&quot;/page1&quot; component={DataTablePage1} /&gt;<br>                    &lt;Route path=&quot;/page2&quot; component={DataTablePage2} /&gt;<br>                &lt;/Switch&gt;<br>            &lt;/Router&gt;<br>        &lt;/DataTableProvider&gt;<br>    );<br>};<br><br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&#39;root&#39;));</pre><p>In this setup, both DataTablePage1 and DataTablePage2 will have access to the commonValues provided by DataTableProvider, ensuring that the shared data is consistent across both pages.</p><p>This example shows how you can share common values between two different DataTables on separate pages using React’s useContext hook. By creating a context to hold the shared state, both pages can access the same data without the need for prop drilling or redundant API calls, leading to a more efficient and maintainable application.</p><h3>Conclusion</h3><p>The useContext hook is a powerful tool in React that simplifies state management across both web and mobile applications. By reducing the need for prop drilling and centralising state, useContext helps keep your components clean, maintainable, and easy to work with. Whether you&#39;re dealing with themes, authentication, localisation, or complex state, useContext is an essential part of the modern React developer&#39;s toolkit.</p><blockquote>If you found this content helpful and informative, I would greatly appreciate your support by following my profile. By following, you can stay updated with my future articles and gain more valuable insights into Salesforce &amp; Web development and other related topics. Your support means a lot to me, and I look forward to sharing more useful content with you in the future. Thank you for your time and consideration!</blockquote><p>If you enjoyed what you read &amp; found it insightful, please consider supporting me <a href="https://buymeacoffee.com/atuljha24"><strong>here</strong> Your support is greatly appreciated!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e11c831ff714" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Develop Mobile App with Bluetooth functionality — React Native]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@atuljha2402/develop-mobile-app-with-bluetooth-functionality-react-native-d6028c827935?source=rss-d100b49c8be3------2"><img src="https://cdn-images-1.medium.com/max/1920/1*HEVqMXasu5V3abHjTc8rVQ.png" width="1920"></a></p><p class="medium-feed-snippet">react-native-ble-manager a popular library for managing Bluetooth Low Energy (BLE) connections in React Native applications. The library&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@atuljha2402/develop-mobile-app-with-bluetooth-functionality-react-native-d6028c827935?source=rss-d100b49c8be3------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@atuljha2402/develop-mobile-app-with-bluetooth-functionality-react-native-d6028c827935?source=rss-d100b49c8be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6028c827935</guid>
            <category><![CDATA[bluetooth]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[react-native-ble-manager]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Atul jha]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 06:00:00 GMT</pubDate>
            <atom:updated>2024-09-01T11:14:39.610Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Change data capture: CDC in Salesforce using Postman]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@atuljha2402/change-data-capture-cdc-in-salesforce-using-postman-a437871fb2ae?source=rss-d100b49c8be3------2"><img src="https://cdn-images-1.medium.com/max/1920/1*sWp2RT13IkYcNzwCTM3-_A.png" width="1920"></a></p><p class="medium-feed-snippet">In this article we will understand how to implement CDC with Postman, a popular API platform.</p><p class="medium-feed-link"><a href="https://medium.com/@atuljha2402/change-data-capture-cdc-in-salesforce-using-postman-a437871fb2ae?source=rss-d100b49c8be3------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@atuljha2402/change-data-capture-cdc-in-salesforce-using-postman-a437871fb2ae?source=rss-d100b49c8be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a437871fb2ae</guid>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[postman]]></category>
            <dc:creator><![CDATA[Atul jha]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 11:17:03 GMT</pubDate>
            <atom:updated>2024-08-18T05:26:46.335Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Accessibility in Salesforce: Object level secu]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@atuljha2402/accessibility-in-salesforce-object-level-secu-fd0ae58ca3a2?source=rss-d100b49c8be3------2"><img src="https://cdn-images-1.medium.com/max/1920/1*8kQlYekv9USMdy8ucOqURQ.png" width="1920"></a></p><p class="medium-feed-snippet">Salesforce&#x2019;s Sharing architecture forms the foundation of ensuring that the right people have access to the required data. Just imagine&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@atuljha2402/accessibility-in-salesforce-object-level-secu-fd0ae58ca3a2?source=rss-d100b49c8be3------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@atuljha2402/accessibility-in-salesforce-object-level-secu-fd0ae58ca3a2?source=rss-d100b49c8be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd0ae58ca3a2</guid>
            <category><![CDATA[permission-set]]></category>
            <category><![CDATA[cred]]></category>
            <category><![CDATA[profile]]></category>
            <category><![CDATA[salesforce-object]]></category>
            <category><![CDATA[record-type]]></category>
            <dc:creator><![CDATA[Atul jha]]></dc:creator>
            <pubDate>Sun, 14 Jan 2024 17:32:47 GMT</pubDate>
            <atom:updated>2024-08-18T05:27:23.339Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Unlocking the Future: Blockchain Technology and the Emergence of Web3]]></title>
            <link>https://medium.com/@atuljha2402/unlocking-the-future-blockchain-technology-and-the-emergence-of-web3-48c0d75efe71?source=rss-d100b49c8be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/48c0d75efe71</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[consensus-mechanism]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[decentralized]]></category>
            <dc:creator><![CDATA[Atul jha]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 20:36:01 GMT</pubDate>
            <atom:updated>2024-08-18T05:27:54.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TapSFor9K0u-NCHgzZMPKw.png" /></figure><p>Since decades the internet or world of web has gone through various advancement, each of which has seen a substantial shift in the ways that we use and interact with it.<strong> The first version of the internet, referred to as Web1 or the “static web,” debuted in the 1990s</strong>. It was essentially used for information exchange and communication via email and early chat rooms. It was a collection of static web pages connected by hyperlinks.</p><p><strong>The emergence of Web2, commonly referred to as the “social web,” in the early 2000s was marked by the growth of cloud computing, e-commerce, and social media.</strong> Web2 allows users to create and share content, engage with others, and do business online. It was more interactive and user-driven than Web1.</p><p><strong>At present, Web3 is settling into our lives &amp; revolutionizing the world of web using blockchain technology.</strong> Web3 is focused on introducing decentralization, ownership of data &amp; assets, smart contracts, tokenization and cryptocurrencies, with the goal of creating a more open and autonomous internet free of administrative control. Web3 provides users with increased privacy, security, and autonomy while also encouraging innovation and collaboration among social communities, developers and entrepreneurs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGdV67l47rG8Z-PRtEHeQw.png" /></figure><h3><strong>What is blockchain?</strong></h3><p>Blockchain is a self-defining word which means “<strong>Blocks of digital databases or ledgers which are shared among computer network node’s</strong>”. Most of us got to know about blockchain due to the rise of cryptocurrencies as blockchain plays a very crucial role in maintaining decentralized record of transactions, but it is not just limited to crypto uses. It can be used in any industry to make any form of data immutable by using its fundamental features such as cryptographic hashing techniques &amp; decentralized nature of the network.</p><h4>Why blocks of data cannot be accessed by any third party?</h4><p>The immutability of data in a blockchain is one of its fundamental features ensured by cryptographic techniques such as hashing &amp; linking of blocks and the decentralized nature of the network. Once a block of data is added to the blockchain, it becomes next to impossible for any unauthorized person to make changes in the information within that block.</p><h4>Let’s dive into the key features of blockchain which makes our data immutable:</h4><p><strong>Cryptographic hashing:</strong> Each block in a blockchain contains a cryptographic hash, a unique and fixed-length string of characters generated using a hashing algorithm. The hash is like a digital fingerprint for the block. <br>Any change in the data within the block would result in a completely different hash. Even a small modification in the input data would produce a significantly different hash output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*Cb5XSWE0YFBeHpQYLRlukg.png" /></figure><p>Since each block contains the hash of the previous block, any change in a block would necessitate changing the hash of all subsequent blocks, creating a domino effect throughout the entire chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpgahPdP3lFOU_oXYttilg.gif" /></figure><p><strong>Linking of Blocks:</strong> Blocks in a blockchain are linked together through the cryptographic hash of the previous block. This linking ensures the privacy &amp; security of the entire chain.</p><p>If a malicious developer attempts to alter the data in a block, they would need to recalculate the hash of that block and all subsequent blocks. This task becomes computationally infeasible due to the complexity of cryptographic hashing algorithms.</p><p><strong>Decentralized Consensus:</strong> Blockchain operates on a decentralized network of nodes (computers) that participate in the validation and consensus process.</p><p><strong>A consensus mechanism is a set of rules or protocols that govern how participants in a distributed network agree on the validity of transactions and the state of the system.</strong></p><p>Consensus mechanism includes Proof of Work (miners solve puzzles for rewards), Proof of Stake (validators create blocks based on staked cryptocurrency), DPoS (elected delegates validate), PoA (known validators), PBFT (nodes agree on transactions), and Raft Consensus (simple, fault-tolerant). <strong>Basically consensus mechanism work on the principle of “Sabka saath, Sabka vikas”</strong>. They ensure trust and security in decentralized systems like blockchain. Choice depends on network goals, desired decentralization, and application requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XjfiCb0_2VkQ8xTh3MSXw.png" /><figcaption><strong>Basically consensus mechanism work on the principle of “Sabka saath, Sabka vikas”</strong></figcaption></figure><p><strong>Tamper-Resistant Design:</strong> The decentralized and distributed nature of a blockchain ensures that <strong>no single entity has control over the entire network. This prevents a central point of vulnerability.</strong></p><p>Even if a node is compromised or a few nodes are malicious, the majority of the network’s uncompromised nodes will reject any attempts to alter the data, maintaining the integrity of the blockchain.</p><p><strong>Above mentioned feature of blockchain contributes to immutability of data in a blockchain &amp; this makes it exceptionally secure against unauthorized modification by third parties. Also we can simply say that blockchain is a part of the world of web3 for ensuring autonomous &amp; private behavior.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mwl2seIqMo2enxsLHDSSQ.png" /></figure><h3><strong>Let’s explore use cases of web 3:</strong></h3><p>As we know web3 is the future of the internet so its use cases consist of all types of current as well as futuristic applications for making our lives simple &amp; efficient. Obviously its not possible to explore every aspect of web3 so we will see some of the most popular use cases of web3:</p><h4><strong>Lets begin with social media:</strong></h4><p>Web3 social media platforms prioritize decentralization, granting users enhanced privacy and data control. It will foster a user-centric environment that contrasts with traditional social media platforms. In simpler words, you are the owner of your own data &amp; no unauthorized person will have access to your data for any purpose.</p><h4><strong>Gaming:</strong></h4><p>Web3 is transforming the world of gaming by making it more secure, transparent, decentralized &amp; gamer-centric. Blockchain integration will allow players to own the game assets, facilitating trade and opening new ways for monetization and engagement which will provide them better opportunities</p><h4><strong>Identity management:</strong></h4><p>Web3 introduces secure and decentralized identity management systems. Users have control over their identity data, granting access on a need-to-know basis. This will not only prevent identity related data breaches but also provides users with full control over their data.</p><h4><strong>Decentralized finance(DeFi):</strong></h4><p>Decentralization is a core principle of Web3. It leverages blockchain technology to create distributed networks where no single entity has full control. Web3 revolutionizes finance with DeFi, enabling peer-to-peer transactions without intermediaries. Lending platforms, decentralized exchanges, and prediction markets thrive, providing financial services accessible to anyone. And the best example of De-Fi is cryptocurrencies.</p><h4><strong>Non-Fungible Tokens (NFTs):</strong></h4><p>NFTs are unique digital assets stored on the blockchain based platforms which redefines ownership of the digital assets in digital realms. From digital art to in-game items, NFTs empower creators to monetize their work while offering collectors truly distinctive digital possessions.</p><h3><strong>Conclusion</strong></h3><p>In summary, the evolution of the world of web has witnessed various transformative phases from web1 to futuristic web3 with blockchain technology. And by going through the features of web3 &amp; blockchain we know that web3 is here to stay. The immutability is deeply rooted in blockchain due to cryptographic hashing, linking of blocks &amp; decentralized consensus. Tamper-resistant design ensures data security, making it exceptionally secure against unauthorized modifications.</p><p>Web3 holds the potential to revolutionize the web industry by enhanced privacy, and great opportunities for collaborations. This secure and transparent nature of blockchain ensures that users remain in control of their digital lives. Web3 use cases contribute to building a more equitable and sustainable digital future for the world.</p><blockquote><em>If you found this content helpful and informative, I would greatly appreciate your support by following my profile. By following, you can stay updated with my future articles and gain more valuable insights into Web development and other related topics. Your support means a lot to me, and I look forward to sharing more useful content with you in the future. Thank you for your time and consideration!</em></blockquote><p>If you enjoyed what you read &amp; found it insightful, please consider supporting me <a href="https://buymeacoffee.com/atuljha24"><strong>here</strong> Your support is greatly appreciated!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48c0d75efe71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Array Encyclopedia: Exploring Built-in Methods]]></title>
            <link>https://medium.com/@atuljha2402/the-array-encyclopedia-exploring-built-in-methods-c9562d4052ca?source=rss-d100b49c8be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9562d4052ca</guid>
            <category><![CDATA[slice]]></category>
            <category><![CDATA[push]]></category>
            <category><![CDATA[pop]]></category>
            <category><![CDATA[built-in-methods]]></category>
            <category><![CDATA[length]]></category>
            <dc:creator><![CDATA[Atul jha]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 20:16:30 GMT</pubDate>
            <atom:updated>2024-08-18T05:28:32.434Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Array Builtin Methods</h3><p>Welcome to “The Array Encyclopedia: Exploring Built-in Methods”! In this blog, we will dive into the concepts of various built-in methods of Array. Together, we will understand the power and versatility of array built-in methods, equipping you with the knowledge and skills to manipulate arrays with ease and efficiency. <strong>Get ready to unlock the full potential of arrays as we understand each methods, providing clear explanations, practical examples, and valuable insights to equip you with the skills to navigate arrays like a seasoned pro.</strong></p><p>In this blog, we will focus solely on understanding “Built-in Methods.” For a comprehensive grasp of the basics of arrays in JavaScript, please refer to the blog titled “<a href="https://medium.com/@atuljha2402/lets-learn-basics-of-array-using-javascript-d5ae3be58c84">Let’s Learn Basics of Array Using JavaScript.</a>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6JDbn4AjBK3wGFvPfH31g.png" /></figure><h3>Lets start with some commonly used Array built-in methods:</h3><h4>- isArray()</h4><p>The isArray() method is a built-in function of array that checks whether a given value is an array or not. It returns true if the value is an array, and false if it is not.</p><p>isArray() is helpful when you need to ensure that a variable is an array before performing array-specific operations on it. It prevents potential errors that might occur if you try to use array methods on a non-array value.</p><p>Suppose you are building a function to process data that comes from various sources, and you expect an array as input. Before proceeding with the data processing, you can use isArray() to validate if the input data is an array to ensure smooth execution of your logic.</p><p><strong>Syntax: </strong>Array.isArray(value)</p><p><strong>Example-</strong></p><pre>const array1 = [1, 2, 3];<br>const value = 42;<br><br>console.log(Array.isArray(array1)); // Output: true<br>console.log(Array.isArray(value));  // Output: false</pre><p><strong>Explanation:</strong> In the example, Array.isArray(array1) returns true because array1 is an array, while Array.isArray(value) returns false since value is not an array.</p><h4>- fill()</h4><p>The fill() method is used to fill all the elements of an array with a static value. It modifies the original array and returns the modified array. The fill() method is useful when you want to initialize an array with a specific value or update all elements of an array to a common value.</p><p>Suppose you are creating a game where you have a game board represented by a 2D array. You can use fill() to initialize the board with empty cells at the beginning of each game.</p><p><strong>Syntax:</strong> array.fill(value, start, end)</p><ul><li>value: The value to fill the array with.</li><li>start (optional): The index to start filling the array (default is 0).</li><li>end (optional): The index to stop filling the array (default is array.length).</li></ul><p><strong>Example:</strong></p><pre>const array1 = [1, 2, 3, 4, 5];<br><br>console.log(array1.fill(0)); // Output: [0, 0, 0, 0, 0]<br>console.log(array1.fill(9, 2, 4)); // Output: [0, 0, 9, 9, 0]</pre><p><strong>Explanation</strong>: In the first example, array1.fill(0) sets all elements of array1 to 0. In the second example, array1.fill(9, 2, 4) sets the elements at index 2 and 3 to 9, leaving the rest unchanged.</p><h4>- flat()</h4><p>The flat() method is used to create a new array that is a flattened version of the original array. It recursively flattens nested arrays to a specified depth. <br><strong>Note:</strong> Depth means the number of time you want to repeat the process.</p><p>The flat() method is handy when working with arrays containing multiple nested arrays. It allows you to create a single-level array, simplifying data processing and iteration.</p><p><strong>Syntax</strong>: array.flat(depth)</p><p><strong>Example:</strong></p><pre>const array1 = [1, 2, [3, 4, [5, 6]]];<br><br>console.log(array1.flat()); // Output: [1, 2, 3, 4, [5, 6]]<br>console.log(array1.flat(2)); // Output: [1, 2, 3, 4, 5, 6]</pre><p><strong>Explanation: </strong>In the first example, array1.flat() flattens the array to one level, but it does not flatten nested arrays beyond that. In the second example, array1.flat(2) flattens the array to a depth of 2, resulting in a fully flattened array.</p><h4>- reverse()</h4><p>The reverse() method is used to reverse the order of elements in an array. It modifies the original array and returns the modified array. The reverse() method is helpful when you need to change the order of elements in an array to process them in a different direction.</p><p>Consider a quiz application where you have an array of questions. Using reverse(), you can change the order of questions to present them in reverse, creating a fun challenge for users.</p><p><strong>Syntax:</strong> array.reverse()</p><p><strong>Example:</strong></p><pre>const array1 = [1, 2, 3, 4, 5];<br><br>console.log(array1.reverse()); // Output: [5, 4, 3, 2, 1]</pre><p><strong>Explanation</strong>: In this example, the reverse() method reverses the order of elements in array1.</p><h4>- sort()</h4><p>The sort() method is used to sort the elements of an array in place and return the sorted array. By default, it sorts elements as strings. The sort() method is crucial when you want to arrange the elements of an array in a particular order, allowing you to perform operations on sorted data.</p><p>Imagine you have an array of student scores, and you want to rank them from the highest to lowest. You can use sort() to organize the scores in descending order.</p><p><strong>Syntax</strong>: array.sort(compareFunction)</p><ul><li>compareFunction (optional): The function that defines the sort order. It takes two arguments (a and b) and returns a negative value if a should come before b, a positive value if a should come after b, or 0 if they are equal.</li></ul><p><strong>Example</strong>:</p><pre>const fruits = [&#39;banana&#39;, &#39;apple&#39;, &#39;orange&#39;, &#39;grapes&#39;];<br>fruits.sort();<br>console.log(fruits); // Output: [&#39;apple&#39;, &#39;banana&#39;, &#39;grapes&#39;, &#39;orange&#39;]</pre><h4>- length</h4><p>The length property of an array represents the number of elements in that array. The length property is used to determine the size of an array. It is automatically updated when elements are added or removed from the array using methods like push(), pop(), shift(), or splice().</p><p>In various scenarios, you might use the length property to check the size of an array before iterating over its elements or to perform certain operations when the array reaches a specific size.</p><p><strong>Syntax</strong>: array.length</p><p><strong>Example:</strong></p><pre>const fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];<br>console.log(fruits.length); // Output: 3<br><br>fruits.push(&#39;grapes&#39;);<br>console.log(fruits.length); // Output: 4<br><br>fruits.pop();<br>console.log(fruits.length); // Output: 3</pre><p><strong>Explanation: </strong>An array fruits is initialized with three elements: ‘apple’, ‘banana’, and ‘orange’. When we use fruits.push(‘grapes’), it adds ‘grapes’ to the end of the array, increasing its length to 4. Subsequently, fruits.pop() removes the last element (‘grapes’) from the array, reducing its length back to 3. The fruits.length property reflects the number of elements in the array at each stage of modification.</p><p><strong>Now lets dive into another niches of array inbuilt methods.</strong></p><h3>Array methods for Adding/Removing Elements:</h3><h4>- push()</h4><p>The push() method adds one or more elements to the end of an array and returns the new length of the array. It is a simple and efficient way to add new elements to an array.</p><p>Imagine you have an online shopping cart, and you want to add new items to the cart when users click the “Add to Cart” button.</p><p><strong>Syntax</strong>: array.push(element1, element2, …, elementN)</p><p><strong>Example:</strong></p><pre>const fruits = [&#39;apple&#39;, &#39;banana&#39;];<br>const newLength = fruits.push(&#39;orange&#39;, &#39;grapes&#39;);<br><br>console.log(fruits); // Output: [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;, &#39;grapes&#39;]<br>console.log(newLength); // Output: 4</pre><h4>- pop()</h4><p>The pop() method removes the last element from an array and returns that element. It helps in efficiently removing elements from the end of the array.</p><p>In a to-do list application, you might use pop() to remove the last task from the list when the user clicks the &quot;Completed&quot; button.</p><p><strong>Syntax: </strong>array.pop()</p><p><strong>Example:</strong></p><pre>const fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];<br>const removedFruit = fruits.pop();<br><br>console.log(fruits); // Output: [&#39;apple&#39;, &#39;banana&#39;]<br>console.log(removedFruit); // Output: &#39;orange&#39;</pre><h4>- shift()</h4><p>The shift() method is used to remove the first element from an array. It is commonly used when you want to remove the first item from the array and shift all other elements one position down.</p><p>Imagine a queue of people waiting to buy movie tickets. The first person to enter the queue will be the first to get the ticket. Similarly, shift() can be used to model a queue data structure.</p><p><strong>Syntax</strong>: array.shift()</p><p><strong>Example:</strong></p><pre>let fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];<br>let firstFruit = fruits.shift();<br>console.log(firstFruit); // Output: &#39;apple&#39;<br>console.log(fruits); // Output: [&#39;banana&#39;, &#39;orange&#39;]</pre><p><strong>Explanation</strong>: This code demonstrates the use of the shift() method in JavaScript arrays. The shift() method removes the first element from the fruits array and returns that removed element. In this case, &#39;apple&#39; is the first element of the fruits array, so it is removed and assigned to the variable firstFruit. After the shift() operation, the fruits array now contains only &#39;banana&#39; and &#39;orange&#39;. The console.log statements display the removed element (&#39;apple&#39;) and the updated array [&#39;banana&#39;, &#39;orange&#39;].</p><h4>- unshift()</h4><p>The unshift() method is used to add one or more elements to the beginning of an array. It is commonly used when you want to add elements to the start of the array, shifting the existing elements to higher indices.</p><p>Imagine a list of tasks that need to be done. When a new task is added, it usually becomes the first one to be completed. unshift() can be used to model this behavior.</p><p><strong>Syntax</strong>: array.unshift(element1, element2, ..., elementN)</p><p><strong>Example:</strong></p><pre>let tasks = [&#39;Task 1&#39;, &#39;Task 2&#39;, &#39;Task 3&#39;];<br>tasks.unshift(&#39;New Task&#39;);<br>console.log(tasks); // Output: [&#39;New Task&#39;, &#39;Task 1&#39;, &#39;Task 2&#39;, &#39;Task 3&#39;]</pre><p><strong>Explanation</strong>: The unshift() method adds one or more elements to the beginning of an array. In this case, &#39;New Task&#39; is added to the beginning of the tasks array, shifting the existing elements to the right. After the unshift() operation, the tasks array becomes [&#39;New Task&#39;, &#39;Task 1&#39;, &#39;Task 2&#39;, &#39;Task 3&#39;], as shown in the console.log output.</p><h4>- splice()</h4><p>The splice() method is used to add or remove elements from an array at a specific index. It is commonly used when you want to insert new elements at a specific position or remove elements from a particular position in the array.</p><p>Imagine a list of students in a class, and you want to add a new student in the middle of the list or remove a student who dropped out. splice() can be used to accomplish this.</p><p><strong>Syntax (adding)</strong>: array.splice(startIndex, deleteCount, element1, element2, ..., elementN)</p><p><strong>Example of adding:</strong></p><pre>let numbers = [1, 2, 3, 7, 8];<br>numbers.splice(3, 0, 4, 5, 6);<br>console.log(numbers); // Output: [1, 2, 3, 4, 5, 6, 7, 8]</pre><p><strong>Explanation: </strong>The splice() method allows us to modify an array by adding, removing, or replacing elements. In this case, it starts at index 3 (3rd position) in the numbers array and removes zero elements (0), then adds the elements 4, 5, and 6 at that position. The console.log output displays the updated numbers array: [1, 2, 3, 4, 5, 6, 7, 8].</p><p><strong>Syntax (removing)</strong>: array.splice(startIndex, deleteCount)</p><p><strong>Example of removing:</strong></p><pre>let animals = [&#39;dog&#39;, &#39;cat&#39;, &#39;elephant&#39;, &#39;giraffe&#39;, &#39;monkey&#39;];<br>animals.splice(2, 2);<br>console.log(animals); // Output: [&#39;dog&#39;, &#39;cat&#39;, &#39;monkey&#39;]</pre><p><strong>Explanation</strong>: The splice() method allows us to modify an array by adding, removing, or replacing elements. In this case, it starts at index 2 (3rd position) in the animals array and removes two elements. The elements &#39;elephant&#39; and &#39;giraffe&#39; are removed from the array, resulting in the animals array being updated to [&#39;dog&#39;, &#39;cat&#39;, &#39;monkey&#39;]. The console.log output displays the updated animals array.</p><h3>Array methods for combining arrays:</h3><h4>- concat()</h4><p>The concat() method is used to combine two or more arrays, creating a new array without modifying the existing arrays. It is commonly used when you want to merge multiple arrays together without altering the original arrays.</p><p>Suppose you have two separate lists of items, and you want to create a single list containing all items from both lists. concat() can be used to achieve this.</p><p><strong>Syntax</strong>: array.concat(array1, array2, ..., arrayN)</p><p><strong>Example:</strong></p><pre>let arr1 = [1, 2, 3];<br>let arr2 = [4, 5, 6];<br>let combinedArray = arr1.concat(arr2);<br>console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]</pre><h3>Array methods for Extracting elements:</h3><h4>- slice()</h4><p>The slice() method is used to extract a portion of an array and return it as a new array, without modifying the original array. It is commonly used when you want to create a new array containing elements from a specific range in the original array.</p><p>Consider a playlist of songs, and you want to create a new playlist with only a selection of songs based on their positions. slice() can be used to make a new playlist without altering the original one.</p><p><strong>Syntax</strong>: array.slice(startIndex, endIndex)</p><p><strong>Example:</strong></p><pre>let playlist = [&#39;song1&#39;, &#39;song2&#39;, &#39;song3&#39;, &#39;song4&#39;, &#39;song5&#39;];<br>let selectedSongs = playlist.slice(1, 4);<br>console.log(selectedSongs); // Output: [&#39;song2&#39;, &#39;song3&#39;, &#39;song4&#39;]</pre><p><strong>Explanation</strong>: The slice() method extracts a section of an array and returns a new array containing the selected elements. In this case, it starts at index 1 (2nd position) and goes up to, but does not include, index 4 (5th position) in the playlist array. Therefore, it extracts the elements &#39;song2&#39;, &#39;song3&#39;, and &#39;song4&#39; from the playlist, creating a new array called selectedSongs. The console.log output displays the new array [&#39;song2&#39;, &#39;song3&#39;, &#39;song4&#39;]. The original playlist array remains unchanged.</p><h3>Array methods for Searching elements:</h3><h4>- indexOf()</h4><p>The indexOf() method is used to find the first occurrence of a specific element in an array and returns its index. If the element is not found, it returns -1. It is commonly used when you want to know the position of an element in the array.</p><p>Imagine you have a list of products in a store, and a customer asks for a particular product. You can use indexOf() to find the product&#39;s position in the list.</p><p><strong>Syntax</strong>: array.indexOf(element, startIndex)</p><p><strong>Example:</strong></p><pre>let fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;, &#39;apple&#39;, &#39;grapes&#39;];<br>let position = fruits.indexOf(&#39;apple&#39;);<br>console.log(position); // Output: 0</pre><h4>- lastIndexOf()</h4><p>The lastIndexOf() method is used to find the last occurrence of a specific element in an array and returns its index. If the element is not found, it returns -1. It is commonly used when you want to find the position of the last occurrence of an element in the array.</p><p>Consider a chat conversation where you want to find the last message sent by a specific user. lastIndexOf() can be used to locate the last message in the array of messages from that user.</p><p><strong>Syntax</strong>: array.lastIndexOf(element, startIndex)</p><p><strong>Example:</strong></p><pre>let messages = [&#39;Hi&#39;, &#39;Hello&#39;, &#39;How are you?&#39;, &#39;Hi&#39;];<br>let lastIndex = messages.lastIndexOf(&#39;Hi&#39;);<br>console.log(lastIndex); // Output: 3</pre><p><strong>Example: </strong>This code uses the lastIndexOf() method in JavaScript arrays. The lastIndexOf() method returns the index of the last occurrence of a specified element in an array. In this case, it searches for the element &#39;Hi&#39; in the messages array and finds it at the index 3 (last occurrence). The lastIndex variable is assigned the value 3, which is then displayed using console.log(). If the element is not found in the array, the method returns -1.</p><h4>- includes()</h4><p>The includes() method is used to check if an array contains a specific element. It returns a boolean value (true or false). It is commonly used when you want to determine whether an array includes a particular element or not.</p><p>Think of a membership list for a club event. You can use includes() to check if a person&#39;s name is on the list to confirm their attendance.</p><p><strong>Syntax</strong>: array.includes(element, startIndex)</p><p><strong>Example:</strong></p><pre>let numbers = [1, 2, 3, 4, 5];<br>let hasThree = numbers.includes(3);<br>console.log(hasThree); // Output: true</pre><h4>- find()</h4><p>The find() method is used to find the first element in an array that satisfies a provided testing function. It returns the value of the first element that matches the condition, otherwise, it returns undefined. It is commonly used when you want to search for a specific element in the array based on a certain condition.</p><p>Consider an array of products, and you want to find the first product that is currently on sale. find() can be used to locate the first product with a sale price.</p><p><strong>Syntax</strong>: array.find(callback(element, index, array))</p><p><strong>Example:</strong></p><pre>let products = [<br>  { name: &#39;Shirt&#39;, price: 20 },<br>  { name: &#39;Pants&#39;, price: 30 },<br>  { name: &#39;Shoes&#39;, price: 50 },<br>];<br><br>let onSaleProduct = products.find((product) =&gt; product.price &lt; 40);<br>console.log(onSaleProduct); // Output: { name: &#39;Shirt&#39;, price: 20 }</pre><p><strong>Explanation</strong>: The find() method is used to search for the first element in an array that satisfies a given condition specified by the provided callback function. In this case, it searches the products array and returns the first product that has a price less than 40. The callback function checks each product&#39;s price, and it finds the first product, which is a shirt with a price of 20, satisfying the condition. The onSaleProduct variable is assigned the matching product object, which is then displayed using console.log().</p><h4>- findIndex()</h4><p>The findIndex() method is similar to find(), but it returns the index of the first element that satisfies the provided testing function. If no element matches the condition, it returns -1. It is commonly used when you want to find the index of the first element that satisfies a specific condition.</p><p>Think of a list of students’ test scores, and you want to find the index of the first student who scored above 90. findIndex() can be used to find the position of that student&#39;s score in the array.</p><p><strong>Syntax</strong>: array.findIndex(callback(element, index, array))</p><p><strong>Example</strong>:</p><pre>let scores = [85, 92, 78, 95, 88];<br>let above90Index = scores.findIndex((score) =&gt; score &gt;90);<br>console.log(above90Index); // Output: 1</pre><p>In this example, it searches the scores array and returns the index of the first element that is greater than 90. The callback function checks each score, and it finds that the score of 92 is the first one greater than 90, and its index is 1. The above90Index variable is assigned the value 1, which is then displayed using console.log(). If no element satisfies the condition, the method returns -1.</p><h3>Array methods for Iterating over elements:</h3><h4>- forEach()</h4><p>The forEach() method is used to iterate over each element in an array and execute a provided callback function for each element. It is commonly used when you want to perform an action on each element of the array, such as printing its value or updating it in some way.</p><p>Consider a list of students’ names, and you want to greet each student individually. forEach() can be used to loop through the array and greet each student.</p><p><strong>Syntax</strong>: array.forEach(callback(element, index, array))</p><p><strong>Example:</strong></p><pre>let students = [&#39;Atul&#39;, &#39;Meenal&#39;, &#39;Animesh&#39;];<br>students.forEach((student) =&gt; {<br>  console.log(`Hello, ${student}!`);<br>});<br><br>// Output: <br>// Hello, Atul<br>// Hello, Meenal<br>// Hello, Animesh</pre><h4>- map()</h4><p>The map() method is used to create a new array by applying a provided callback function to each element of the original array. It is commonly used when you want to transform the elements of an array and create a new array with the transformed values.</p><p>The main purpose of .map() is to transform each element of the array according to the logic defined in the callback function and collect the results in a new array of the same length. The original array remains unchanged.</p><p>Imagine a list of prices, and you want to apply a discount to each price. map() can be used to create a new array with the discounted prices.</p><p><strong>Syntax</strong>: array.map(callback(element, index, array))</p><p><strong>Example:</strong></p><pre>let prices = [20, 30, 50];<br>let discountedPrices = prices.map((price) =&gt; price * 0.9);<br>console.log(discountedPrices); // Output: [18, 27, 45]</pre><h4>- filter()</h4><p>The filter() method is used to create a new array containing elements from the original array that satisfy a provided testing function. It is commonly used when you want to filter out elements from the array based on a certain condition.</p><p>Consider a list of products, and you want to create a new list with only the products that are currently in stock. filter() can be used to generate the filtered list.</p><p><strong>Syntax</strong>: array.filter(callback(element, index, array))</p><p><strong>Example:</strong></p><pre>let products = [<br>  { name: &#39;Shirt&#39;, inStock: true },<br>  { name: &#39;Pants&#39;, inStock: false },<br>  { name: &#39;Shoes&#39;, inStock: true },<br>];<br><br>let inStockProducts = products.filter((product) =&gt; product.inStock);<br>console.log(inStockProducts);<br>// Output: [{ name: &#39;Shirt&#39;, inStock: true }, { name: &#39;Shoes&#39;, inStock: true }]</pre><h3>Array methods for checking elements:</h3><h4>- every()</h4><p>The every() method is used to check if all elements in an array satisfy a provided testing function. It returns a boolean value (true or false). It is commonly used when you want to determine whether all elements in the array meet a certain condition.</p><p>Think of a task management app, and you want to check if all tasks are completed before marking the entire project as finished. every() can be used to perform this check.</p><p><strong>Syntax</strong>: array.every(callback(element, index, array))</p><p><strong>Example:</strong></p><pre>let tasks = [<br>  { description: &#39;Task 1&#39;, completed: true },<br>  { description: &#39;Task 2&#39;, completed: false },<br>  { description: &#39;Task 3&#39;, completed: true },<br>];<br><br>let allTasksCompleted = tasks.every((task) =&gt; task.completed);<br>console.log(allTasksCompleted); // Output: false</pre><p><strong>Explanation</strong>: The every() method checks if all elements of an array satisfy a given condition specified by the provided callback function. In this case, it checks if all tasks in the tasks array have their completed property set to true.</p><p>The every() method returns true if all elements meet the condition, and false if at least one element fails the condition. In this example, the completed property of the second task is false, so the allTasksCompleted variable is assigned false, which is then displayed using console.log().</p><h4>- some()</h4><p>The some() method is used to check if at least one element in an array satisfies a provided testing function. It returns a boolean value (true or false). It is commonly used when you want to check if at least one element in the array meets a certain condition.</p><p>Consider a quiz application, and you want to check if the user answered at least one question correctly to allow them to proceed. some() can be used to make this determination.</p><p><strong>Syntax</strong>: array.some(callback(element, index, array))</p><p><strong>Example:</strong></p><pre>let quizScores = [80, 70, 95, 60];<br>let passedQuiz = quizScores.some((score) =&gt; score &gt;= 80);<br>console.log(passedQuiz); // Output: true</pre><p><strong>Explanation: </strong>The some() method checks if at least one element in the array satisfies a given condition specified by the provided callback function. In this case, it checks if there is any quiz score in the quizScores array that is greater than or equal to 80.</p><p>The some() method returns true if at least one element meets the condition, and false if none of the elements satisfy the condition. In this example, there is a score of 80 and 95, which are greater than or equal to 80, so the passedQuiz variable is assigned true, which is then displayed using console.log().</p><h3>Array methods for reducing elements:</h3><h4>- reduce()</h4><p>The reduce() method is used to reduce an array to a single value by applying a provided callback function to each element successively. It is commonly used when you want to perform a cumulative operation on the elements of the array, such as summing them up or finding the maximum value.</p><p>Imagine you have a list of expenses, and you want to calculate the total expenditure for a month. reduce() can be used to sum up all the expenses to get the total.</p><p><strong>Syntax</strong>: array.reduce(callback(accumulator, element, index, array), initialValue)</p><p><strong>Example:</strong></p><pre>let expenses = [100, 50, 80, 30];<br>let totalExpense = expenses.reduce((total, expense) =&gt; total + expense, 0);<br>console.log(totalExpense); // Output: 260</pre><p><strong>Explanation: </strong>The reduce() method is used to accumulate a single value by applying a callback function to each element of the array. It takes two arguments: the callback function and an initial value for the accumulator (here, 0 is provided).</p><p>In this example, the reduce() method adds each expense in the expenses array to the total accumulator. The initial value of total is 0, and the callback function total + expense is applied to each element. The result is the total sum of all the expenses in the array, which is 260. The totalExpense variable is assigned this value and then displayed using console.log().</p><h4>- reduceRight()</h4><p>The reduceRight() method is similar to reduce(), but it starts from the last element and accumulates towards the first element in the array. It is commonly used when you want to perform a cumulative operation from right to left on the elements of the array.</p><p>Consider a string of characters representing a mathematical expression, and you want to evaluate it from right to left. reduceRight() can be used to perform this evaluation.</p><p><strong>Syntax</strong>: array.reduceRight(callback(accumulator, element, index, array), initialValue)</p><p><strong>Example:</strong></p><pre>let words = [&#39;world&#39;, &#39;hello&#39;, &#39;nice&#39;, &#39;have&#39;, &#39;I&#39;];<br>let reversedSentence = words.reduceRight((accumulator, current) =&gt; {<br>  return `${accumulator} ${current}`;<br>});<br>console.log(reversedSentence); // Output: &#39;I have nice hello world&#39;</pre><p><strong>Explanation: </strong>In this example, we have an array words containing a list of strings. The reduceRight() method is applied to the array, starting from the rightmost element (&#39;I&#39;). The callback function takes two arguments, accumulator and current, where accumulator initially holds the value of the last element (&#39;I&#39;) and current is the element before it (&#39;have&#39;). The function concatenates the current element to the accumulator with a space in between and returns the updated value.</p><p>The process continues for each element, effectively reversing the order of the words in the sentence. The final reversedSentence is the concatenation of all the words in reverse order, which is &#39;I have nice hello world&#39;.</p><h3>Array methods for converting to string:</h3><h4>- join()</h4><p>The join() method is used to concatenate all the elements of an array into a single string, using a specified separator between each element. It is commonly used when you want to create a string representation of the array with custom formatting.</p><p>Think of a shopping list, and you want to create a comma-separated string of items to display it on the screen. join() can be used to format the list.</p><p><strong>Syntax</strong>: array.join(separator)</p><p><strong>Example:</strong></p><pre>let shoppingList = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];<br>let formattedList = shoppingList.join(&#39;, &#39;);<br>console.log(formattedList); // Output: &#39;apple, banana, orange&#39;</pre><p><strong>Explanation</strong>: In this example, the shoppingList array is converted into a string called formattedList. The join(&#39;, &#39;) function call specifies that each element in the array should be separated by a comma and a space. So, the elements &#39;apple&#39;, &#39;banana&#39;, and &#39;orange&#39; are concatenated with &#39;, &#39; in between, resulting in the string &#39;apple, banana, orange&#39;. The formattedList is then displayed using console.log().</p><h4>- toString()</h4><p>The toString() method is used to convert an array to a string representation, with elements separated by commas. It is commonly used when you want to quickly convert an array to a string without specifying a custom separator.</p><p>Consider an array of user names, and you want to display them as a string in the UI without any special formatting. toString() can be used for this purpose.</p><p><strong>Syntax</strong>: array.toString()</p><p><strong>Example:</strong></p><pre>let usernames = [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;];<br>let usernamesString = usernames.toString();<br>console.log(usernamesString); // Output: &#39;Alice,Bob,Charlie&#39;</pre><p><strong>Explanation</strong>: In this example, the usernames array is converted into a string called usernamesString. The toString() function is called implicitly when assigning the array to a string variable. As a result, the elements &#39;Alice&#39;, &#39;Bob&#39;, and &#39;Charlie&#39; are joined with commas in between, resulting in the string &#39;Alice,Bob,Charlie&#39;. The usernamesString is then displayed using console.log().</p><h3>Array methods for Typed Arrays (for handling binary data)</h3><h4>- TypedArray.of()</h4><p>The TypedArray.of() method creates a new TypedArray instance with a variable number of arguments passed as elements of the array. TypedArray.of() is used to create a new TypedArray with specific elements. Unlike traditional arrays, TypedArrays have a fixed size and represent raw binary data, which is useful for working with low-level binary data, such as image data, audio samples, or network packets.</p><p>In a multimedia application, you might use TypedArray.of() to create a Float32Array containing audio samples or an Uint8Array to represent image pixel data.</p><p><strong>Syntax</strong>: TypedArray.of(element0, element1, …, elementN)</p><p><strong>Example:</strong></p><pre>const audioSamples = Float32Array.of(0.1, 0.5, -0.2, 0.8);<br>console.log(audioSamples); // Output: Float32Array [0.1, 0.5, -0.2, 0.8]</pre><p><strong>Explanation</strong>: The of() method creates a new Typed Array from the provided arguments. In this case, a new Float32Array is created with the values 0.1, 0.5, -0.2, and 0.8. The Float32Array is a typed array that represents an array of 32-bit floating-point numbers. It is commonly used in scenarios where precise floating-point arithmetic is required, such as audio processing or graphics.</p><p>The console.log() statement displays the audioSamples Typed Array, which outputs Float32Array [0.1, 0.5, -0.2, 0.8], showing the elements contained within it.</p><h4>- TypedArray.from()</h4><p>The TypedArray.from() method creates a new TypedArray from an array-like or iterable object. TypedArray.from() is used to convert an array-like or iterable object into a TypedArray. This is helpful when you receive binary data as a regular array or an iterable, and you need to work with it as a TypedArray.</p><p>When receiving binary data from network requests or file reads, you can use TypedArray.from() to convert the data into the appropriate TypedArray for further processing.</p><p><strong>Syntax: </strong>TypedArray.from(arrayLikeOrIterable, mapFn, thisArg)</p><p><strong>Example:</strong></p><pre>const binaryData = [255, 0, 127, 64];<br>const uint8Array = Uint8Array.from(binaryData);<br>console.log(uint8Array); // Output: Uint8Array [255, 0, 127, 64]</pre><p><strong>Explanation</strong>: In this example, the binaryData array contains numbers representing binary data in the range of 0 to 255. The Uint8Array.from() method converts this array into a new Uint8Array, which is a Typed Array that can store 8-bit unsigned integers (0 to 255).</p><p>The resulting uint8Array contains the same values as binaryData, but now they are stored as 8-bit unsigned integers. The console.log() statement displays the uint8Array, showing the output Uint8Array [255, 0, 127, 64].</p><h3>Conclusion:</h3><p>In conclusion, JavaScript provides a rich set of array built-in methods that cater to various array manipulation needs. Whether it’s adding or removing elements, combining arrays, searching for specific elements, or iterating through array elements, JavaScript’s array methods offer powerful functionality to efficiently work with data. Additionally, specialized methods for handling binary data using Typed Arrays, and operations for implementing stacks, queues, and immutable array transformations, further enhance the versatility of array manipulations in JavaScript. With this diverse array of tools at their disposal, developers can effectively tackle a wide range of tasks and optimize their code for enhanced performance and functionality.</p><blockquote>If you found this content helpful and informative, I would greatly appreciate your support by following my profile. By following, you can stay updated with my future articles and gain more valuable insights into Web development and other related topics. Your support means a lot to me, and I look forward to sharing more useful content with you in the future. Thank you for your time and consideration!</blockquote><p>If you enjoyed what you read &amp; found it insightful, please consider supporting me <a href="https://buymeacoffee.com/atuljha24"><strong>here</strong> Your support is greatly appreciated!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9562d4052ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lets learn Basics of Array using JavaScript]]></title>
            <link>https://medium.com/@atuljha2402/lets-learn-basics-of-array-using-javascript-d5ae3be58c84?source=rss-d100b49c8be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5ae3be58c84</guid>
            <category><![CDATA[iteration]]></category>
            <category><![CDATA[pop]]></category>
            <category><![CDATA[bubble-sort]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[push]]></category>
            <dc:creator><![CDATA[Atul jha]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 19:34:46 GMT</pubDate>
            <atom:updated>2024-08-18T05:30:36.049Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Arrays are an essential and powerful data structure that allows us to store and manipulate collections of elements efficiently. Whether you’re a beginner or already familiar with JavaScript, understanding arrays is crucial for building dynamic and interactive web applications. In this blog, we will explore the fundamentals of arrays, learn how to add, remove, and manipulate array elements, find specific values within arrays, sort and join arrays, and iterate over their elements using various methods. Get ready to dive into the world of arrays and unlock their potential in JavaScript programming. Let’s begin our journey into the fascinating realm of arrays!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfkIog73IqA0RDoz9jcnYg.png" /></figure><h3>What are Arrays?</h3><p>Arrays are a fundamental data structure in JavaScript used to store and organize collections of elements. They provide a convenient way to work with multiple values as a single entity. <strong>Arrays can contain any combination of primitive values (such as numbers, strings, booleans) or reference values (such as objects, functions, or other arrays).</strong></p><p>Arrays provides various methods and properties that enable us to add, remove, search, and modify elements within the collection. We will understand all these methods in this blog itself.</p><h4>Declaring and initializing an array:</h4><p>The most common method of declaring an array is to use square brackets [ ] to enclose a comma-separated list of elements:</p><pre>let numbers = [1, 2, 3, 4, 5];<br>let fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];<br>let mixedArray = [1, &#39;hello&#39;, true, null, { name: &#39;Atul&#39; }];</pre><p>In the examples above, we declare arrays named numbers, fruits, and mixedArray and initialize them with different elements. Note that arrays can contain elements of different types, allowing for versatility in data representation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vb6U1AgIkDKRJegBoeFzSg.png" /></figure><h4>Accessing Array elements:</h4><p>To access individual elements within an array, we use zero-based indexing. Each element is assigned an index starting from 0 for the first element, 1 for the second element, and so on.</p><pre>let numbers = [1, 2, 3, 4, 5];<br><br>console.log(numbers[0]); // Output: 1<br>console.log(numbers[2]); // Output: 3<br>console.log(numbers[4]); // Output: 5</pre><p>In the example above, we access elements of the numbers array by specifying their respective indices within square brackets.</p><p>It’s important to note that JavaScript arrays are dynamic, meaning their size can change dynamically by adding or removing elements. There is no fixed limit to the number of elements an array can hold.</p><p><strong>Now lets start learning the concept of manipulating arrays….</strong></p><h3>JS Array Length:</h3><p>The length property of arrays in JavaScript provides the number of elements present in an array. It allows you to determine the size or length of an array dynamically. Here&#39;s an explanation with an example:</p><pre>let fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];<br>console.log(fruits.length); // Output: 3</pre><p>In the example above, the array fruits contains three elements. By accessing the length property (fruits.length), we obtain the value 3, indicating the number of elements in the array.</p><p>The length property is automatically updated whenever elements are added to or removed from the array. It provides a convenient way to check the size of an array dynamically, making it useful for various operations and conditions in your code.</p><h3>Adding elements in Array:</h3><p>In JavaScript, there are multiple ways to add elements to an array. Here are a few common methods:</p><ul><li><strong>push()</strong>: The push() method adds one or more elements to the end of an array and returns the new length of the array. It modifies the original array.</li></ul><pre>let numbers = [1, 2, 3];<br>numbers.push(4);<br>numbers.push(5);<br>console.log(numbers); // Output: [1, 2, 3, 4, 5]</pre><ul><li><strong>unshift()</strong>: The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. It also modifies the original array.</li></ul><pre>let numbers = [2, 3, 4];<br>numbers.unshift(0);<br>numbers.unshift(1);<br>console.log(numbers); // Output: [0, 1, 2, 3, 4]</pre><ul><li><strong>Specific index array assignment</strong>: You can assign values to specific index no. of an array to add elements.</li></ul><pre>let numbers = [1, 2, 4];<br>numbers[2] = 3;<br>console.log(numbers); // Output: [1, 2, 3]</pre><p>In the examples above, elements are added to the array numbers using the push() method, unshift() method, and direct assignment to an index.</p><p>It’s important to note that these methods modify the original array. If you want to create a new array without modifying the original, you can use methods like concat() or the array spread syntax ([...array]) to create a new array with the added elements.</p><p>You can refer to this <a href="https://medium.com/@atuljha2402/understanding-javascript-operators-514600727b91">blog </a>to learn about spread operator &amp; Concatenation.</p><h3>Removing element in Array:</h3><p>JavaScript provides various techniques to remove elements from an array. Here are a few common methods:</p><ul><li><strong>pop()</strong>: The pop() method removes the last element from an array and returns the removed element. It also modifies the original array.</li></ul><pre>let numbers = [1, 2, 3, 4];<br>let removedElement = numbers.pop();<br>console.log(numbers); // Output: [1, 2, 3]<br>console.log(removedElement); // Output: 4</pre><ul><li><strong>shift()</strong>: The shift() method removes the first element from an array and returns the removed element. It modifies the original array.</li></ul><pre>let numbers = [1, 2, 3, 4];<br>let removedElement = numbers.shift();<br>console.log(numbers); // Output: [2, 3, 4]<br>console.log(removedElement); // Output: 1</pre><ul><li><strong>Array Assignment:</strong> You can assign a new value (undefined) or remove an element by assigning undefined or null to a specific index.</li></ul><pre>let numbers = [1, 2, 3, 4];<br>numbers[2] = undefined;<br>console.log(numbers); // Output: [1, 2, undefined, 4]</pre><p>In the examples above, elements are removed from the array numbers using the pop() method, shift() method, and by assigning undefined to an index.</p><p>Similar to adding elements, these methods modify the original array. If you want to create a new array without the removed elements, you can use methods like slice() or the array filter method (filter()) to create a new array with the desired elements.</p><h3>Emptying an Array:</h3><p>Emptying an array refers to the process of removing all elements from the array. There are several approaches to achieve this:</p><ul><li><strong>Reassigning an Empty Array</strong>: You can empty an array by assigning it an empty array literal ([]), which effectively replaces the existing array with a new empty array.</li></ul><pre>let numbers = [1, 2, 3, 4];<br>numbers = [];<br>console.log(numbers); // Output: []<br><br>// Don&#39;t declare the number variable using const. <br>// As once the values are assigned it can be modified</pre><p>In the above example, the array numbers is emptied by assigning it an empty array.</p><ul><li><strong>Using the Length Property:</strong> Another approach is to set the length property of the array to 0. This method effectively truncates the array, removing all elements beyond the new length.</li></ul><pre>let numbers = [1, 2, 3, 4];<br>numbers.length = 0;<br>console.log(numbers); // Output: []</pre><p>In this example, setting numbers.length to 0 results in an empty array.</p><p>Both methods effectively empty the array, but it’s important to note that they differ in how they handle the original array reference. Reassigning an empty array creates a new array instance, while modifying the length property modifies the original array in place.</p><h3>Finding Elements in array (Primitives):</h3><p>When dealing with arrays of primitive values (such as numbers, strings, booleans), JavaScript provides several methods to find specific elements:</p><ul><li><strong>indexOf()</strong>: The indexOf() method returns the first index at which a given element is found in the array. If the element is not found, it returns -1.</li></ul><pre>let numbers = [1, 2, 3, 4, 5];<br>console.log(numbers.indexOf(3)); // Output: 2<br>console.log(numbers.indexOf(6)); // Output: -1 (element not found)</pre><p>In the example above, indexOf(3) returns 2, indicating that the element 3 is found at index 2 in the array.</p><ul><li><strong>includes()</strong>: The includes() method determines whether an array contains a specific element and returns a boolean value (true or false).</li></ul><pre>let numbers = [1, 2, 3, 4, 5];<br>console.log(numbers.includes(3)); // Output: true<br>console.log(numbers.includes(6)); // Output: false</pre><p>In this example, includes(3) returns true since the element 3 is present in the array.</p><ul><li><strong>find()</strong>: The find() method returns the first element in the array that satisfies a provided testing function. If no element satisfies the condition, it returns undefined.</li></ul><pre>let numbers = [1, 2, 3, 4, 5];<br>let foundNumber = numbers.find((element) =&gt; element &gt; 3);<br>console.log(foundNumber); // Output: 4</pre><p>In the above example, find() returns 4 as the first element greater than 3 in the array.</p><p>These methods provide ways to search for specific primitive values in an array, enabling you to locate and perform further operations on the found elements.</p><h3>Finding Elements in array (Reference Types):</h3><p>When dealing with arrays of reference types (such as objects, functions, or arrays themselves), additional methods can be used to find elements:</p><ul><li><strong>find():</strong> The find() method can also be used with reference types. It returns the first element in the array that satisfies a provided testing function.</li></ul><pre>let employees = [<br>  { id: 1, name: &#39;Raj&#39; },<br>  { id: 2, name: &#39;Kanha&#39; },<br>  { id: 3, name: &#39;Vishnu&#39; },<br>];<br><br>let foundEmployee = employees.find((employee) =&gt; employee.id === 2);<br>console.log(foundEmployee); // Output: { id: 2, name: &#39;Kanha&#39; }</pre><p>In this example, find() returns the employee object with an id of 2.</p><ul><li><strong>filter()</strong>: The filter() method creates a new array with all elements that pass a provided testing function.</li></ul><pre>let employees = [<br>  { id: 1, name: &#39;Raj&#39; },<br>  { id: 2, name: &#39;Kanha&#39; },<br>  { id: 3, name: &#39;Vishnu&#39; },<br>];<br><br>let filteredEmployees = employees.filter((employee) =&gt; employee.name.startsWith(&#39;R&#39;));<br>console.log(filteredEmployees); // Output: [{ id: 1, name: &#39;Raj&#39; }</pre><p>In this example, filter() returns a new array containing the employee objects with names starting with &#39;R&#39;.</p><p>Custom comparison functions can be used with both find() and filter() to define specific criteria for finding elements within the array.</p><p>These methods allow you to search arrays of reference types based on specific conditions, making it easier to locate and work with the desired elements.</p><h3>Sorting Arrays:</h3><p>Sorting arrays in JavaScript involves arranging the elements of an array in a specific order.</p><ul><li><strong>Manual Swap Sorting Technique:</strong> The manual swap sorting technique, also known as the bubble sort algorithm, is a simple sorting algorithm that compares adjacent elements and swaps them if they are in the wrong order. This process is repeated until the array is sorted.</li></ul><p><strong>Here’s an example of how the bubble sort algorithm can be implemented:</strong></p><pre>function bubbleSort(arr) {<br>  let len = arr.length;<br>  let swapped;<br>  <br>  do {<br>    swapped = false;<br>    for (let i = 0; i &lt; len - 1; i++) {<br>      if (arr[i] &gt; arr[i + 1]) {<br>        let temp = arr[i];<br>        arr[i] = arr[i + 1];<br>        arr[i + 1] = temp;<br>        swapped = true;<br>      }<br>    }<br>  } while (swapped);<br>  <br>  return arr;<br>}<br><br>let numbers = [5, 3, 8, 1, 2];<br>console.log(bubbleSort(numbers)); // Output: [1, 2, 3, 5, 8]</pre><p>In the example above, the bubbleSort() function implements the manual swap sorting technique on the numbers array. The algorithm repeatedly compares adjacent elements and swaps them if necessary until the array is sorted in ascending order.</p><ul><li><strong>Using the sort() method: </strong>JavaScript arrays provide a built-in sort() method, which sorts the elements of an array in place and returns the sorted array. By default, the sort() method sorts elements as strings based on their Unicode code points. However, for numerical or custom sorting, you can provide a custom comparison function as a parameter.</li></ul><pre>let numbers = [5, 3, 8, 1, 2];<br>numbers.sort();<br>console.log(numbers); // Output: [1, 2, 3, 5, 8]</pre><p>In the example above, the sort() method is used to sort the numbers array. Since the elements are numbers, the default string-based comparison results in the array being sorted correctly.</p><h3>Joining Arrays:</h3><p>The join() method in JavaScript allows you to join the elements of an array into a single string. You can specify a separator that will be inserted between the elements in the resulting string.</p><p>Here’s an example of using the join() method:</p><pre>let fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;];<br>let joinedString = fruits.join(&#39;, &#39;);<br>console.log(joinedString); // Output: &quot;apple, banana, orange&quot;</pre><p>In the example above, the join(&#39;, &#39;) call joins the elements of the fruits array into a single string with a comma and space as the separator.</p><p>By default, if no separator is provided to the join() method, it uses a comma as the separator. However, you can customize the separator by passing it as an argument.</p><h3>Iterating array:</h3><p>Array iteration methods allow you to iterate over each element in an array and perform certain actions or transformations. <strong>Here are some commonly used array iteration methods:</strong></p><ul><li><strong>forEach()</strong>: The forEach() method executes a provided function once for each element in the array.</li></ul><pre>let numbers = [1, 2, 3, 4, 5];<br>numbers.forEach((number) =&gt; {<br>  console.log(number * 2);<br>});<br>// Output: 2, 4, 6, 8, 10</pre><p>In this example, the forEach() method is used to iterate over each element in the numbers array and log its double to the console.</p><ul><li><strong>map():</strong> The map() method creates a new array by calling a provided function on each element in the array.</li></ul><pre>let numbers = [1, 2, 3, 4, 5];<br>let doubledNumbers = numbers.map((number) =&gt; number * 2);<br>console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]</pre><p>In this example, the map() method transforms each element in the numbers array by multiplying it by 2 and creates a new array (doubledNumbers) with the transformed values.</p><ul><li><strong>filter()</strong>: The filter() method creates a new array with all elements that pass a provided test implemented by a provided function.</li></ul><pre>let numbers = [1, 2, 3, 4, 5];<br>let evenNumbers = numbers.filter((number) =&gt; number % 2 === 0);<br>console.log(evenNumbers); // Output: [2, 4]</pre><p>In this example, the filter() method filters out the odd numbers from the numbers array and creates a new array (evenNumbers) containing only the even numbers.</p><ul><li><strong>reduce()</strong>: The reduce() method applies a provided function to reduce the array to a single value.</li></ul><pre>let numbers = [1, 2, 3, 4, 5];<br>let sum = numbers.reduce((accumulator, currentNumber) =&gt; accumulator + currentNumber, 0);<br>console.log(sum); // Output: 15</pre><p>In this example, the reduce() method calculates the sum of all the numbers in the numbers array by continuously adding each number to the accumulator (sum) starting from an initial value of 0.</p><h3>Example time:</h3><p>As an example incorporating many of these array concepts, let’s consider a minor project. We will be developing a simple task management application where users can create, update, and delete tasks. We will utilize arrays to store and manage the task data. Here’s a simplified code snippet &amp; live working project. (You can apply more style &amp; publish it on your github as an minor project😬)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fweb-platform-qnwgr6%3Fembed%3D1%26file%3Dscript.js&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fweb-platform-qnwgr6%3Fembed%3D1%26file%3Dscript.js&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fweb-platform-qnwgr6%2F0793cfe9bcc3c3205fb63c6d8ff3d454&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7702b1b5b7998e802c095d591a6ddae/href">https://medium.com/media/a7702b1b5b7998e802c095d591a6ddae/href</a></iframe><p>In the above project, we have created an HTML To-Do form where users can enter tasks. On clicking the “Add Task” button, the addTask() function is called, which adds the task to the tasks array. The renderTasks() function iterates over the array using forEach() and dynamically generates a list of tasks in the HTML.</p><p>This minor project showcases concepts such as adding elements to an array (push()), rendering array elements (forEach()), and utilizing arrays for managing dynamic data.</p><h3>Conclusion:</h3><p>In this blog of JavaScript arrays, we have covered various topics related to their usage and manipulation. We began with an introduction to arrays, understanding their purpose as a fundamental data structure for organizing and managing collections of elements. We learned how to declare and initialize arrays using different methods.</p><p>Moving forward, we discussed the length property of arrays, which provides the number of elements present in an array. We explored techniques for adding and removing elements from arrays using methods like push(), pop(), unshift(), shift(), and array assignment.</p><p>We also delved into emptying an array through different approaches, including reassigning an empty array and utilizing the length property. We explored finding elements in arrays, both with primitive values and reference types, using methods like indexOf(), includes(), find(), and filter().</p><p>Sorting arrays was another important aspect we covered, including the manual swap sorting technique and utilizing the sort() method with custom comparison functions. Additionally, we explored joining array elements into a single string using the join() method.</p><p>Lastly, we introduced array iteration methods like forEach(), map(), filter(), and reduce(), which enable us to iterate over array elements and perform various actions or transformations.</p><p>To conclude, understanding JavaScript arrays is essential for effective data management and manipulation in web development. By mastering these array concepts, you can build powerful applications that efficiently handle collections of data.</p><p>If you enjoyed what you read &amp; found it insightful, please consider supporting me <a href="https://buymeacoffee.com/atuljha24"><strong>here</strong> Your support is greatly appreciated!</a></p><blockquote>If you found this content helpful and informative, I would greatly appreciate your support by following my profile. By following, you can stay updated with my future articles and gain more valuable insights into Web development and other related topics. Your support means a lot to me, and I look forward to sharing more useful content with you in the future. Thank you for your time and consideration!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5ae3be58c84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JavaScript Objects]]></title>
            <link>https://medium.com/@atuljha2402/mastering-javascript-objects-845c4f0c5de3?source=rss-d100b49c8be3------2</link>
            <guid isPermaLink="false">https://medium.com/p/845c4f0c5de3</guid>
            <category><![CDATA[setter]]></category>
            <category><![CDATA[objects-in-javascript]]></category>
            <category><![CDATA[methods]]></category>
            <category><![CDATA[getter]]></category>
            <category><![CDATA[constructor]]></category>
            <dc:creator><![CDATA[Atul jha]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 21:53:23 GMT</pubDate>
            <atom:updated>2023-07-16T21:53:23.811Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will explore JavaScript objects from the ground up, covering everything from the basics to advanced concepts. We’ll dive into object creation, properties, methods, prototypes, and much more. Along the way, we’ll dive into practical examples and code snippets to help solidify the understanding and demonstrate its real-world applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCt79nyqtG9-bVwQ7Y5idQ.png" /></figure><h3>Introduction:</h3><p>Object is a container that holds properties and methods, making it a important concept for modeling real-world entities, data structures, and more. <strong>Objects provide a way to represent complex data structures and enclose behavior within a single entity.</strong></p><p>One of the simplest ways to create objects is by using object literals. <strong>An object literal is a comma-separated list of key-value pairs enclosed in curly braces </strong><strong>{}</strong>. The keys (also known as properties) are strings that represent the names of the properties, and the values can be any valid JavaScript datatype, such as strings, numbers, booleans, arrays, or even other valid objects.</p><p><strong>Here’s an example of an object literal representing a person</strong><em>:</em></p><pre>const person = {<br>  name: &quot;Atul Jha&quot;,<br>  age: 21,<br>  profession: &quot;Web Developer&quot;,<br>};</pre><p>In the above example, person is an object with three properties: name, age, and profession. You can access these properties using dot notation (person.name) or bracket notation (person[&#39;name&#39;]).</p><blockquote><strong>Writers thought:</strong> But don’t you think that when using the object creation method mentioned above, if you need to store multiple objects with the same properties, you would end up duplicating the objects multiple times, which can become confusing and inefficient?</blockquote><blockquote><strong>Imaginary reader</strong>: Yes I do. Is there any efficient way of storing data of multiple objects having same properties without duplicating code?</blockquote><blockquote><strong>Writers thought</strong>: Yes !! We can do it by using “<strong>Object constructors</strong>”.</blockquote><h3>What are object constructors?</h3><p>Object constructors provide a way to create objects using a constructor function. A constructor function serves as a blueprint for creating multiple instances of similar objects. It allows you to define the initial state (properties) and behavior (methods) of an object.</p><p>Here’s an example of an object constructor function that creates person objects:</p><pre>function Person(name, age, profession) {<br>  this.name = name;<br>  this.age = age;<br>  this.profession = profession;<br>}<br><br>// Creating a new person object using the constructor<br>const john = new Person(&quot;Atul Jha&quot;, 21, &quot;Web Developer&quot;);</pre><p>In the above example, the Person constructor function takes parameters for name, age, and profession. Inside the constructor function, this refers to the newly created object. <strong>By using </strong><strong>this.propertyName, we assign values to the object&#39;s properties based on the provided arguments. </strong>The new keyword creates a new instance of the Person object.</p><p>Using object constructors allows you to create multiple objects with similar properties and methods without duplicating code. You can add methods to the constructor function’s prototype to be shared among all instances, achieving better memory efficiency.</p><h4>Lets dive into the concept of Object properties &amp; Object Methods:</h4><h3>Object Properties:</h3><p>Properties are an essential part of objects. They allow us to store and access data within an object. Let’s explore each aspect in detail:</p><h4>a) Creating and Accessing Object Properties:</h4><p>To create an object property, we assign a value to a key within the object. We can access properties using dot notation (object.property) or bracket notation (object[&quot;property&quot;]). Here&#39;s an example:</p><pre>const person = {<br>  name: &quot;Atul Jha&quot;,<br>  age: 21,<br>  profession: &quot;Web Developer&quot;,<br>};<br><br>console.log(person.name); // Output: Atul Jha<br>console.log(person[&quot;age&quot;]); // Output: 21</pre><p>In the above example, we have created a person object with defined properties such as name, age, and profession. We access these properties using dot notation and bracket notation.</p><h4>b) Declaration of different types of properties in object:</h4><p>Properties can hold different types of values. They can store primitive values like strings, numbers, booleans, or even more complex types like arrays and objects. Let’s consider an example:</p><pre>const student = {<br>  name: &quot;Atul Jha&quot;,<br>  age: 21,<br>  subjects: [&quot;Math&quot;, &quot;Science&quot;, &quot;Coding&quot;],<br>  address: {<br>    street: &quot;Vijaynagar Society&quot;,<br>    city: &quot;Pune&quot;,<br>  },<br>};<br><br>console.log(student.subjects[1]); // Output: Science<br>console.log(student.address.city); // Output: Pune</pre><p>In this example, the subjects property holds an array, and the address property contains another object (Nested Objects). We can access nested properties by using dot notation.</p><p><strong>c) Property Iteration using Loops and Built-in Methods:</strong></p><p>We can <strong>iterate over all the properties of an object using loops or built-in methods</strong>. One common approach is to use a for…in loop, which allows us to loop through all enumerable properties of an object.</p><p>Alternatively, we can use built-in methods like Object.keys(), Object.values(), or Object.entries() to obtain arrays of the object’s keys, values, or <strong>key-value</strong> pairs, respectively. <strong>Let’s see an example:</strong></p><pre>const person = {<br>  name: &quot;Atul Jha&quot;,<br>  age: 21,<br>};<br><br>// Using loop<br>for (let key in person) {<br>  console.log(key + &quot;: &quot; + person[key]);<br>} // Output: name: Atul Jha age: 21<br><br>//Alternate Method (Using built-in method)👇<br>const keys = Object.keys(person);<br>console.log(keys); // Output: [&quot;name&quot;, &quot;age&quot;]</pre><p>In the above example, the for...in loop iterates through each property of the person object, and the Object.keys() method retrieves an array of the object&#39;s keys.</p><p>Now lets dive into the concept of Object methods….</p><h3>Object Methods:</h3><p>Methods are functions associated with objects that can perform actions or calculations. Think of a bank account object with properties like balance and methods like deposit() and withdraw(). These methods allow you to interact with the object by performing actions on the account balance. <strong>Let’s explore the concepts related to object methods:</strong></p><h4>a) Adding Methods to Objects:</h4><p>Methods can be added to objects by assigning a function to a property. We can then invoke the method using dot notation on the object. Here’s an example:</p><pre>const calculator = {<br>  operand1: 5,<br>  operand2: 10,<br>  add: function () {<br>    return this.operand1 + this.operand2;<br>  },<br>};<br><br>console.log(calculator.add()); // Output: 15</pre><p>In the above example, we add the add method to the calculator object, which calculates the sum of the operands using this.operand1 and this.operand2.</p><h4>b) Invoking Object Methods:</h4><p>Object methods are invoked using dot notation or bracket notation. When a method is invoked, the this keyword inside the method refers to the object itself. It allows the method to access and manipulate the object&#39;s properties. <strong>Here&#39;s an example:</strong></p><pre>const person = {<br>  name: &quot;Atul Jha&quot;,<br>  age: 21,<br>  greet: function () {<br>    console.log(&quot;Hello, my name is &quot; + this.name);<br>  },<br>};<br><br>person.greet(); // Output: Hello, my name is Atul Jha</pre><p><strong>In the above example</strong>, the greet method of the person object uses this.name to access the object&#39;s name property and generates a greeting.</p><blockquote><strong>Writers thought: </strong>Working with objects involves various manipulation and utility methods. Until now we have learnt everything about creating &amp; accessing objects. Now it time to learn Object manipulation &amp; utility method.</blockquote><h3>Object Manipulation and Utility Methods:</h3><h4>a) Object Copying (Shallow and Deep):</h4><p>Object copying refers to creating new objects with the same properties and values as an existing object. <br>Shallow copying creates a new object with references to the same properties, while deep copying creates a new object with entirely new properties. <strong>Here’s an example:</strong></p><pre>// Shallow copying<br>const originalObject = { name: &quot;Atul&quot;, age: 21 };<br>const copiedObject = Object.assign({}, originalObject);<br><br>// Deep copying<br>const deepCopiedObject = JSON.parse(JSON.stringify(originalObject));</pre><p>In the above example, Object.assign() performs shallow copying, while using JSON.stringify() and JSON.parse() achieves deep copying.</p><h4>b) Object Merging:</h4><p>Object merging combines multiple objects into a single object, either by modifying an existing object or creating a new one. The spread syntax (...) allows us to merge objects easily. <strong>Here&#39;s an example:</strong></p><pre>const obj1 = { a: 1, b: 2 };<br>const obj2 = { c: 3, d: 4 };<br><br>// Merging objects using spread syntax<br>const mergedObject = { ...obj1, ...obj2 };</pre><p>In the above example, the mergedObject contains properties from both obj1 and obj2.</p><h4>c) Object Property Deletion:</h4><p>To delete a property from an object, we can use the delete keyword. <strong>Here&#39;s an example:</strong></p><pre>const person = { name: &quot;Atul Jha&quot;, age: 21 };<br>delete person.age;</pre><p>In the above example, the age property is deleted from the person object.</p><h4>d) Object Property Existence Checks:</h4><p>To check if an object has a specific property, we can use various techniques. The in operator and the hasOwnProperty() method are commonly used. <strong>Here&#39;s an example:</strong></p><pre>const person = { name: &quot;Atul Jha&quot;, age: 21 };<br><br>console.log(&quot;name&quot; in person); // Output: true<br>console.log(person.hasOwnProperty(&quot;age&quot;)); // Output: true</pre><p>In the above example, we check if the person object has the properties &quot;name&quot; and &quot;age&quot;.</p><h4>e) Object Property Enumeration:</h4><p>Object property enumeration involves iterating over an object’s properties. The for...in loop and the Object.keys() method are commonly used for this purpose. <strong>Here&#39;s an example:</strong></p><pre>const person = { name: &quot;Atul Jha&quot;, age: 21 };<br><br>for (let key in person) {<br>  console.log(key + &quot;: &quot; + person[key]);<br>}<br><br>const keys = Object.keys(person);<br>console.log(keys); // Output: [&quot;name&quot;, &quot;age&quot;]</pre><p><strong>In the above example</strong>, the for...in loop iterates over each property of the person object, while Object.keys() retrieves an array of the object&#39;s keys.</p><h3>Built-in Objects:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqAC7FMBOObfZnG_K0b_gA.png" /></figure><p>Built-in objects in JavaScript are predefined objects that are part of the JavaScript language itself. They provide useful functionality and methods for performing various operations without requiring explicit instantiation or external libraries. These objects are available globally and can be accessed from anywhere in your JavaScript code.</p><h4>a) The Object Constructor and Methods:</h4><p>The Object constructor is a built-in object in JavaScript that serves as the foundation for creating other objects. It provides methods to perform various operations on objects. <strong>Let&#39;s explore:</strong></p><ul><li><strong>Creating Objects with the Object Constructor:</strong></li></ul><pre>const person = new Object();<br>person.name = &quot;Atul Jha&quot;;<br>person.age = 21;</pre><p>In the above example, we use the Object constructor to create a new object called person. We then add properties name and age to the object.</p><ul><li><strong>The </strong><strong>Object.keys() Method:</strong></li></ul><pre>const person = { name: &quot;Atul Jha&quot;, age: 21 };<br>const keys = Object.keys(person);<br>console.log(keys); // Output: [&quot;name&quot;, &quot;age&quot;]</pre><p>Here, Object.keys() returns an array containing the keys of the person object.</p><h4>b) The Array Object and Array-Specific Methods:</h4><p>The Array object is used for working with arrays, which are ordered collections of elements. It offers a range of methods to manipulate and access array elements. <strong>Let&#39;s see some examples:</strong></p><ul><li><strong>Creating and Accessing Arrays:</strong></li></ul><pre>const numbers = [1, 2, 3, 4, 5];<br>console.log(numbers[0]); // Output: 1<br>console.log(numbers.length); // Output: 5</pre><p><strong>In the above example</strong>, we create an array called numbers containing five elements. We access the first element using bracket notation and retrieve the length of the array.</p><ul><li><strong>Array Methods:</strong></li></ul><pre>const fruits = [&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;];<br>fruits.push(&quot;grape&quot;); // Adds an element to the end<br>console.log(fruits); // Output: [&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;, &quot;grape&quot;]<br>fruits.pop(); // Removes the last element<br>console.log(fruits); // Output: [&quot;apple&quot;, &quot;banana&quot;, &quot;orange&quot;]</pre><p>In the above example, we use the push() method to add an element to the end of the fruits array, and pop() to remove the last element.</p><h4><strong>c) The Math Object and Math-Related Methods:</strong></h4><p>The Math object provides mathematical operations and constants for performing calculations. <strong>Let&#39;s explore some useful methods:</strong></p><ul><li><strong>Generating Random Numbers:</strong></li></ul><pre>const randomNum = Math.random(); // Generates a random number between 0 and 1<br>console.log(randomNum);</pre><p>The Math.random() method returns a random number between 0 (inclusive) and 1 (exclusive).</p><ul><li><strong>Rounding Numbers:</strong></li></ul><pre>const number = 3.7;<br>const roundedNum = Math.round(number); // Rounds to the nearest integer<br>console.log(roundedNum); // Output: 4</pre><p>The Math.round() method rounds a number to the nearest integer.</p><h4>d) The Date Object and Date/Time Manipulation:</h4><p>The Date object provides functionality for working with dates and times. Let&#39;s explore some common operations:</p><ul><li><strong>Creating a Date Object:</strong></li></ul><pre>const currentDate = new Date();<br>console.log(currentDate);</pre><p>The Date() constructor creates a new Date object representing the current date and time.</p><ul><li><strong>Getting Specific Date/Time Components:</strong></li></ul><pre>const currentDate = new Date();<br>const year = currentDate.getFullYear();<br>const month = currentDate.getMonth();<br>const day = currentDate.getDate();<br>console.log(year, month, day);</pre><p>Here, we use various Date methods like getFullYear(), getMonth(), and getDate() to retrieve specific date components.</p><p>By utilizing these built-in objects and their methods, you can perform a wide range of operations, manipulate data, and work with dates and times in JavaScript. You can visit to this <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#static_methods">documentation </a>for exploring more JavaScript built-in methods.</p><p>Now its time to learn one last important topic related to JavaScript object…..</p><h3>What is object accessor?</h3><p>Object accessors, also known as property accessors or property getters and setters, are a way to define custom behavior for accessing and modifying object properties in JavaScript. Accessors allow you to define functions that are invoked when a property is read or written, enabling you to add custom logic or validation to property access. <strong>Accessors consist of two special functions:</strong></p><ul><li><strong>Getter, &amp;</strong></li><li><strong>Setter</strong></li></ul><h4>Getter:</h4><p>A getter function is used to retrieve the value of a property. It is defined using the get keyword followed by the property name, and it does not take any arguments. When the property is accessed, the getter function is automatically invoked, and its return value is used as the property value.</p><p><strong>Here’s an example of a getter function:</strong></p><pre>const person = {<br>  firstName: &quot;Atul&quot;,<br>  lastName: &quot;Jha&quot;,<br>  get fullName() {<br>    return this.firstName + &quot; &quot; + this.lastName;<br>  }<br>};<br><br>console.log(person.fullName); // Output: Atul Jha</pre><p>In the above example, the fullName property is defined with a getter function. When person.fullName is accessed, the getter function is called, and it returns the concatenation of the firstName and lastName properties.</p><h4>Setter:</h4><p>A setter function is used to modify the value of a property. It is defined using the set keyword followed by the property name and a parameter representing the new value. When the property is assigned a new value, the setter function is automatically invoked with the assigned value as the argument.</p><p><strong>Here’s an example of a setter function:</strong></p><pre>const person = {<br>  firstName: &quot;Atul&quot;,<br>  lastName: &quot;Jha&quot;,<br>  set fullName(name) {<br>    const [first, last] = name.split(&quot; &quot;);<br>    this.firstName = first;<br>    this.lastName = last;<br>  }<br>};<br><br>person.fullName = &quot;Meenal Oza&quot;;<br>console.log(person.firstName); // Output: Meenal<br>console.log(person.lastName); // Output: Oza</pre><p>In the above example, the fullName property is defined as a setter. When person.fullName is assigned a new value, the setter function is called with the assigned value. Inside the setter function, the value is split into firstName and lastName, and the corresponding properties are updated.</p><p>By using object accessors, you can define custom behavior for property access and modification, allowing you to control the logic, perform validations, and enhance the encapsulation and integrity of your data within objects.</p><h3>Conclusion:</h3><p>In conclusion, JavaScript objects are fundamental data structures that allow us to organize and manipulate data in a structured manner. They are collections of key-value pairs, where each value can be of any data type, including other objects or arrays.</p><p>JavaScript objects offer immense flexibility and power for representing real-world entities, organizing data, and building complex applications. They provide a way to encapsulate data, define behavior through methods, and enable interaction with the outside world.</p><p>Understanding JavaScript objects is crucial for any JavaScript developer, as they form the building blocks of modern JavaScript programming. By mastering object creation, property manipulation, methods, object prototypes, and object-oriented concepts, developers can effectively model and solve problems in a more organized and efficient manner.</p><p>Moreover, JavaScript’s built-in objects, such as Object, Array, Math, and Date, expand the capabilities of objects and provide specialized functionality for common programming tasks. They offer a wealth of methods and properties that simplify data manipulation, mathematical operations, date and time handling, and more.</p><blockquote>If you found this content helpful and informative, I would greatly appreciate your support by following my profile. By following, you can stay updated with my future articles and gain more valuable insights into Web development and other related topics. Your support means a lot to me, and I look forward to sharing more useful content with you in the future. Thank you for your time and consideration!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=845c4f0c5de3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>