<?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 Dhruvil Bhuva on Medium]]></title>
        <description><![CDATA[Stories by Dhruvil Bhuva on Medium]]></description>
        <link>https://medium.com/@dhruvil.unofficial?source=rss-c2f1b6068e6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Gb4ajUwQutQhFXm7</url>
            <title>Stories by Dhruvil Bhuva on Medium</title>
            <link>https://medium.com/@dhruvil.unofficial?source=rss-c2f1b6068e6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:19:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhruvil.unofficial/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[React useCallback Hook: Function Memoization, Dependencies, and Performance]]></title>
            <link>https://medium.com/@dhruvil.unofficial/react-usecallback-hook-function-memoization-dependencies-and-performance-b355ecece80b?source=rss-c2f1b6068e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b355ecece80b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Dhruvil Bhuva]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 18:12:46 GMT</pubDate>
            <atom:updated>2026-10-22T18:12:46.880Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwtrHoNawgD0RAwdtI7ErA.png" /></figure><p>You may have seen React code wrapped in useCallback and wondered why a function needs to be memoized at all.</p><p>After all, JavaScript lets us create functions whenever we need them. So what problem is this Hook solving?</p><p>The answer involves function identity, component re-renders, and cases where a function is passed to another component or used as a dependency.</p><p>Let’s work through a practical example.</p><h3>1. What is useCallback?</h3><p>useCallback is a React Hook that caches a function definition between renders, as long as its dependencies remain unchanged.</p><pre>import { useCallback } from &quot;react&quot;;</pre><pre>const handleClick = useCallback(() =&gt; {<br>  console.log(&quot;Button clicked&quot;);<br>}, []);</pre><p>React can return the same cached function reference on subsequent renders while the dependencies stay the same.</p><p>This doesn’t mean the function only runs once. It can be called many times. The Hook caches the function itself, not the result of calling it.</p><h3>2. Why function identity matters</h3><p>In JavaScript, functions are objects. Two separately created functions are different references, even if they contain identical code.</p><pre>const first = () =&gt; console.log(&quot;Hello&quot;);<br>const second = () =&gt; console.log(&quot;Hello&quot;);</pre><pre>console.log(first === second); // false</pre><p>In React, a new function can be created whenever a component renders.</p><p>Usually, that’s fine. But if a function is passed to a child wrapped in memo, a new function reference can prevent that child from skipping a render caused by changed props.</p><h3>3. A practical example with memo</h3><pre>import { memo, useCallback, useState } from &quot;react&quot;;</pre><pre>const ChildButton = memo(function ChildButton({ onClick }) {<br>  console.log(&quot;ChildButton rendered&quot;);</pre><pre>  return &lt;button onClick={onClick}&gt;Child Button&lt;/button&gt;;<br>});</pre><pre>function Parent() {<br>  const [count, setCount] = useState(0);<br>  const [theme, setTheme] = useState(&quot;light&quot;);</pre><pre>  const handleChildClick = useCallback(() =&gt; {<br>    console.log(&quot;Child button clicked&quot;);<br>  }, []);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;p&gt;Theme: {theme}&lt;/p&gt;</pre><pre>      &lt;button onClick={() =&gt; setCount((value) =&gt; value + 1)}&gt;<br>        Increase Count<br>      &lt;/button&gt;</pre><pre>      &lt;button<br>        onClick={() =&gt;<br>          setTheme((value) =&gt;<br>            value === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;<br>          )<br>        }<br>      &gt;<br>        Change Theme<br>      &lt;/button&gt;</pre><pre>      &lt;ChildButton onClick={handleChildClick} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default Parent;</pre><p>Because handleChildClick has no reactive dependencies, React can reuse its reference across parent renders. With memo, the child can skip a render when its props remain equal.</p><p>The child can still render for other reasons, such as its own state changing or a Context it consumes updating. useCallback does not prevent every possible render.</p><h3>4. When dependencies change</h3><p>Suppose a callback uses a name variable:</p><pre>const greet = useCallback(() =&gt; {<br>  console.log(`Hello, ${name}`);<br>}, [name]);</pre><p>The dependency array includes name because the callback reads it.</p><p>When name changes, React returns a callback that captures the updated value.</p><p>Leaving name out of the dependency array can cause the callback to use a stale value.</p><h3>5. useCallback versus useMemo</h3><p>They are related but return different things.</p><pre>const calculateTotal = useCallback((price, quantity) =&gt; {<br>  return price * quantity;<br>}, []);</pre><p>This caches a function.</p><pre>const total = useMemo(() =&gt; {<br>  return price * quantity;<br>}, [price, quantity]);</pre><p>This caches the result of a calculation.</p><p>A useful way to remember the difference:</p><ul><li>useCallback caches a function reference.</li><li>useMemo caches a calculated value.</li></ul><h3>6. Common useCallback mistakes</h3><p><strong>Mistake 1: Wrapping every function in useCallback</strong></p><p>A simple event handler often doesn’t need it. Memoization should solve a real problem, not make every component more complicated.</p><p><strong>Mistake 2: Forgetting dependencies</strong></p><p>If the callback uses reactive values, include them or restructure the code to avoid needing them.</p><p><strong>Mistake 3: Expecting useCallback to make the function faster</strong></p><p>The Hook does not make the body of the function execute faster. It can help avoid unnecessary updates caused by changing function references.</p><p><strong>Mistake 4: Using useCallback without understanding the child</strong></p><p>If a child isn’t memoized and nothing else benefits from a stable callback, useCallback may not provide a useful improvement.</p><h3>7. Practice task: Create a memoized task button</h3><p>Create a parent component with a counter and a child button.</p><p>Requirements:</p><ol><li>The parent has a counter.</li><li>The child receives an onAdd callback.</li><li>Wrap the child component with memo.</li><li>Use useCallback for the callback.</li><li>Add a console message to observe when the child renders.</li></ol><h3>Solution</h3><pre>import { memo, useCallback, useState } from &quot;react&quot;;</pre><pre>const AddButton = memo(function AddButton({ onAdd }) {<br>  console.log(&quot;AddButton rendered&quot;);</pre><pre>  return &lt;button onClick={onAdd}&gt;Add One&lt;/button&gt;;<br>});</pre><pre>function App() {<br>  const [count, setCount] = useState(0);<br>  const [other, setOther] = useState(0);</pre><pre>  const addOne = useCallback(() =&gt; {<br>    setCount((previous) =&gt; previous + 1);<br>  }, []);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Count: {count}&lt;/h2&gt;<br>      &lt;p&gt;Other value: {other}&lt;/p&gt;</pre><pre>      &lt;AddButton onAdd={addOne} /&gt;</pre><pre>      &lt;button onClick={() =&gt; setOther((value) =&gt; value + 1)}&gt;<br>        Update Other Value<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>When the unrelated value changes, the callback reference stays stable, allowing the memoized child to skip a render if its other props remain unchanged.</p><h3>Final thoughts</h3><p>useCallback is most useful when function identity matters—for example, when passing callbacks to memoized children or using them as dependencies in other Hooks.</p><p>Use it deliberately. Stable references can help with performance, but readable code and correct dependencies matter more than memoizing everything.</p><p><strong>Next article:</strong> React useLayoutEffect Hook — Measuring the DOM Before the Browser Paints.</p><p><em>Official reference: </em><a href="https://react.dev/reference/react/useCallback"><em>React — useCallback</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b355ecece80b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React useMemo Explained: Optimize Performance Without Overcomplicating Your Code]]></title>
            <link>https://medium.com/@dhruvil.unofficial/react-usememo-explained-optimize-performance-without-overcomplicating-your-code-025489d65546?source=rss-c2f1b6068e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/025489d65546</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Dhruvil Bhuva]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 18:12:21 GMT</pubDate>
            <atom:updated>2026-10-22T18:12:21.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUsjtqQTIYbTh684ITye7A.png" /></figure><p>As a React application grows, some components perform calculations that take noticeable time. Others filter hundreds or thousands of records whenever the component renders.</p><p>It is tempting to optimize everything immediately, but that can make code harder to read without improving performance.</p><p>The useMemo Hook gives you a way to cache the result of a calculation between renders when its dependencies haven&#39;t changed.</p><p>Let’s look at how it works, when it helps, and when it is unnecessary.</p><h3>1. What is useMemo?</h3><p>useMemo is a React Hook that caches the result of a calculation between renders.</p><p>Its syntax is:</p><pre>import { useMemo } from &quot;react&quot;;</pre><pre>const result = useMemo(() =&gt; {<br>  return calculateSomething();<br>}, [dependencies]);</pre><p>React runs the calculation during rendering. On later renders, it can reuse the previous result if the dependencies haven’t changed.</p><p>For example:</p><pre>const total = useMemo(() =&gt; price * quantity, [price, quantity]);</pre><p>The calculation is simple here, so memoization probably isn’t necessary. It illustrates the syntax, but real benefits are more likely when a calculation is expensive or when stable object identity matters to a memoized child.</p><h3>2. A practical example: Filtering products</h3><p>Imagine a product list with a search field.</p><pre>import { useMemo, useState } from &quot;react&quot;;</pre><pre>const products = [<br>  { id: 1, name: &quot;Keyboard&quot;, price: 2500 },<br>  { id: 2, name: &quot;Mouse&quot;, price: 850 },<br>  { id: 3, name: &quot;Monitor&quot;, price: 20000 },<br>  { id: 4, name: &quot;Headphones&quot;, price: 8000 },<br>];</pre><pre>function ProductSearch() {<br>  const [search, setSearch] = useState(&quot;&quot;);<br>  const [count, setCount] = useState(0);</pre><pre>  const filteredProducts = useMemo(() =&gt; {<br>    console.log(&quot;Filtering products...&quot;);</pre><pre>    const query = search.toLowerCase();</pre><pre>    return products.filter((product) =&gt;<br>      product.name.toLowerCase().includes(query)<br>    );<br>  }, [search]);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Product Search&lt;/h2&gt;</pre><pre>      &lt;input<br>        value={search}<br>        onChange={(event) =&gt; setSearch(event.target.value)}<br>        placeholder=&quot;Search products&quot;<br>      /&gt;</pre><pre>      &lt;button onClick={() =&gt; setCount((value) =&gt; value + 1)}&gt;<br>        Unrelated count: {count}<br>      &lt;/button&gt;</pre><pre>      &lt;ul&gt;<br>        {filteredProducts.map((product) =&gt; (<br>          &lt;li key={product.id}&gt;<br>            {product.name} — ${product.price}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default ProductSearch;</pre><p>When search changes, React recalculates the filtered list. When only count changes, React can reuse the cached filtered result.</p><p>The console message helps you observe the calculation. Remember that development Strict Mode may invoke render-time calculations more than once to help detect impure code, so console output is not a reliable benchmark.</p><h3>3. Why dependencies matter</h3><p>The dependency array tells React which values the calculation depends on.</p><pre>const filtered = useMemo(() =&gt; {<br>  return products.filter((product) =&gt;<br>    product.name.includes(search)<br>  );<br>}, [products, search]);</pre><p>If either dependency changes, React recalculates the result.</p><p>If you omit a dependency, the calculation can use outdated values. Include the reactive values used by the calculation.</p><p>Also, don’t treat memoization as permanent storage. React documents useMemo as a performance optimization, not a guarantee that the cached value will never be discarded.</p><h3>4. useMemo versus useState</h3><p>These Hooks solve different problems.</p><ul><li>useState stores a value that can be updated over time.</li><li>useMemo caches a calculation result that can be recomputed from its inputs.</li></ul><p>If a value can be calculated cheaply during rendering, you often don’t need either Hook.</p><p>For example:</p><pre>const fullName = `${firstName} ${lastName}`;</pre><p>This is simpler than memoizing a string concatenation.</p><h3>5. Common useMemo mistakes</h3><p><strong>Mistake 1: Memoizing every calculation</strong></p><p>Memoization adds complexity and has its own cost. Use it when there is a meaningful performance reason.</p><p><strong>Mistake 2: Forgetting dependencies</strong></p><p>A memoized calculation must use current values. An incomplete dependency list can produce stale results.</p><p><strong>Mistake 3: Using it to fix incorrect logic</strong></p><p>If a component produces the wrong result, first fix the underlying logic. Memoization won’t make incorrect calculations correct.</p><p><strong>Mistake 4: Expecting useMemo to prevent all re-renders</strong></p><p>It caches a value. It does not automatically prevent the component itself from rendering again.</p><h3>6. Practice task: Build a score calculator</h3><p>Create a component with:</p><ol><li>An array of test scores.</li><li>A button that adds a new score.</li><li>A displayed average score.</li><li>A separate counter that can change without changing the scores.</li><li>useMemo to calculate the average from the score array.</li></ol><h3>Solution</h3><pre>import { useMemo, useState } from &quot;react&quot;;</pre><pre>function ScoreCalculator() {<br>  const [scores, setScores] = useState([70, 85, 90]);<br>  const [clicks, setClicks] = useState(0);</pre><pre>  const average = useMemo(() =&gt; {<br>    if (scores.length === 0) return 0;</pre><pre>    const total = scores.reduce(<br>      (sum, score) =&gt; sum + score,<br>      0<br>    );</pre><pre>    return total / scores.length;<br>  }, [scores]);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Score Calculator&lt;/h2&gt;</pre><pre>      &lt;p&gt;Scores: {scores.join(&quot;, &quot;)}&lt;/p&gt;<br>      &lt;p&gt;Average: {average.toFixed(2)}&lt;/p&gt;</pre><pre>      &lt;button<br>        onClick={() =&gt;<br>          setScores((previous) =&gt; [...previous, 80])<br>        }<br>      &gt;<br>        Add Score<br>      &lt;/button&gt;</pre><pre>      &lt;button onClick={() =&gt; setClicks((value) =&gt; value + 1)}&gt;<br>        Clicks: {clicks}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default ScoreCalculator;</pre><p>The average is recalculated when the scores array changes. The unrelated counter doesn&#39;t change the dependency, so React can reuse the cached average.</p><p>With a tiny array, the performance benefit is negligible. The example is mainly for learning how dependencies work.</p><h3>Final thoughts</h3><p>useMemo can help avoid repeated expensive calculations and can preserve a value&#39;s identity when that matters to another optimization.</p><p>But don’t reach for it automatically. Start with readable code, measure performance when necessary, and memoize where it provides a real benefit.</p><p><strong>Next article:</strong> React useCallback Hook — Why Function References Matter.</p><p><em>Official reference: </em><a href="https://react.dev/reference/react/useMemo"><em>React — useMemo</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=025489d65546" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React useReducer Hook Explained: Manage Complex State with Confidence]]></title>
            <link>https://medium.com/@dhruvil.unofficial/react-usereducer-hook-explained-manage-complex-state-with-confidence-efe3821db328?source=rss-c2f1b6068e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/efe3821db328</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Dhruvil Bhuva]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 18:32:15 GMT</pubDate>
            <atom:updated>2026-10-22T11:20:04.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSXv2DaWK3zF9BG8obGDeA.png" /></figure><p>A Practical Guide to Managing Complex State</p><p>At first, useState can handle almost everything you build in a small React application. A counter, a form, a dropdown, or a simple task list doesn&#39;t need much state logic.</p><p>But imagine building a shopping cart.</p><p>You need to add products, remove products, change quantities, and clear the cart. As the application grows, the logic for each operation can become scattered across several event handlers.</p><p>This is where useReducer can help.</p><p>Instead of placing all the update logic in separate handlers, you define how each action transforms the current state.</p><h3>1. What is useReducer?</h3><p>useReducer is a React Hook for managing state through a reducer function.</p><p>Its basic syntax is:</p><pre>const [state, dispatch] = useReducer(reducer, initialState);</pre><p>Here:</p><ul><li>state is the current state.</li><li>dispatch sends an action to the reducer.</li><li>reducer calculates the next state.</li><li>initialState provides the initial state value.</li></ul><p>A reducer receives the current state and an action, then returns the next state.</p><pre>function reducer(state, action) {<br>  switch (action.type) {<br>    case &quot;increment&quot;:<br>      return state + 1;</pre><pre>    case &quot;decrement&quot;:<br>      return state - 1;</pre><pre>    default:<br>      return state;<br>  }<br>}</pre><p>The reducer should be pure: it should not directly mutate existing state or perform side effects such as network requests.</p><h3>2. Build a counter with useReducer</h3><p>Let’s start with a simple example.</p><pre>import { useReducer } from &quot;react&quot;;</pre><pre>function reducer(state, action) {<br>  switch (action.type) {<br>    case &quot;increment&quot;:<br>      return state + 1;</pre><pre>    case &quot;decrement&quot;:<br>      return state - 1;</pre><pre>    case &quot;reset&quot;:<br>      return 0;</pre><pre>    default:<br>      return state;<br>  }<br>}</pre><pre>function Counter() {<br>  const [count, dispatch] = useReducer(reducer, 0);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Count: {count}&lt;/h2&gt;</pre><pre>      &lt;button onClick={() =&gt; dispatch({ type: &quot;increment&quot; })}&gt;<br>        Increase<br>      &lt;/button&gt;</pre><pre>      &lt;button onClick={() =&gt; dispatch({ type: &quot;decrement&quot; })}&gt;<br>        Decrease<br>      &lt;/button&gt;</pre><pre>      &lt;button onClick={() =&gt; dispatch({ type: &quot;reset&quot; })}&gt;<br>        Reset<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default Counter;</pre><p>When you click Increase, the component dispatches an action with the type &quot;increment&quot;.</p><p>The reducer receives the current state and that action, calculates the next value, and returns it. React then updates the component.</p><p>The benefit is that all the counter’s state-transition rules live in one place.</p><h3>3. Actions can carry additional data</h3><p>Real applications need more than increment and decrement actions.</p><p>For example, a shopping cart needs to know which product to add.</p><p>An action can contain a payload or other fields:</p><pre>dispatch({<br>  type: &quot;add&quot;,<br>  payload: {<br>    id: 1,<br>    name: &quot;Keyboard&quot;,<br>    price: 50,<br>  },<br>});</pre><p>The reducer can use that information to calculate the next state.</p><p>This makes actions descriptive: they explain what happened rather than manually changing the state wherever a button is clicked.</p><h3>4. Real-world example: A shopping cart</h3><p>Let’s build a small cart with add, remove, and quantity operations.</p><pre>import { useReducer } from &quot;react&quot;;</pre><pre>const products = [<br>  { id: 1, name: &quot;Keyboard&quot;, price: 50 },<br>  { id: 2, name: &quot;Mouse&quot;, price: 25 },<br>  { id: 3, name: &quot;Monitor&quot;, price: 200 },<br>];</pre><pre>function cartReducer(state, action) {<br>  switch (action.type) {<br>    case &quot;add&quot;: {<br>      const existing = state.find(<br>        (item) =&gt; item.id === action.product.id<br>      );</pre><pre>      if (existing) {<br>        return state.map((item) =&gt;<br>          item.id === action.product.id<br>            ? { ...item, quantity: item.quantity + 1 }<br>            : item<br>        );<br>      }</pre><pre>      return [<br>        ...state,<br>        { ...action.product, quantity: 1 },<br>      ];<br>    }</pre><pre>    case &quot;remove&quot;:<br>      return state.filter((item) =&gt; item.id !== action.id);</pre><pre>    case &quot;increase&quot;:<br>      return state.map((item) =&gt;<br>        item.id === action.id<br>          ? { ...item, quantity: item.quantity + 1 }<br>          : item<br>      );</pre><pre>    case &quot;decrease&quot;:<br>      return state<br>        .map((item) =&gt;<br>          item.id === action.id<br>            ? { ...item, quantity: item.quantity - 1 }<br>            : item<br>        )<br>        .filter((item) =&gt; item.quantity &gt; 0);</pre><pre>    case &quot;clear&quot;:<br>      return [];</pre><pre>    default:<br>      return state;<br>  }<br>}</pre><pre>function ShoppingCart() {<br>  const [cart, dispatch] = useReducer(cartReducer, []);</pre><pre>  const total = cart.reduce(<br>    (sum, item) =&gt; sum + item.price * item.quantity,<br>    0<br>  );</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Products&lt;/h2&gt;</pre><pre>      {products.map((product) =&gt; (<br>        &lt;div key={product.id}&gt;<br>          &lt;span&gt;<br>            {product.name} — ${product.price}<br>          &lt;/span&gt;</pre><pre>          &lt;button<br>            onClick={() =&gt; dispatch({ type: &quot;add&quot;, product })}<br>          &gt;<br>            Add to Cart<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      ))}</pre><pre>      &lt;h2&gt;Your Cart&lt;/h2&gt;</pre><pre>      {cart.length === 0 &amp;&amp; &lt;p&gt;Your cart is empty.&lt;/p&gt;}</pre><pre>      {cart.map((item) =&gt; (<br>        &lt;div key={item.id}&gt;<br>          &lt;p&gt;<br>            {item.name} — ${item.price} × {item.quantity}<br>          &lt;/p&gt;</pre><pre>          &lt;button<br>            onClick={() =&gt;<br>              dispatch({ type: &quot;decrease&quot;, id: item.id })<br>            }<br>          &gt;<br>            -<br>          &lt;/button&gt;</pre><pre>          &lt;button<br>            onClick={() =&gt;<br>              dispatch({ type: &quot;increase&quot;, id: item.id })<br>            }<br>          &gt;<br>            +<br>          &lt;/button&gt;</pre><pre>          &lt;button<br>            onClick={() =&gt;<br>              dispatch({ type: &quot;remove&quot;, id: item.id })<br>            }<br>          &gt;<br>            Remove<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      ))}</pre><pre>      &lt;h3&gt;Total: ${total}&lt;/h3&gt;</pre><pre>      &lt;button onClick={() =&gt; dispatch({ type: &quot;clear&quot; })}&gt;<br>        Clear Cart<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default ShoppingCart;</pre><h3>What makes this example useful?</h3><p>The reducer owns the rules for adding and removing products. The component handles rendering and dispatching actions.</p><p>Notice that the reducer uses map, filter, and the spread syntax instead of mutating the existing array or objects.</p><p>The total is calculated from the cart instead of being stored as a second state variable. That avoids keeping two values synchronized unnecessarily.</p><h3>5. useState or useReducer?</h3><p>Use useState when updates are straightforward and easy to understand.</p><p>Consider useReducer when:</p><ul><li>Several actions update the same state.</li><li>Update logic is becoming difficult to maintain.</li><li>The next state depends on the type of action.</li><li>You want state-transition rules in one place.</li><li>The state is an object or collection with related update operations.</li></ul><p>You don’t need to replace every useState call with useReducer. Both Hooks are useful, and either can be the right choice depending on the problem.</p><h3>6. Common useReducer mistakes</h3><p><strong>Mistake 1: Mutating the existing state</strong></p><p>Don’t call methods that modify the current state array or object directly. Return a new state instead.</p><p><strong>Mistake 2: Forgetting the default case</strong></p><p>A reducer should return the current state for an action type it doesn’t handle, or use an explicit error strategy appropriate to the application.</p><p><strong>Mistake 3: Performing side effects inside the reducer</strong></p><p>Keep reducers pure. Perform network requests and other side effects in event handlers, Effects, or suitable application logic.</p><p><strong>Mistake 4: Making the reducer unnecessarily complicated</strong></p><p>A reducer is useful when it makes the code easier to understand. For a single boolean toggle, useState is usually simpler.</p><h3>7. Practice task: Build a task manager</h3><p>Create a task manager with these requirements:</p><ol><li>Add a task using an action.</li><li>Mark a task as completed.</li><li>Delete a task.</li><li>Clear all tasks.</li><li>Store each task with a unique ID and a completed boolean.</li></ol><p>Try to write the reducer before writing the UI. Define the action types first, then decide how each action changes the state.</p><h3>Solution approach</h3><p>Start with a reducer like this:</p><pre>function taskReducer(state, action) {<br>  switch (action.type) {<br>    case &quot;add&quot;:<br>      return [<br>        ...state,<br>        {<br>          id: action.task.id,<br>          text: action.task.text,<br>          completed: false,<br>        },<br>      ];</pre><pre>    case &quot;toggle&quot;:<br>      return state.map((task) =&gt;<br>        task.id === action.id<br>          ? { ...task, completed: !task.completed }<br>          : task<br>      );</pre><pre>    case &quot;delete&quot;:<br>      return state.filter((task) =&gt; task.id !== action.id);</pre><pre>    case &quot;clear&quot;:<br>      return [];</pre><pre>    default:<br>      return state;<br>  }<br>}</pre><p>Use it with useReducer(taskReducer, []), and dispatch the corresponding actions from your buttons.</p><p>For a production application, generate task IDs in the event handler or another suitable place, not inside the reducer. That keeps the reducer pure and predictable.</p><h3>Final thoughts</h3><p>useReducer isn&#39;t about making state management more complicated. It&#39;s about giving related state updates a clear structure.</p><p>If your event handlers are becoming full of conditional update logic, try moving those rules into a reducer. If the logic is simple, stay with useState.</p><p>The best choice is the one that makes your code easier to understand and maintain.</p><p><strong>Next article:</strong> React useMemo Hook — Optimize Expensive Calculations Without Guesswork.</p><p><em>Official reference: </em><a href="https://react.dev/reference/react/useReducer"><em>React — useReducer</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efe3821db328" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React useRef Hook Explained: DOM Access, Persistent Values, and Common Mistakes]]></title>
            <link>https://medium.com/@dhruvil.unofficial/react-useref-hook-explained-dom-access-persistent-values-and-common-mistakes-a885192e8478?source=rss-c2f1b6068e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a885192e8478</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dhruvil Bhuva]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 18:21:49 GMT</pubDate>
            <atom:updated>2026-10-22T11:24:11.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWTNW1RZtv9EZubCi0RFiw.png" /></figure><p>Most React developers learn useState first because it updates the UI. But what if you need to store a value between renders without triggering another render whenever that value changes?</p><p>Or what if you want to focus an input field programmatically?</p><p>That is where useRef comes in.</p><p>Although many tutorials introduce it only as a way to access DOM elements, useRef has another important use: keeping a mutable value between renders without using state.</p><p>Let’s explore both.</p><h3>1. What is useRef?</h3><p>useRef is a React Hook that returns an object with a current property.</p><pre>import { useRef } from &quot;react&quot;;</pre><pre>const reference = useRef(initialValue);</pre><p>You can access or update its value using:</p><pre>reference.current</pre><p>React preserves the same ref object between renders of the component.</p><p>Unlike state, changing reference.current does not trigger a render.</p><h3>2. Example: Focus an input automatically</h3><p>Imagine a login form. When the user clicks a button, you want the cursor to move directly into the username field.</p><pre>import { useRef } from &quot;react&quot;;</pre><pre>function LoginForm() {<br>  const inputRef = useRef(null);</pre><pre>  function focusInput() {<br>    inputRef.current?.focus();<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        ref={inputRef}<br>        type=&quot;text&quot;<br>        placeholder=&quot;Enter username&quot;<br>      /&gt;</pre><pre>      &lt;button onClick={focusInput}&gt;<br>        Focus Input<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default LoginForm;</pre><h3>How it works</h3><ol><li>useRef(null) creates a ref object.</li><li>The ref prop connects the object to the input DOM element.</li><li>After React attaches the element, inputRef.current refers to that input.</li><li>Clicking the button calls its focus() method.</li></ol><p>The optional chaining operator (?.) prevents an error if the ref is currently null.</p><p>This technique is useful for search bars, forms, dialogs, and other interfaces where controlling focus improves usability.</p><h3>3. Store a value without triggering a render</h3><p>Sometimes a component needs to keep track of something that doesn’t directly determine the displayed UI.</p><p>For example, you might want to count how many times a button has been clicked without displaying that count.</p><pre>import { useRef, useState } from &quot;react&quot;;</pre><pre>function ClickTracker() {<br>  const clickCount = useRef(0);<br>  const [message, setMessage] = useState(&quot;Click the button&quot;);</pre><pre>  function handleClick() {<br>    clickCount.current += 1;<br>    setMessage(&quot;Button clicked!&quot;);<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;{message}&lt;/p&gt;<br>      &lt;button onClick={handleClick}&gt;Click Me&lt;/button&gt;<br>      &lt;button onClick={() =&gt; alert(clickCount.current)}&gt;<br>        Show Click Count<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default ClickTracker;</pre><p>The ref stores the count between renders. Updating it does not cause a render by itself. The state update changes the message and triggers a render.</p><p>One important distinction: if you need the count to update visibly every time the button is clicked, use state instead.</p><h3>4. useRef versus useState</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lznCrE741FwmNcK7q6guyA.png" /></figure><p>Neither Hook is universally better. Choose based on whether a value should cause the UI to update.</p><h3>5. Store a timer ID with useRef</h3><p>Suppose you want to start and stop a timer using buttons.</p><pre>import { useRef, useState } from &quot;react&quot;;</pre><pre>function Stopwatch() {<br>  const [seconds, setSeconds] = useState(0);<br>  const timerRef = useRef(null);</pre><pre>  function startTimer() {<br>    if (timerRef.current !== null) return;</pre><pre>    timerRef.current = setInterval(() =&gt; {<br>      setSeconds((previous) =&gt; previous + 1);<br>    }, 1000);<br>  }</pre><pre>  function stopTimer() {<br>    clearInterval(timerRef.current);<br>    timerRef.current = null;<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Seconds: {seconds}&lt;/h2&gt;<br>      &lt;button onClick={startTimer}&gt;Start&lt;/button&gt;<br>      &lt;button onClick={stopTimer}&gt;Stop&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default Stopwatch;</pre><p>The ref stores the interval ID so the event handlers can access it without making it part of the UI state.</p><p>For a production component, also clean up the interval when the component unmounts. You could use an Effect for that cleanup.</p><h3>6. Common useRef mistakes</h3><p><strong>Mistake 1: Expecting a ref update to refresh the screen</strong></p><p>Changing ref.current does not cause React to render again.</p><p><strong>Mistake 2: Accessing a DOM ref before it is attached</strong></p><p>A DOM ref can be null, particularly before the element mounts or after it is removed.</p><p><strong>Mistake 3: Using a ref for information that must be displayed</strong></p><p>If a value needs to update the UI, state is generally the right tool.</p><p><strong>Mistake 4: Reading or writing refs during rendering without a good reason</strong></p><p>Treat refs as mutable storage for event handlers and Effects. Avoid reading or writing mutable refs during rendering in ways that make rendering impure.</p><h3>7. Practice task: Build an input focus tool</h3><p>Create a component that:</p><ol><li>Displays an input field.</li><li>Focuses the input when a button is clicked.</li><li>Clears the input when another button is clicked.</li><li>Uses useRef to access the input element.</li></ol><h3>Solution</h3><pre>import { useRef } from &quot;react&quot;;</pre><pre>function InputTool() {<br>  const inputRef = useRef(null);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;input ref={inputRef} placeholder=&quot;Enter text&quot; /&gt;</pre><pre>      &lt;button onClick={() =&gt; inputRef.current?.focus()}&gt;<br>        Focus<br>      &lt;/button&gt;</pre><pre>      &lt;button<br>        onClick={() =&gt; {<br>          if (inputRef.current) {<br>            inputRef.current.value = &quot;&quot;;<br>          }<br>        }}<br>      &gt;<br>        Clear<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default InputTool;</pre><p>This example demonstrates direct DOM access. For a fully controlled input, storing its text in state is usually preferable, but a ref is useful for practicing DOM interactions.</p><h3>Final thoughts</h3><p>useRef is more than a DOM-access tool. It gives you a place to store information that must persist between renders but doesn&#39;t itself need to trigger a render when changed.</p><p>Remember the simple distinction: use state for changing UI data, and use refs for DOM references or mutable values that don’t need to drive the UI.</p><p><strong>Next article:</strong> <a href="https://medium.com/@dhruvil.unofficial/react-usereducer-hook-explained-manage-complex-state-with-confidence-efe3821db328?sharedUserId=dhruvil.unofficial">React </a><a href="https://medium.com/@dhruvil.unofficial/react-usereducer-hook-explained-manage-complex-state-with-confidence-efe3821db328?sharedUserId=dhruvil.unofficial">useReducer Hook — Managing Complex State Without Losing Control.</a></p><p><em>Official reference: </em><a href="https://react.dev/reference/react/useRef"><em>React — useRef</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a885192e8478" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React useContext Hook Explained: Share Data Without Prop Drilling]]></title>
            <link>https://medium.com/@dhruvil.unofficial/react-usecontext-hook-explained-share-data-without-prop-drilling-8b766ca7b5ba?source=rss-c2f1b6068e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b766ca7b5ba</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Dhruvil Bhuva]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 18:06:44 GMT</pubDate>
            <atom:updated>2026-10-22T11:33:47.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYp-UmY0pYi1wQpqtUyfEA.png" /></figure><p>Understand context with simple examples and practical component patterns.</p><p>Imagine building a dashboard with a navigation bar, sidebar, profile menu, and settings page. Several components need access to the current user’s information or the selected theme.</p><p>You could pass the same data through every component, even when the intermediate components don’t need it. As an application grows, that can make the component tree harder to maintain.</p><p>React Context offers another approach.</p><p>In this article, we’ll explore the useContext Hook, build a working theme switcher, and understand when Context is useful—and when it isn&#39;t.</p><h3>1. What is useContext?</h3><p>useContext is a React Hook that lets a component read a value from a Context.</p><p>Context is useful when multiple components need access to shared information, such as:</p><ul><li>The current theme</li><li>The authenticated user’s profile</li><li>Locale or language preferences</li><li>Application-wide settings</li></ul><p>First, create a Context:</p><pre>import { createContext } from &quot;react&quot;;</pre><pre>const ThemeContext = createContext(&quot;light&quot;);</pre><pre>export default ThemeContext;</pre><p>Then a component can read its value using useContext:</p><pre>import { useContext } from &quot;react&quot;;<br>import ThemeContext from &quot;./ThemeContext&quot;;</pre><pre>function Heading() {<br>  const theme = useContext(ThemeContext);</pre><pre>  return &lt;h1&gt;Current theme: {theme}&lt;/h1&gt;;<br>}</pre><p>If no matching provider exists above the component, React uses the default value supplied to createContext.</p><h3>2. Why useContext exists</h3><p>Consider this component structure:</p><pre>App<br> └── Dashboard<br>      └── Sidebar<br>           └── UserProfile</pre><p>Suppose App has the current user&#39;s information, but only UserProfile needs it.</p><p>Without Context, you might pass the user through Dashboard and Sidebar just to reach UserProfile. This is often called <strong>prop drilling</strong>.</p><p>Context allows the relevant component to read the value directly from a provider higher in the tree.</p><p>Context doesn’t eliminate props. Props are still a good choice when data naturally flows from a parent to its direct children. Context is useful when many components need the same information.</p><h3>3. Build a complete theme switcher</h3><p>Let’s create a simple theme system.</p><h3>Step 1: Create the Context</h3><p>Create ThemeContext.jsx:</p><pre>import { createContext } from &quot;react&quot;;</pre><pre>const ThemeContext = createContext(&quot;light&quot;);</pre><pre>export default ThemeContext;</pre><h3>Step 2: Create the provider</h3><p>Create App.jsx:</p><pre>import { useState } from &quot;react&quot;;<br>import ThemeContext from &quot;./ThemeContext&quot;;<br>import Dashboard from &quot;./Dashboard&quot;;</pre><pre>function App() {<br>  const [theme, setTheme] = useState(&quot;light&quot;);</pre><pre>  function toggleTheme() {<br>    setTheme((previous) =&gt;<br>      previous === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;<br>    );<br>  }</pre><pre>  return (<br>    &lt;ThemeContext value={theme}&gt;<br>      &lt;Dashboard<br>        theme={theme}<br>        onToggleTheme={toggleTheme}<br>      /&gt;<br>    &lt;/ThemeContext&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>This provider syntax works in React 19 and newer. In older React versions, use &lt;ThemeContext.Provider value={theme}&gt;.</p><h3>Step 3: Create a component that reads Context</h3><p>Create Dashboard.jsx:</p><pre>import { useContext } from &quot;react&quot;;<br>import ThemeContext from &quot;./ThemeContext&quot;;</pre><pre>function Dashboard({ onToggleTheme }) {<br>  const theme = useContext(ThemeContext);</pre><pre>  const styles = {<br>    background: theme === &quot;dark&quot; ? &quot;#222&quot; : &quot;#fff&quot;,<br>    color: theme === &quot;dark&quot; ? &quot;#fff&quot; : &quot;#222&quot;,<br>    padding: &quot;24px&quot;,<br>    borderRadius: &quot;8px&quot;,<br>  };</pre><pre>  return (<br>    &lt;div style={styles}&gt;<br>      &lt;h2&gt;Dashboard&lt;/h2&gt;<br>      &lt;p&gt;The current theme is {theme}.&lt;/p&gt;</pre><pre>      &lt;button onClick={onToggleTheme}&gt;<br>        Switch Theme<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default Dashboard;</pre><p>Now clicking the button changes the state in App. The Context provider receives the new value, and the consuming component renders with the updated theme.</p><p>Notice that Dashboard still receives the event handler as a prop. That&#39;s intentional: Context is not a rule that says every value must be shared through Context.</p><h3>4. How Context updates work</h3><p>When a provider receives a different value, React updates components that consume that Context.</p><p>This is convenient, but it also means Context should be designed thoughtfully.</p><p>For example, placing frequently changing data into one giant Context may cause many consumers to re-render when they receive a new value.</p><p>For larger applications, consider splitting unrelated Contexts, keeping provider values stable where appropriate, or using a state-management solution when the needs become more complex.</p><h3>5. Common useContext mistakes</h3><p><strong>Mistake 1: Forgetting the provider</strong></p><p>If a provider is missing, useContext returns the Context&#39;s default value. That can make a component appear to work while it is using the wrong data.</p><p><strong>Mistake 2: Expecting Context to replace every prop</strong></p><p>Props are often simpler for data used by just a few closely related components.</p><p><strong>Mistake 3: Putting all application state into one Context</strong></p><p>Group values by purpose. Authentication, theme settings, and rapidly changing page data may have different update patterns.</p><p><strong>Mistake 4: Forgetting provider placement</strong></p><p>A provider only affects components below it in the rendered tree. A component cannot read a provider that exists only inside its own returned JSX.</p><h3>6. Practice task: Build a language selector</h3><p>Create a Context that stores the selected language.</p><p>Requirements:</p><ol><li>Create a LanguageContext.</li><li>Start with &quot;English&quot;.</li><li>Add a button that switches between English and Gujarati.</li><li>Display the selected language in a separate child component.</li><li>Make the child read the language using useContext.</li></ol><h3>Solution</h3><pre>import { createContext, useContext, useState } from &quot;react&quot;;</pre><pre>const LanguageContext = createContext(&quot;English&quot;);</pre><pre>function LanguageDisplay() {<br>  const language = useContext(LanguageContext);</pre><pre>  return &lt;h2&gt;Selected language: {language}&lt;/h2&gt;;<br>}</pre><pre>function App() {<br>  const [language, setLanguage] = useState(&quot;English&quot;);</pre><pre>  function changeLanguage() {<br>    setLanguage((previous) =&gt;<br>      previous === &quot;English&quot; ? &quot;Gujarati&quot; : &quot;English&quot;<br>    );<br>  }</pre><pre>  return (<br>    &lt;LanguageContext value={language}&gt;<br>      &lt;div&gt;<br>        &lt;LanguageDisplay /&gt;</pre><pre>        &lt;button onClick={changeLanguage}&gt;<br>          Change Language<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/LanguageContext&gt;<br>  );<br>}</pre><pre>export default App;</pre><h3>Final thoughts</h3><p>useContext is useful when data needs to be accessible across different parts of a component tree. It can make themes, user settings, and localization easier to manage.</p><p>The important part isn’t removing every prop. It’s choosing a clear way to pass each piece of data.</p><p><strong>Next article:</strong> <a href="https://medium.com/@dhruvil.unofficial/react-useref-hook-explained-dom-access-persistent-values-and-common-mistakes-a885192e8478?sharedUserId=dhruvil.unofficial">React </a><a href="https://medium.com/@dhruvil.unofficial/react-useref-hook-explained-dom-access-persistent-values-and-common-mistakes-a885192e8478?sharedUserId=dhruvil.unofficial">useRef Hook — Access DOM Elements and Store Values Without Re-rendering.</a></p><p><em>Official reference: </em><a href="https://react.dev/reference/react/useContext"><em>React — useContext</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b766ca7b5ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React useEffect Hook Explained: Dependencies, Cleanup, and Real-World Examples]]></title>
            <link>https://medium.com/@dhruvil.unofficial/react-useeffect-hook-explained-dependencies-cleanup-and-real-world-examples-71d16ebbf3ee?source=rss-c2f1b6068e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/71d16ebbf3ee</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Dhruvil Bhuva]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 17:53:57 GMT</pubDate>
            <atom:updated>2026-10-22T11:37:42.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tx6lpTBG27dcE0dJ174Gfg.png" /></figure><p>Learn how to handle effects, fetch data, and avoid common dependency mistakes.</p><p>Have you ever wondered how to fetch data when a page opens, listen for browser events, or start a timer inside a React component?</p><p>These tasks involve more than simply displaying data. They require your component to synchronize with something outside React.</p><p>That’s where useEffect becomes useful.</p><p>It is also one of the Hooks that causes the most confusion for beginners. Dependency arrays, repeated API calls, cleanup functions, and unexpected behavior can make it seem harder than it really is.</p><p>Let’s understand it step by step.</p><h3>1. What is useEffect?</h3><p>useEffect is a React Hook that lets a component synchronize with an external system.</p><p>External systems include:</p><ul><li>Network connections and subscriptions</li><li>Browser event listeners</li><li>Timers</li><li>Third-party widgets</li><li>Other systems that exist outside React’s rendering process</li></ul><p>Basic syntax:</p><pre>import { useEffect } from &quot;react&quot;;</pre><pre>useEffect(() =&gt; {<br>  // Synchronize with an external system.</pre><pre>  return () =&gt; {<br>    // Clean up when necessary.<br>  };<br>}, [dependencies]);</pre><p>The cleanup function is optional. The dependency array controls when React needs to re-synchronize the Effect.</p><h3>2. Your first useEffect example</h3><p>Suppose you want to log a message after the component appears.</p><pre>import { useEffect } from &quot;react&quot;;</pre><pre>function Welcome() {<br>  useEffect(() =&gt; {<br>    console.log(&quot;Welcome component is active&quot;);<br>  }, []);</pre><pre>  return &lt;h2&gt;Welcome to React!&lt;/h2&gt;;<br>}</pre><pre>export default Welcome;</pre><p>The empty dependency array means this Effect doesn’t depend on changing reactive values from the component. React runs it after the component mounts.</p><p>One important detail: in development Strict Mode, React may run an extra setup-and-cleanup cycle to help detect bugs. Therefore, an Effect should not be written under the assumption that its setup can only ever run once.</p><h3>3. Understanding the dependency array</h3><p>The dependency array is often the most confusing part of useEffect.</p><h3>No dependency array</h3><pre>useEffect(() =&gt; {<br>  console.log(&quot;Effect ran after a commit&quot;);<br>});</pre><p>React runs this Effect after every commit of the component.</p><p>If the Effect itself triggers state updates, be careful: this can cause repeated renders.</p><h3>Empty dependency array</h3><pre>useEffect(() =&gt; {<br>  console.log(&quot;Effect has no reactive dependencies&quot;);<br>}, []);</pre><p>The Effect runs when the component mounts, with the development Strict Mode behavior mentioned earlier.</p><h3>Dependency array with values</h3><pre>useEffect(() =&gt; {<br>  console.log(&quot;Selected user changed:&quot;, userId);<br>}, [userId]);</pre><p>React re-runs the Effect when userId changes between renders, and after the initial mount.</p><p>Include every reactive value used by the Effect that needs to stay synchronized. Don’t remove dependencies just to stop an Effect from running; instead, restructure the code when necessary.</p><h3>4. A practical example: Updating the browser title</h3><p>Let’s display the current counter value in the browser tab.</p><pre>import { useEffect, useState } from &quot;react&quot;;</pre><pre>function Counter() {<br>  const [count, setCount] = useState(0);</pre><pre>  useEffect(() =&gt; {<br>    document.title = `Count: ${count}`;<br>  }, [count]);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Count: {count}&lt;/h2&gt;</pre><pre>      &lt;button onClick={() =&gt; setCount((value) =&gt; value + 1)}&gt;<br>        Increase<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default Counter;</pre><p>Whenever count changes, React runs the Effect and updates the document title.</p><p>This is a simple example of synchronizing React state with the browser.</p><h3>5. Fetching data with useEffect</h3><p>A common beginner project is displaying data from an API.</p><p>Here’s a basic example using the browser’s built-in fetch function:</p><pre>import { useEffect, useState } from &quot;react&quot;;</pre><pre>function Users() {<br>  const [users, setUsers] = useState([]);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(&quot;&quot;);</pre><pre>  useEffect(() =&gt; {<br>    const controller = new AbortController();</pre><pre>    async function loadUsers() {<br>      try {<br>        setLoading(true);<br>        setError(&quot;&quot;);</pre><pre>        const response = await fetch(<br>          &quot;https://jsonplaceholder.typicode.com/users&quot;,<br>          { signal: controller.signal }<br>        );</pre><pre>        if (!response.ok) {<br>          throw new Error(&quot;Unable to load users&quot;);<br>        }</pre><pre>        const data = await response.json();<br>        setUsers(data);<br>      } catch (error) {<br>        if (error.name !== &quot;AbortError&quot;) {<br>          setError(error.message);<br>        }<br>      } finally {<br>        if (!controller.signal.aborted) {<br>          setLoading(false);<br>        }<br>      }<br>    }</pre><pre>    loadUsers();</pre><pre>    return () =&gt; {<br>      controller.abort();<br>    };<br>  }, []);</pre><pre>  if (loading) return &lt;p&gt;Loading users...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Error: {error}&lt;/p&gt;;</pre><pre>  return (<br>    &lt;ul&gt;<br>      {users.map((user) =&gt; (<br>        &lt;li key={user.id}&gt;{user.name}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><pre>export default Users;</pre><p>This example includes loading and error states, checks the HTTP response, and aborts the request when the Effect is cleaned up.</p><p>For larger applications, a data-fetching library or framework feature can often handle caching, request deduplication, and server rendering more effectively.</p><h3>6. Why is cleanup important?</h3><p>Some Effects start activities that need to be stopped later.</p><p>Examples include:</p><ul><li>Timers</li><li>Event listeners</li><li>WebSocket connections</li><li>Subscriptions</li></ul><p>Consider a timer:</p><pre>import { useEffect, useState } from &quot;react&quot;;</pre><pre>function Timer() {<br>  const [seconds, setSeconds] = useState(0);</pre><pre>  useEffect(() =&gt; {<br>    const timerId = setInterval(() =&gt; {<br>      setSeconds((previous) =&gt; previous + 1);<br>    }, 1000);</pre><pre>    return () =&gt; {<br>      clearInterval(timerId);<br>    };<br>  }, []);</pre><pre>  return &lt;h2&gt;Seconds: {seconds}&lt;/h2&gt;;<br>}</pre><pre>export default Timer;</pre><p>The cleanup function clears the interval when the component is removed.</p><p>React also runs cleanup before re-running an Effect whose dependencies have changed. This helps prevent old subscriptions or timers from remaining active.</p><h3>7. Common useEffect mistakes</h3><p><strong>Mistake 1: Using an Effect for a value you can calculate during rendering</strong></p><p>Avoid adding an Effect just to keep two state variables synchronized when one can be derived from the other.</p><p>Instead of storing both price and totalPrice when the latter is simply price * quantity, calculate the total during rendering.</p><p><strong>Mistake 2: Forgetting dependencies</strong></p><p>If an Effect uses a reactive value, make sure the dependency list accurately represents what the Effect needs.</p><p><strong>Mistake 3: Creating an infinite update loop</strong></p><p>An Effect that updates state after every render can keep triggering more renders. Check whether an Effect is necessary and whether its dependencies and state updates are correct.</p><p><strong>Mistake 4: Treating useEffect as a tool for every event</strong></p><p>If a user clicks a button to submit a form, the submission generally belongs in that button’s event handler, not in an Effect that watches a separate state variable.</p><h3>8. Practice task: Build a live clock</h3><p>Build a component that displays the current time and updates every second.</p><p>Requirements:</p><ol><li>Store the current time in state.</li><li>Update it every second.</li><li>Display the time in a readable format.</li><li>Clean up the interval when the component is removed.</li></ol><h3>Solution</h3><pre>import { useEffect, useState } from &quot;react&quot;;</pre><pre>function Clock() {<br>  const [time, setTime] = useState(() =&gt; new Date());</pre><pre>  useEffect(() =&gt; {<br>    const intervalId = setInterval(() =&gt; {<br>      setTime(new Date());<br>    }, 1000);</pre><pre>    return () =&gt; clearInterval(intervalId);<br>  }, []);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Live Clock&lt;/h2&gt;<br>      &lt;p&gt;{time.toLocaleTimeString()}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default Clock;</pre><p>The interval updates state every second, and React displays the new time. The cleanup function prevents the interval from continuing after unmounting.</p><h3>Final thoughts</h3><p>useEffect becomes much easier when you stop thinking of it as a way to control every render and start thinking of it as a way to synchronize with external systems.</p><p>Use it for genuine side effects, keep dependencies accurate, and clean up subscriptions or timers when necessary.</p><p>Next, we’ll look at useContext, which helps share data across a component tree without passing the same props through every intermediate component.</p><p><strong>Next article:</strong> <a href="https://medium.com/@dhruvil.unofficial/react-usecontext-hook-explained-share-data-without-prop-drilling-8b766ca7b5ba?sharedUserId=dhruvil.unofficial">React </a><a href="https://medium.com/@dhruvil.unofficial/react-usecontext-hook-explained-share-data-without-prop-drilling-8b766ca7b5ba?sharedUserId=dhruvil.unofficial">useContext Hook — Share Data Without Prop Drilling.</a></p><p><em>Official reference: </em><a href="https://react.dev/reference/react/useEffect"><em>React — use</em>Effect</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d16ebbf3ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React useState Hook Explained: From Your First Counter to Real-World State Management]]></title>
            <link>https://medium.com/@dhruvil.unofficial/react-usestate-hook-explained-from-your-first-counter-to-real-world-state-management-4b44e66cd041?source=rss-c2f1b6068e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b44e66cd041</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dhruvil Bhuva]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 17:45:54 GMT</pubDate>
            <atom:updated>2026-10-22T12:43:00.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P00ES7l3l2MRe6LGVRKC8w.png" /></figure><p>Professional, descriptive, and suitable for a long tutorial with practical examples and exercises.</p><p>When I first started learning React, one question confused me more than I expected: <strong>How does a component remember a value when it renders again?</strong></p><p>Imagine building a counter. You click a button, and the number increases. Then you click it again, and it increases once more. That sounds simple, but React needs a way to remember the current number and update the screen when it changes.</p><p>That is where the useState Hook comes in.</p><p>In this article, we’ll start with the basics and gradually move toward practical examples, common mistakes, and a hands-on challenge.</p><p>By the end, you’ll understand not just how to write useState, but also when and why to use it.</p><h3>1. What is the useState Hook?</h3><p>useState is a built-in React Hook that lets a function component store and update information called <strong>state</strong>.</p><p>State is data that can change while a component is being used.</p><p>For example:</p><ul><li>A counter’s current number</li><li>Text entered into a search box</li><li>Whether a dropdown is open</li><li>Whether a user has selected a checkbox</li><li>Products added to a shopping cart</li><li>Whether a form is displaying a success message</li></ul><p>When state changes, React can render the component again to display the updated information.</p><p>Here is the basic syntax:</p><pre>import { useState } from &quot;react&quot;;</pre><pre>const [value, setValue] = useState(initialValue);</pre><p>Let’s understand each part.</p><ul><li>useState is the Hook that creates a state variable.</li><li>value is the current state value.</li><li>setValue is the function used to request a state update.</li><li>initialValue is the value used when the state is initialized.</li></ul><p>You can choose meaningful names instead of value and setValue.</p><p>For example:</p><pre>const [count, setCount] = useState(0);</pre><p>Here, count starts at 0, and setCount updates it.</p><h3>2. Your first useState example: A counter</h3><p>Let’s build something small before moving to more complex examples.</p><p>Create a file called Counter.jsx:</p><pre>import { useState } from &quot;react&quot;;</pre><pre>function Counter() {<br>  const [count, setCount] = useState(0);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Counter App&lt;/h2&gt;</pre><pre>      &lt;p&gt;Current count: {count}&lt;/p&gt;</pre><pre>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        Increase<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default Counter;</pre><p>Use the component in your application:</p><pre>import Counter from &quot;./Counter&quot;;</pre><pre>function App() {<br>  return &lt;Counter /&gt;;<br>}</pre><pre>export default App;</pre><h3>How does this code work?</h3><p><strong>Step 1:</strong> React initializes count with the value 0.</p><p><strong>Step 2:</strong> The component displays the current value using {count}.</p><p><strong>Step 3:</strong> When the user clicks the button, setCount(count + 1) requests an update.</p><p><strong>Step 4:</strong> React renders the component again with the updated state.</p><p>The displayed number changes from 0 to 1, then 2, then 3, and so on.</p><p>Notice that we don’t manually change the paragraph’s text. We update the state, and React updates the rendered UI.</p><p>That is one of the most important ideas to understand when learning React.</p><h3>3. Why can’t we use a normal variable?</h3><p>You might wonder why we need a Hook at all. Why not use a regular JavaScript variable?</p><p>Consider this example:</p><pre>function Counter() {<br>  let count = 0;</pre><pre>  function increase() {<br>    count = count + 1;<br>    console.log(count);<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={increase}&gt;Increase&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Clicking the button changes the local variable, but it does not tell React to render the component again. The paragraph therefore continues to display the original rendered value.</p><p>There is another problem: whenever React renders the component again, the function runs again and the local variable is initialized to 0.</p><p>Now compare that with:</p><pre>const [count, setCount] = useState(0);</pre><p>React keeps track of this state between renders. Calling setCount requests an update so the component can display the new value.</p><p><strong>The key difference:</strong> A regular variable does not automatically trigger a React render when it changes. Updating state through its setter does.</p><h3>4. Updating state correctly</h3><p>There are two common ways to update state.</p><h3>Method 1: Provide the next value</h3><p>This is useful when the next value is based on something other than the previous state.</p><pre>const [name, setName] = useState(&quot;&quot;);</pre><pre>setName(&quot;Alex&quot;);</pre><p>For example, a button could update a displayed username:</p><pre>import { useState } from &quot;react&quot;;</pre><pre>function Greeting() {<br>  const [name, setName] = useState(&quot;Guest&quot;);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Hello, {name}!&lt;/h2&gt;</pre><pre>      &lt;button onClick={() =&gt; setName(&quot;Alex&quot;)}&gt;<br>        Change Name<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default Greeting;</pre><p>Clicking the button changes the greeting from Hello, Guest! to Hello, Alex!.</p><h3>Method 2: Use a functional state update</h3><p>Sometimes the next state depends on the previous state. In those cases, a function is often the clearest and safest approach.</p><pre>setCount((previousCount) =&gt; previousCount + 1);</pre><p>React passes the previous state value to the updater function, and the function returns the next value.</p><p>For example:</p><pre>import { useState } from &quot;react&quot;;</pre><pre>function Counter() {<br>  const [count, setCount] = useState(0);</pre><pre>  function increaseByThree() {<br>    setCount((previous) =&gt; previous + 1);<br>    setCount((previous) =&gt; previous + 1);<br>    setCount((previous) =&gt; previous + 1);<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{count}&lt;/h2&gt;<br>      &lt;button onClick={increaseByThree}&gt;<br>        Increase by 3<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default Counter;</pre><p>Each updater uses the result of the preceding update, so one click increases the count by 3.</p><p>Compare this with:</p><pre>setCount(count + 1);<br>setCount(count + 1);<br>setCount(count + 1);</pre><p>These calls all calculate the next value from the same count captured by the current render. They do not reliably add three; in this example, they request the same next value three times.</p><p><strong>A useful rule:</strong> When the next state depends on the previous state, prefer a functional update.</p><h3>5. Using useState with input fields</h3><p>Counters are helpful for learning, but input fields are where useState becomes useful in everyday applications.</p><p>Let’s create a live name preview.</p><pre>import { useState } from &quot;react&quot;;</pre><pre>function NameInput() {<br>  const [name, setName] = useState(&quot;&quot;);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Enter Your Name&lt;/h2&gt;</pre><pre>      &lt;input<br>        type=&quot;text&quot;<br>        value={name}<br>        onChange={(event) =&gt; setName(event.target.value)}<br>        placeholder=&quot;Type your name&quot;<br>      /&gt;</pre><pre>      &lt;p&gt;Your name is: {name || &quot;Not entered yet&quot;}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default NameInput;</pre><h3>What’s happening here?</h3><p>The value prop connects the input to React state.</p><p>The onChange handler runs when the user changes the text. It reads the new text from event.target.value and passes it to setName.</p><p>React then renders the updated name below the input.</p><p>This is called a <strong>controlled input</strong> because React state controls the input’s displayed value.</p><p>Controlled inputs are useful for search bars, registration forms, profile editors, and many other interfaces.</p><h3>6. Using useState for show and hide functionality</h3><p>Another common use case is toggling a section of the interface.</p><p>For example, a password visibility button:</p><pre>import { useState } from &quot;react&quot;;</pre><pre>function PasswordInput() {<br>  const [visible, setVisible] = useState(false);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type={visible ? &quot;text&quot; : &quot;password&quot;}<br>        placeholder=&quot;Enter password&quot;<br>      /&gt;</pre><pre>      &lt;button onClick={() =&gt; setVisible((previous) =&gt; !previous)}&gt;<br>        {visible ? &quot;Hide Password&quot; : &quot;Show Password&quot;}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default PasswordInput;</pre><p>The state begins as false, so the input uses the password type.</p><p>When the button is clicked, the updater flips the value. React changes the input type and button label accordingly.</p><p>This example demonstrates an important principle: <strong>state doesn’t have to be text or a number. It can also be a boolean.</strong></p><p>In a real application, remember that toggling password visibility does not provide authentication or secure storage; it only changes how the input is displayed.</p><h3>7. Can useState store objects and arrays?</h3><p>Yes. State can contain strings, numbers, booleans, objects, arrays, and other JavaScript values.</p><p>However, objects and arrays require a little extra care.</p><h3>Example: Managing an object</h3><pre>import { useState } from &quot;react&quot;;</pre><pre>function UserProfile() {<br>  const [user, setUser] = useState({<br>    name: &quot;Dhruvil&quot;,<br>    age: 22,<br>  });</pre><pre>  function increaseAge() {<br>    setUser((previousUser) =&gt; ({<br>      ...previousUser,<br>      age: previousUser.age + 1,<br>    }));<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{user.name}&lt;/h2&gt;<br>      &lt;p&gt;Age: {user.age}&lt;/p&gt;</pre><pre>      &lt;button onClick={increaseAge}&gt;<br>        Increase Age<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default UserProfile;</pre><p>The spread syntax (...previousUser) copies the existing object&#39;s properties. We then replace age with its new value.</p><p>This matters because React state should be treated as immutable. Instead of modifying the existing object, create a new object containing the updated data.</p><p>For example, avoid:</p><pre>user.age = user.age + 1;<br>setUser(user);</pre><p>This mutates the existing object and passes the same object reference back to React. React may skip the update because the reference hasn’t changed.</p><h3>Example: Managing an array</h3><pre>import { useState } from &quot;react&quot;;</pre><pre>function TodoList() {<br>  const [tasks, setTasks] = useState([&quot;Learn React&quot;]);</pre><pre>  function addTask() {<br>    setTasks((previousTasks) =&gt; [<br>      ...previousTasks,<br>      &quot;Practice useState&quot;,<br>    ]);<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;My Tasks&lt;/h2&gt;</pre><pre>      &lt;ul&gt;<br>        {tasks.map((task, index) =&gt; (<br>          &lt;li key={`${task}-${index}`}&gt;{task}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;</pre><pre>      &lt;button onClick={addTask}&gt;Add Task&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default TodoList;</pre><p>The spread syntax creates a new array containing the previous tasks and the new task.</p><p>For a real task manager, it’s better to give each task a stable unique ID and use that ID as the React key, rather than relying on the index.</p><h3>8. Lazy initialization: When the initial value is expensive to calculate</h3><p>Usually, you can initialize state directly:</p><pre>const [count, setCount] = useState(0);</pre><p>But what if calculating the initial value requires more work?</p><p>You can pass a function to useState:</p><pre>const [value, setValue] = useState(() =&gt; calculateInitialValue());</pre><p>React calls the initializer to obtain the initial state. This can avoid repeating an expensive calculation on every render.</p><p>For example:</p><pre>import { useState } from &quot;react&quot;;</pre><pre>function Example() {<br>  const [initialNumber, setInitialNumber] = useState(() =&gt; {<br>    console.log(&quot;Calculating initial value...&quot;);<br>    return 100 * 5;<br>  });</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Value: {initialNumber}&lt;/p&gt;</pre><pre>      &lt;button onClick={() =&gt; setInitialNumber((value) =&gt; value + 1)}&gt;<br>        Increase<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default Example;</pre><p>The initializer is used when React initializes the state, rather than being called as the initializer on every render.</p><p>In development Strict Mode, React may call initializer functions more than once to help reveal accidental side effects. Keep initializer functions pure.</p><p>Also, lazy initialization is not necessary for every state variable. Use it when the initial calculation is meaningfully expensive or when you need to initialize from a source such as browser storage.</p><h3>9. Common useState mistakes to avoid</h3><h3>Mistake 1: Mutating an object directly</h3><p>Avoid:</p><pre>user.name = &quot;Dhruvil&quot;;<br>setUser(user);</pre><p>Prefer:</p><pre>setUser((previousUser) =&gt; ({<br>  ...previousUser,<br>  name: &quot;Dhruvil&quot;,<br>}));</pre><h3>Mistake 2: Assuming state changes immediately</h3><p>Calling a setter does not change the state variable inside the currently executing function.</p><pre>setCount(count + 1);<br>console.log(count);</pre><p>That console.log still reads the value from the current render. The updated value will be available when React renders the component again.</p><h3>Mistake 3: Using a regular variable for UI state</h3><p>If a changing value should be reflected in the rendered UI, state is usually the right choice.</p><h3>Mistake 4: Calling Hooks conditionally</h3><p>Don’t put useState inside an if statement, loop, or nested function.</p><p>Incorrect:</p><pre>if (isLoggedIn) {<br>  const [name, setName] = useState(&quot;&quot;);<br>}</pre><p>Correct:</p><pre>const [name, setName] = useState(&quot;&quot;);</pre><pre>if (isLoggedIn) {<br>  // Use name and setName here.<br>}</pre><p>Call Hooks at the top level of a function component or custom Hook, before any conditional returns.</p><h3>Mistake 5: Using separate state variables when one object is clearer — or one object when separate state is clearer</h3><p>Both of these approaches can be valid:</p><pre>const [firstName, setFirstName] = useState(&quot;&quot;);<br>const [lastName, setLastName] = useState(&quot;&quot;);</pre><p>Or:</p><pre>const [user, setUser] = useState({<br>  firstName: &quot;&quot;,<br>  lastName: &quot;&quot;,<br>});</pre><p>Choose the structure that makes updates and relationships between values easiest to understand. You don’t need to combine every related value into one object.</p><h3>10. When should you use useState?</h3><p>Use useState when a component needs to remember a changing value that affects its behavior or displayed UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mytRaD0zUn0MoNXANYD8Xw.png" /></figure><p>You don’t need useState for every variable. Static values and temporary calculations that don&#39;t need to survive a render can usually remain regular variables.</p><p>If the state logic becomes complex, consider useReducer. If multiple components need to share state, consider lifting the state to a common parent or using Context when appropriate.</p><h3>11. Practice task: Build a character counter</h3><p>Now it’s your turn to apply what you’ve learned.</p><p><strong>Your challenge:</strong> Build a text input that displays how many characters the user has typed.</p><p>Requirements:</p><ol><li>Create a state variable called text.</li><li>Start with an empty string.</li><li>Display a text input.</li><li>Update the state whenever the input changes.</li><li>Display the current character count.</li><li>Show a message when the user reaches 20 characters.</li><li>Add a button that clears the input.</li></ol><p>Try to solve it yourself before checking the solution.</p><h3>Solution</h3><pre>import { useState } from &quot;react&quot;;</pre><pre>function CharacterCounter() {<br>  const [text, setText] = useState(&quot;&quot;);</pre><pre>  function clearText() {<br>    setText(&quot;&quot;);<br>  }</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Character Counter&lt;/h2&gt;</pre><pre>      &lt;input<br>        type=&quot;text&quot;<br>        value={text}<br>        onChange={(event) =&gt; setText(event.target.value)}<br>        placeholder=&quot;Start typing...&quot;<br>      /&gt;</pre><pre>      &lt;p&gt;Characters: {text.length}&lt;/p&gt;</pre><pre>      {text.length &gt;= 20 &amp;&amp; (<br>        &lt;p&gt;You have reached 20 characters!&lt;/p&gt;<br>      )}</pre><pre>      &lt;button onClick={clearText}&gt;Clear&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default CharacterCounter;</pre><h3>What this task teaches you</h3><p>You used a string as state, connected it to a controlled input, derived a value using text.length, displayed conditional UI, and reset state with a button.</p><p>Notice that the character count doesn’t need its own state variable. It can be calculated directly from text, which avoids storing the same information twice.</p><p><strong>Bonus challenge:</strong> Limit the input to 20 characters and display how many characters remain.</p><h3>12. Final thoughts</h3><p>useState is one of the first React Hooks worth learning because it introduces a core React idea: your interface can respond to changing data.</p><p>Once you understand how state is initialized, updated, and rendered, you can build interactive forms, counters, menus, task lists, and much more.</p><p>Don’t just memorize the syntax. Experiment with the examples, change the values, introduce a bug, and figure out why it happens. That process will teach you far more than copying code alone.</p><p>In the next article, we’ll explore the useEffect Hook, which helps you synchronize a component with external systems such as browser APIs, subscriptions, and network requests.</p><p><strong>Next in the series:</strong> <a href="https://medium.com/@dhruvil.unofficial/react-useeffect-hook-explained-dependencies-cleanup-and-real-world-examples-71d16ebbf3ee?sharedUserId=dhruvil.unofficial">React </a><a href="https://medium.com/@dhruvil.unofficial/react-useeffect-hook-explained-dependencies-cleanup-and-real-world-examples-71d16ebbf3ee?sharedUserId=dhruvil.unofficial">useEffect Hook — Dependencies, Cleanup, and Real-World Examples.</a></p><p><em>Official reference: </em><a href="https://react.dev/reference/react/useState"><em>React — useState</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b44e66cd041" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Type Conversion and Coercion — Why "10" + 5 Becomes "105"]]></title>
            <link>https://medium.com/@dhruvil.unofficial/javascript-type-conversion-and-coercion-why-10-5-becomes-105-0768b0f10dc5?source=rss-c2f1b6068e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0768b0f10dc5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dhruvil Bhuva]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 10:35:39 GMT</pubDate>
            <atom:updated>2026-10-14T10:36:47.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2H6_gt4abQjCy5oMhhdQSw.png" /></figure><p><strong>JavaScript From Zero to Advanced — Part 5 of 35</strong></p><p>If you have ever written JavaScript and wondered why &quot;10&quot; + 5 produces &quot;105&quot; instead of 15, you are not alone.</p><p>It is one of those JavaScript behaviors that looks confusing at first. You have two values that seem like numbers, you use the + operator, and JavaScript gives you something completely different from what you expected.</p><p>But there is a reason behind it.</p><p>JavaScript sometimes converts a value from one data type to another. Sometimes we tell it to do this ourselves, and sometimes JavaScript does it automatically.</p><p>Understanding this behavior will help you avoid unexpected results when working with form inputs, calculations, user data, APIs, and real-world applications.</p><p>In Part 4, we explored arithmetic, comparison, and logical operators. Now, let’s understand what happens when those operators work with different data types.</p><p>By the end of this article, you will understand:</p><ul><li>What type conversion and type coercion mean.</li><li>Why &quot;10&quot; + 5 produces &quot;105&quot;.</li><li>How to use Number(), String(), and Boolean().</li><li>What truthy and falsy values are.</li><li>What NaN means and how to check for it.</li><li>How to handle form inputs without accidentally concatenating strings.</li><li>How to build a small bill calculator using JavaScript.</li></ul><p>Let’s start with the problem.</p><h3>1. The Problem: Why Does &quot;10&quot; + 5 Become &quot;105&quot;?</h3><p>Look at this code:</p><pre>let firstValue = &quot;10&quot;;<br>let secondValue = 5;</pre><pre>let result = firstValue + secondValue;</pre><pre>console.log(result);</pre><p>Output:</p><pre>105</pre><p>Wait a second. Why didn’t JavaScript calculate 10 + 5?</p><p>The reason is that firstValue contains a <strong>string</strong>, not a number.</p><p>Even though &quot;10&quot; looks like a number, JavaScript treats it as text because it is enclosed in quotation marks.</p><p>The + operator has two important jobs in JavaScript:</p><ol><li>Adding numbers.</li><li>Joining strings together, which is called concatenation.</li></ol><p>When JavaScript evaluates &quot;10&quot; + 5, it converts the number 5 into the string &quot;5&quot; and joins the two strings.</p><p>The result is:</p><pre>&quot;10&quot; + &quot;5&quot; // &quot;105&quot;</pre><p>Here is the difference:</p><pre>console.log(10 + 5);<br>console.log(&quot;10&quot; + 5);<br>console.log(&quot;10&quot; + &quot;5&quot;);</pre><p>Output:</p><pre>15<br>105<br>105</pre><p>The first expression performs arithmetic addition. The other two perform string concatenation.</p><p><strong>Remember:</strong> A value that looks like a number is not necessarily a number. Its data type matters.</p><h3>2. What Is Type Conversion?</h3><p>Type conversion means changing a value from one data type to another.</p><p>For example, you might convert:</p><ul><li>A string into a number.</li><li>A number into a string.</li><li>A value into a Boolean (true or false).</li></ul><p>JavaScript supports two main forms of type conversion.</p><h3>A. Explicit conversion</h3><p>Explicit conversion happens when you deliberately convert a value using a function such as Number(), String(), or Boolean().</p><pre>let age = &quot;25&quot;;</pre><pre>let numericAge = Number(age);</pre><pre>console.log(numericAge);<br>console.log(typeof numericAge);</pre><p>Output:</p><pre>25<br>number</pre><p>We explicitly converted the string &quot;25&quot; into the number 25.</p><h3>B. Implicit conversion, also called coercion</h3><p>Implicit conversion happens when JavaScript automatically converts a value during an operation.</p><pre>let result = &quot;10&quot; + 5;</pre><pre>console.log(result);<br>console.log(typeof result);</pre><p>Output:</p><pre>105<br>string</pre><p>JavaScript automatically converted the number 5 into a string.</p><p>The important difference is that explicit conversion is something you request, while implicit conversion happens as part of JavaScript’s evaluation of an expression.</p><p>For predictable application code, explicit conversion is usually easier to understand and maintain.</p><h3>3. Convert Values into Numbers with Number()</h3><p>The Number() function attempts to convert a value into a number.</p><p>Let’s look at some examples.</p><pre>console.log(Number(&quot;10&quot;));<br>console.log(Number(&quot;25.5&quot;));<br>console.log(Number(&quot;0&quot;));<br>console.log(Number(&quot;&quot;));<br>console.log(Number(&quot;hello&quot;));<br>console.log(Number(true));<br>console.log(Number(false));</pre><p>Output:</p><pre>10<br>25.5<br>0<br>0<br>NaN<br>1<br>0</pre><p>Let’s understand each result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oyhuk9cbrTHg-W-qFWbIBw.png" /></figure><p>Notice something important: Number(&quot;&quot;) returns 0.</p><p>This means you should not automatically assume that an empty form input is a meaningful zero. If a user leaves a required field blank, validate the input before calculating.</p><h3>Example: Converting a price</h3><pre>let price = &quot;499&quot;;<br>let quantity = &quot;3&quot;;</pre><pre>let total = Number(price) * Number(quantity);</pre><pre>console.log(total);</pre><p>Output:</p><pre>1497</pre><p>Both values are converted into numbers before multiplication.</p><p>You could also write:</p><pre>let total = Number(price) * Number(quantity);</pre><pre>console.log(`Total: ₹${total}`);</pre><p>Output:</p><pre>Total: ₹1497</pre><p>We will use this approach later when building a practical calculator.</p><h3>4. Convert Values into Strings with String()</h3><p>Sometimes you need to convert a value into text.</p><p>For example, you might display a calculated result, combine a value with a message, or prepare a value for a text-based interface.</p><p>JavaScript provides the String() function.</p><pre>console.log(String(100));<br>console.log(String(25.5));<br>console.log(String(true));<br>console.log(String(false));<br>console.log(String(null));<br>console.log(String(undefined));</pre><p>Output:</p><pre>100<br>25.5<br>true<br>false<br>null<br>undefined</pre><p>These results are strings, even though some of them look like numbers or Boolean values.</p><p>Let’s verify this.</p><pre>let price = 499;</pre><pre>let message = String(price);</pre><pre>console.log(message);<br>console.log(typeof message);</pre><p>Output:</p><pre>499<br>string</pre><h3>Why does this matter?</h3><p>Consider the following code:</p><pre>let price = 499;<br>let quantity = 2;</pre><pre>let total = price * quantity;</pre><pre>console.log(&quot;Total: &quot; + total);</pre><p>Output:</p><pre>Total: 998</pre><p>Here, JavaScript first calculates 499 * 2, producing the number 998. Then, the + operator joins the string &quot;Total: &quot; with the result.</p><p>You can make the intention clearer with a template literal:</p><pre>console.log(`Total: ${total}`);</pre><p>Output:</p><pre>Total: 998</pre><p>Template literals are especially useful when displaying calculated values alongside text.</p><h3>5. Convert Values into Booleans with Boolean()</h3><p>A Boolean value is either true or false.</p><p>JavaScript can convert many different values into Boolean values using Boolean().</p><pre>console.log(Boolean(1));<br>console.log(Boolean(0));<br>console.log(Boolean(&quot;hello&quot;));<br>console.log(Boolean(&quot;&quot;));<br>console.log(Boolean(null));<br>console.log(Boolean(undefined));</pre><p>Output:</p><pre>true<br>false<br>true<br>false<br>false<br>false</pre><p>But why do some values become true while others become false?</p><p>This is where truthy and falsy values come in.</p><h3>6. Truthy and Falsy Values Explained</h3><p>In JavaScript, a value is <strong>truthy</strong> if it behaves like true in a Boolean context. A value is <strong>falsy</strong> if it behaves like false.</p><p>You do not need to convert every value manually with Boolean(). JavaScript performs this Boolean conversion automatically in conditions such as if and while.</p><h3>Common falsy values</h3><p>The following values are falsy:</p><ul><li>false</li><li>0</li><li>-0</li><li>0n</li><li>&quot;&quot; (an empty string)</li><li>null</li><li>undefined</li><li>NaN</li></ul><p>There is also a special value called document.all with unusual legacy behavior in browsers, but you do not need it for everyday JavaScript development.</p><p>Almost everything else is truthy.</p><p>For example:</p><ul><li>&quot;hello&quot; is truthy.</li><li>&quot;0&quot; is truthy.</li><li>&quot;false&quot; is truthy.</li><li>-1 is truthy.</li><li>[] is truthy.</li><li>{} is truthy.</li></ul><p>This is a common source of mistakes.</p><h3>Example 1: An empty string</h3><pre>let username = &quot;&quot;;</pre><pre>if (username) {<br>    console.log(&quot;Username entered&quot;);<br>} else {<br>    console.log(&quot;Username is empty&quot;);<br>}</pre><p>Output:</p><pre>Username is empty</pre><p>The empty string is falsy, so JavaScript executes the else block.</p><h3>Example 2: A string containing zero</h3><pre>let value = &quot;0&quot;;</pre><pre>if (value) {<br>    console.log(&quot;The condition is true&quot;);<br>} else {<br>    console.log(&quot;The condition is false&quot;);<br>}</pre><p>Output:</p><pre>The condition is true</pre><p>Why?</p><p>Because &quot;0&quot; is a non-empty string. It is not the number 0.</p><p>Compare these expressions:</p><pre>console.log(Boolean(0));<br>console.log(Boolean(&quot;0&quot;));</pre><p>Output:</p><pre>false<br>true</pre><h3>Example 3: Empty arrays and objects</h3><pre>console.log(Boolean([]));<br>console.log(Boolean({}));</pre><p>Output:</p><pre>true<br>true</pre><p>An empty array and an empty object are both truthy in JavaScript.</p><p><strong>Important:</strong> An empty array is not the same as an empty string, and an empty object is not automatically considered missing.</p><h3>When should you use truthy and falsy checks?</h3><p>They are useful when checking whether a value exists or whether a condition should run.</p><p>However, they are not always suitable for validating numeric input.</p><p>For example:</p><pre>let quantity = 0;</pre><pre>if (!quantity) {<br>    console.log(&quot;Quantity is missing&quot;);<br>}</pre><p>Output:</p><pre>Quantity is missing</pre><p>This code treats zero as missing. That might be correct for a quantity that must be positive, but it is not correct if zero is a valid value.</p><p>Choose your validation rule according to the actual requirement.</p><h3>7. What Is NaN in JavaScript?</h3><p>NaN stands for <strong>Not-a-Number</strong>.</p><p>It is a special numeric value that indicates an invalid or undefined numeric result.</p><p>Consider this example:</p><pre>let result = Number(&quot;hello&quot;);</pre><pre>console.log(result);<br>console.log(typeof result);</pre><p>Output:</p><pre>NaN<br>number</pre><p>The surprising part is that typeof NaN returns &quot;number&quot;.</p><p>That is because NaN is a special value within JavaScript&#39;s Number type.</p><h3>Example: Invalid arithmetic</h3><pre>let result = 10 / &quot;hello&quot;;</pre><pre>console.log(result);</pre><p>Output:</p><pre>NaN</pre><p>JavaScript cannot produce a meaningful numeric result from this calculation, so it returns NaN.</p><h3>How do you check for NaN?</h3><p>You might think this would work:</p><pre>let result = NaN;</pre><pre>console.log(result === NaN);</pre><p>Output:</p><pre>false</pre><p>Even though result contains NaN, the comparison returns false.</p><p>Instead, use Number.isNaN().</p><pre>let result = Number(&quot;hello&quot;);</pre><pre>console.log(Number.isNaN(result));<br>console.log(Number.isNaN(25));</pre><p>Output:</p><pre>true<br>false</pre><h3>Why is Number.isNaN() useful?</h3><p>Imagine a user enters &quot;abc&quot; into a price field. If you convert it with Number(), you get NaN.</p><p>Checking for NaN helps you prevent invalid calculations and display a useful error message.</p><p>However, Number.isNaN() alone does not validate every kind of form input. You must also check whether the field is empty and whether the number meets your application&#39;s rules.</p><h3>8. parseInt(), parseFloat(), and Number() — What&#39;s the Difference?</h3><p>These three methods can convert text into numeric values, but they behave differently.</p><h3>Using Number()</h3><pre>console.log(Number(&quot;25&quot;));<br>console.log(Number(&quot;25.75&quot;));<br>console.log(Number(&quot;25px&quot;));</pre><p>Output:</p><pre>25<br>25.75<br>NaN</pre><p>Number() expects the entire non-whitespace string to represent a valid numeric value.</p><h3>Using parseInt()</h3><pre>console.log(parseInt(&quot;25&quot;));<br>console.log(parseInt(&quot;25.75&quot;));<br>console.log(parseInt(&quot;25px&quot;));</pre><p>Output:</p><pre>25<br>25<br>25</pre><p>parseInt() reads an integer from the beginning of a string and stops when it encounters a character that cannot be part of that integer.</p><h3>Using parseFloat()</h3><pre>console.log(parseFloat(&quot;25.75&quot;));<br>console.log(parseFloat(&quot;25.75px&quot;));<br>console.log(parseFloat(&quot;hello25&quot;));</pre><p>Output:</p><pre>25.75<br>25.75<br>NaN</pre><p>parseFloat() reads a decimal number from the beginning of a string.</p><h3>Quick comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjr9hPI7zjFd_glXj3FhNg.png" /></figure><p>For form fields that are supposed to contain a complete numeric value, Number() is often a good choice after checking that the input is not empty.</p><p>Do not use parseInt() simply to make invalid input appear valid. For example, &quot;25px&quot; may be invalid as a price even though parseInt(&quot;25px&quot;) returns 25.</p><h3>9. Understanding Implicit Conversion with the + Operator</h3><p>Now let’s explore a few examples that demonstrate how JavaScript decides what to do with different data types.</p><h3>Example 1: Number plus number</h3><pre>console.log(10 + 5);</pre><p>Output:</p><pre>15</pre><p>Both values are numbers, so JavaScript performs addition.</p><h3>Example 2: String plus number</h3><pre>console.log(&quot;10&quot; + 5);</pre><p>Output:</p><pre>105</pre><p>The values are combined as strings.</p><h3>Example 3: Number plus string</h3><pre>console.log(10 + &quot;5&quot;);</pre><p>Output:</p><pre>105</pre><p>The order of the operands does not change the result in this example.</p><h3>Example 4: String minus number</h3><pre>console.log(&quot;10&quot; - 5);</pre><p>Output:</p><pre>5</pre><p>The - operator performs numeric subtraction. JavaScript converts the numeric string &quot;10&quot; into the number 10.</p><h3>Example 5: String multiplied by number</h3><pre>console.log(&quot;10&quot; * 5);</pre><p>Output:</p><pre>50</pre><p>JavaScript converts &quot;10&quot; into a number and performs multiplication.</p><h3>Example 6: String divided by number</h3><pre>console.log(&quot;20&quot; / 4);</pre><p>Output:</p><pre>5</pre><p>The division operator also performs numeric conversion.</p><h3>The key takeaway</h3><p>The + operator can mean addition or concatenation. The -, *, and / operators generally perform numeric operations, which may require converting operands to numbers.</p><p>This is why the following results differ:</p><pre>console.log(&quot;10&quot; + 5);<br>console.log(&quot;10&quot; - 5);<br>console.log(&quot;10&quot; * 5);<br>console.log(&quot;10&quot; / 5);</pre><p>Output:</p><pre>105<br>5<br>50<br>2</pre><p>Understanding this difference will save you from many beginner-level bugs.</p><h3>10. Comparison Operators Can Also Cause Confusion</h3><p>JavaScript can convert values during comparisons, too.</p><p>Consider:</p><pre>console.log(10 == &quot;10&quot;);<br>console.log(10 === &quot;10&quot;);</pre><p>Output:</p><pre>true<br>false</pre><p>The == operator allows type conversion when comparing different types. In this example, it converts the string &quot;10&quot; into a number before comparing.</p><p>The === operator compares both value and type without performing that kind of coercion.</p><p>Therefore:</p><pre>10 == &quot;10&quot;  // true<br>10 === &quot;10&quot; // false</pre><p>For most everyday application code, prefer === and !== because they make type differences explicit.</p><p>Here is another example:</p><pre>console.log(0 == false);<br>console.log(0 === false);</pre><p>Output:</p><pre>true<br>false</pre><p>The first comparison permits conversion. The second does not.</p><p><strong>Developer tip:</strong> When comparing values from form inputs, APIs, or databases, check their types rather than assuming that matching-looking values have matching types.</p><h3>11. The Real-World Problem: HTML Form Inputs Are Strings</h3><p>This is one of the most important lessons in this article.</p><p>When a user enters a number into a normal HTML text input, the input’s .value property returns a string.</p><p>Even when a user types 100, JavaScript generally receives &quot;100&quot;.</p><p>Let’s see what can happen.</p><pre>&lt;input id=&quot;price&quot; value=&quot;100&quot;&gt;<br>&lt;input id=&quot;quantity&quot; value=&quot;2&quot;&gt;</pre><pre>&lt;script&gt;<br>    const price = document.getElementById(&quot;price&quot;).value;<br>    const quantity = document.getElementById(&quot;quantity&quot;).value;</pre><pre>    console.log(price + quantity);<br>&lt;/script&gt;</pre><p>Output:</p><pre>1002</pre><p>You might expect 200, but JavaScript combines the two strings.</p><p>The fix is to convert the input values into numbers before calculating.</p><pre>const price = Number(<br>    document.getElementById(&quot;price&quot;).value<br>);</pre><pre>const quantity = Number(<br>    document.getElementById(&quot;quantity&quot;).value<br>);</pre><pre>const total = price * quantity;</pre><pre>console.log(total);</pre><p>Output:</p><pre>200</pre><p>Notice that multiplication already attempts numeric conversion. Still, explicitly converting the values makes the intended data types clear and helps you validate the inputs before using them.</p><p>Let’s build a complete example.</p><h3>12. Mini Project: Build a Bill Calculator</h3><p>Let’s create a small bill calculator that accepts a product price and quantity, calculates the total, and handles invalid input.</p><p>This example uses plain HTML, CSS, and JavaScript. You can save it as index.html and open it in your browser.</p><h3>Complete working code</h3><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;JavaScript Bill Calculator&lt;/title&gt;</pre><pre>    &lt;style&gt;<br>        * {<br>            box-sizing: border-box;<br>        }</pre><pre>        body {<br>            font-family: Arial, sans-serif;<br>            background: #f4f6f8;<br>            margin: 0;<br>            padding: 30px 16px;<br>        }</pre><pre>        .calculator {<br>            max-width: 420px;<br>            margin: 40px auto;<br>            padding: 24px;<br>            background: white;<br>            border-radius: 12px;<br>            box-shadow: 0 4px 18px rgba(0, 0, 0, 0.08);<br>        }</pre><pre>        h1 {<br>            margin-top: 0;<br>            font-size: 24px;<br>        }</pre><pre>        label {<br>            display: block;<br>            margin: 16px 0 6px;<br>            font-weight: bold;<br>        }</pre><pre>        input,<br>        button {<br>            width: 100%;<br>            padding: 12px;<br>            font-size: 16px;<br>            border-radius: 6px;<br>        }</pre><pre>        input {<br>            border: 1px solid #cbd5e1;<br>        }</pre><pre>        button {<br>            margin-top: 20px;<br>            border: none;<br>            background: #2563eb;<br>            color: white;<br>            cursor: pointer;<br>        }</pre><pre>        button:hover {<br>            background: #1d4ed8;<br>        }</pre><pre>        #result {<br>            margin-top: 18px;<br>            overflow-wrap: anywhere;<br>            font-weight: bold;<br>        }</pre><pre>        .error {<br>            color: #b91c1c;<br>        }</pre><pre>        .success {<br>            color: #166534;<br>        }<br>    &lt;/style&gt;<br>&lt;/head&gt;</pre><pre>&lt;body&gt;<br>    &lt;main class=&quot;calculator&quot;&gt;<br>        &lt;h1&gt;Bill Calculator&lt;/h1&gt;</pre><pre>        &lt;form id=&quot;billForm&quot;&gt;<br>            &lt;label for=&quot;price&quot;&gt;Price per item (₹)&lt;/label&gt;<br>            &lt;input<br>                type=&quot;number&quot;<br>                id=&quot;price&quot;<br>                min=&quot;0&quot;<br>                step=&quot;0.01&quot;<br>                placeholder=&quot;Enter price&quot;<br>                required<br>            &gt;</pre><pre>            &lt;label for=&quot;quantity&quot;&gt;Quantity&lt;/label&gt;<br>            &lt;input<br>                type=&quot;number&quot;<br>                id=&quot;quantity&quot;<br>                min=&quot;1&quot;<br>                step=&quot;1&quot;<br>                placeholder=&quot;Enter quantity&quot;<br>                required<br>            &gt;</pre><pre>            &lt;button type=&quot;submit&quot;&gt;Calculate Total&lt;/button&gt;<br>        &lt;/form&gt;</pre><pre>        &lt;p id=&quot;result&quot; aria-live=&quot;polite&quot;&gt;&lt;/p&gt;<br>    &lt;/main&gt;</pre><pre>    &lt;script&gt;<br>        const billForm = document.getElementById(&quot;billForm&quot;);<br>        const priceInput = document.getElementById(&quot;price&quot;);<br>        const quantityInput = document.getElementById(&quot;quantity&quot;);<br>        const result = document.getElementById(&quot;result&quot;);</pre><pre>        billForm.addEventListener(&quot;submit&quot;, function (event) {<br>            event.preventDefault();</pre><pre>            const priceText = priceInput.value.trim();<br>            const quantityText = quantityInput.value.trim();</pre><pre>            if (priceText === &quot;&quot; || quantityText === &quot;&quot;) {<br>                showError(&quot;Please fill in both fields.&quot;);<br>                return;<br>            }</pre><pre>            const price = Number(priceText);<br>            const quantity = Number(quantityText);</pre><pre>            if (!Number.isFinite(price) || !Number.isFinite(quantity)) {<br>                showError(&quot;Please enter valid numeric values.&quot;);<br>                return;<br>            }</pre><pre>            if (price &lt; 0 || quantity &lt; 1 || !Number.isInteger(quantity)) {<br>                showError(<br>                    &quot;Price must be non-negative and quantity must be a positive whole number.&quot;<br>                );<br>                return;<br>            }</pre><pre>            const total = price * quantity;</pre><pre>            if (!Number.isFinite(total)) {<br>                showError(&quot;The calculated total is outside the supported range.&quot;);<br>                return;<br>            }</pre><pre>            result.className = &quot;success&quot;;<br>            result.textContent =<br>                `Total: ₹${total.toFixed(2)}`;<br>        });</pre><pre>        function showError(message) {<br>            result.className = &quot;error&quot;;<br>            result.textContent = message;<br>        }<br>    &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h3>How the project works</h3><p><strong>Step 1: Select the form elements</strong></p><pre>const billForm = document.getElementById(&quot;billForm&quot;);<br>const priceInput = document.getElementById(&quot;price&quot;);<br>const quantityInput = document.getElementById(&quot;quantity&quot;);<br>const result = document.getElementById(&quot;result&quot;);</pre><p>We select the form, the two input fields, and the element that will display the result.</p><p><strong>Step 2: Listen for form submission</strong></p><pre>billForm.addEventListener(&quot;submit&quot;, function (event) {<br>    event.preventDefault();<br>});</pre><p>When the form is submitted, JavaScript runs the callback function.</p><p>event.preventDefault() prevents the browser from submitting the form normally and reloading the page.</p><p><strong>Step 3: Read and validate the input</strong></p><pre>const priceText = priceInput.value.trim();<br>const quantityText = quantityInput.value.trim();</pre><pre>if (priceText === &quot;&quot; || quantityText === &quot;&quot;) {<br>    showError(&quot;Please fill in both fields.&quot;);<br>    return;<br>}</pre><p>We read the values as strings and check for empty inputs before converting them.</p><p>The return stops the calculation when validation fails.</p><p><strong>Step 4: Convert the values</strong></p><pre>const price = Number(priceText);<br>const quantity = Number(quantityText);</pre><p>We explicitly convert the input strings into numbers.</p><p><strong>Step 5: Reject invalid numbers</strong></p><pre>if (!Number.isFinite(price) || !Number.isFinite(quantity)) {<br>    showError(&quot;Please enter valid numeric values.&quot;);<br>    return;<br>}</pre><p>Number.isFinite() rejects NaN, positive and negative infinity, and non-numeric values. This prevents invalid numbers from reaching the calculation.</p><p><strong>Step 6: Check the business rules</strong></p><pre>if (price &lt; 0 || quantity &lt; 1 || !Number.isInteger(quantity)) {<br>    showError(<br>        &quot;Price must be non-negative and quantity must be a positive whole number.&quot;<br>    );<br>    return;<br>}</pre><p>A negative price is not allowed, and the quantity must be a positive whole number.</p><p>These rules are specific to this bill calculator. Other applications may have different requirements.</p><p><strong>Step 7: Calculate and display the total</strong></p><pre>const total = price * quantity;</pre><pre>result.className = &quot;success&quot;;<br>result.textContent = `Total: ₹${total.toFixed(2)}`;</pre><p>We multiply two numbers, format the total to two decimal places, and display it.</p><p>We use textContent instead of innerHTML because we only need to display text. This avoids interpreting the result as HTML.</p><h3>Test the project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43TvNBvupM9aub36CVwYdQ.png" /></figure><p>Try these values yourself. Pay attention to the difference between an empty input, a numeric zero, and invalid input.</p><p>One more real-world detail: JavaScript uses floating-point numbers, so some decimal calculations can have tiny precision errors. For financial systems, use integer minor units (such as paise) or a suitable decimal arithmetic library when exact monetary arithmetic is required.</p><h3>13. Common Mistakes to Avoid</h3><h3>Mistake 1: Adding input values directly</h3><pre>let a = &quot;100&quot;;<br>let b = &quot;200&quot;;</pre><pre>console.log(a + b);</pre><p>Output:</p><pre>100200</pre><p><strong>Fix:</strong></p><pre>console.log(Number(a) + Number(b));</pre><p>Output:</p><pre>300</pre><h3>Mistake 2: Assuming Number() rejects an empty string</h3><pre>console.log(Number(&quot;&quot;));</pre><p>Output:</p><pre>0</pre><p><strong>Fix:</strong> Check whether the original input is empty before converting it.</p><h3>Mistake 3: Treating &quot;0&quot; as falsy</h3><pre>console.log(Boolean(&quot;0&quot;));</pre><p>Output:</p><pre>true</pre><p><strong>Fix:</strong> Remember that &quot;0&quot; is a non-empty string, while 0 is a falsy number.</p><h3>Mistake 4: Checking NaN with equality</h3><pre>console.log(NaN === NaN);</pre><p>Output:</p><pre>false</pre><p><strong>Fix:</strong></p><pre>console.log(Number.isNaN(NaN));</pre><p>Output:</p><pre>true</pre><h3>Mistake 5: Using == when you mean strict equality</h3><pre>console.log(5 == &quot;5&quot;);</pre><p>Output:</p><pre>true</pre><p><strong>Fix:</strong></p><pre>console.log(5 === &quot;5&quot;);</pre><p>Output:</p><pre>false</pre><p>Use strict equality when you want both the value and type to match.</p><h3>Mistake 6: Assuming multiplication always makes invalid input safe</h3><pre>console.log(Number(&quot;abc&quot;) * 5);</pre><p>Output:</p><pre>NaN</pre><p><strong>Fix:</strong> Validate the converted number before using it in a calculation.</p><h3>Mistake 7: Thinking every truthy value contains useful data</h3><pre>console.log(Boolean([]));<br>console.log(Boolean({}));</pre><p>Output:</p><pre>true<br>true</pre><p><strong>Fix:</strong> If you need to check whether an array is empty, use array.length === 0. If you need to check whether an object has properties, use an appropriate object-key check.</p><h3>14. Practice Tasks</h3><p>Now it is your turn. Try solving these problems without looking at the answers immediately.</p><h3>Task 1: Predict the output</h3><p>What will this code print?</p><pre>console.log(&quot;20&quot; + 10);<br>console.log(&quot;20&quot; - 10);<br>console.log(&quot;20&quot; * 2);<br>console.log(&quot;20&quot; / 4);</pre><p>Explain why the first result is different from the others.</p><h3>Task 2: Convert strings into numbers</h3><p>Create two variables:</p><pre>let firstNumber = &quot;45&quot;;<br>let secondNumber = &quot;15&quot;;</pre><p>Convert both values into numbers and print:</p><ul><li>Their sum.</li><li>Their difference.</li><li>Their product.</li><li>Their division result.</li></ul><p>Your solution should not concatenate the strings.</p><h3>Task 3: Identify truthy and falsy values</h3><p>Predict whether each value becomes true or false when converted with Boolean():</p><pre>Boolean(0)<br>Boolean(&quot;0&quot;)<br>Boolean(&quot;&quot;)<br>Boolean(&quot;false&quot;)<br>Boolean(null)<br>Boolean([])<br>Boolean({})<br>Boolean(NaN)</pre><p>Write your predictions before running the code.</p><h3>Task 4: Handle invalid numeric input</h3><p>Write a function named calculateTotal(price, quantity) that:</p><ol><li>Converts both arguments into numbers.</li><li>Rejects empty strings.</li><li>Rejects invalid numeric values.</li><li>Rejects negative prices and quantities below one.</li><li>Returns the total when the inputs are valid.</li><li>Displays an appropriate error or returns a clear error result when they are invalid.</li></ol><p>Test it with &quot;100&quot; and &quot;3&quot;, then with &quot;hello&quot; and &quot;3&quot;.</p><h3>Task 5: Build a discount calculator</h3><p>Create a small program that accepts:</p><ul><li>Product price.</li><li>Quantity.</li><li>Discount percentage.</li></ul><p>Calculate the subtotal, discount amount, and final total.</p><p>Requirements:</p><ul><li>Convert all inputs to numbers.</li><li>Do not accept empty or invalid numeric values.</li><li>Do not accept negative prices or quantities below one.</li><li>Keep the discount between 0 and 100 percent.</li><li>Display the result with two decimal places.</li></ul><p><strong>Challenge:</strong> Add a rule that gives a 10% discount when the subtotal is ₹1,000 or more. Otherwise, no automatic discount is applied.</p><h3>15. Practice Task Solutions</h3><p>Try the exercises first, then compare your answers.</p><h3>Solution 1: Predict the output</h3><pre>console.log(&quot;20&quot; + 10);<br>console.log(&quot;20&quot; - 10);<br>console.log(&quot;20&quot; * 2);<br>console.log(&quot;20&quot; / 4);</pre><p>Output:</p><pre>2010<br>10<br>40<br>5</pre><p>The + operator concatenates the string and number. The other operators perform numeric calculations after converting the numeric string.</p><h3>Solution 2: Convert strings into numbers</h3><pre>let firstNumber = &quot;45&quot;;<br>let secondNumber = &quot;15&quot;;</pre><pre>firstNumber = Number(firstNumber);<br>secondNumber = Number(secondNumber);</pre><pre>console.log(firstNumber + secondNumber);<br>console.log(firstNumber - secondNumber);<br>console.log(firstNumber * secondNumber);<br>console.log(firstNumber / secondNumber);</pre><p>Output:</p><pre>60<br>30<br>675<br>3</pre><p>We convert both values before performing arithmetic.</p><h3>Solution 3: Truthy and falsy values</h3><pre>console.log(Boolean(0));       // false<br>console.log(Boolean(&quot;0&quot;));     // true<br>console.log(Boolean(&quot;&quot;));      // false<br>console.log(Boolean(&quot;false&quot;)); // true<br>console.log(Boolean(null));    // false<br>console.log(Boolean([]));      // true<br>console.log(Boolean({}));      // true<br>console.log(Boolean(NaN));     // false</pre><p>The key is to distinguish a value’s type from how it looks when printed.</p><h3>Solution 4: Handle invalid numeric input</h3><p>Here is one possible solution:</p><pre>function calculateTotal(price, quantity) {<br>    if (<br>        (typeof price === &quot;string&quot; &amp;&amp; price.trim() === &quot;&quot;) ||<br>        (typeof quantity === &quot;string&quot; &amp;&amp; quantity.trim() === &quot;&quot;)<br>    ) {<br>        return &quot;Error: Price and quantity are required.&quot;;<br>    }</pre><pre>    const numericPrice = Number(price);<br>    const numericQuantity = Number(quantity);</pre><pre>    if (<br>        !Number.isFinite(numericPrice) ||<br>        !Number.isFinite(numericQuantity)<br>    ) {<br>        return &quot;Error: Enter valid numbers.&quot;;<br>    }</pre><pre>    if (<br>        numericPrice &lt; 0 ||<br>        numericQuantity &lt; 1 ||<br>        !Number.isInteger(numericQuantity)<br>    ) {<br>        return &quot;Error: Invalid price or quantity.&quot;;<br>    }</pre><pre>    const total = numericPrice * numericQuantity;</pre><pre>    if (!Number.isFinite(total)) {<br>        return &quot;Error: Total is outside the supported range.&quot;;<br>    }</pre><pre>    return total;<br>}</pre><pre>console.log(calculateTotal(&quot;100&quot;, &quot;3&quot;));<br>console.log(calculateTotal(&quot;hello&quot;, &quot;3&quot;));<br>console.log(calculateTotal(&quot;&quot;, &quot;3&quot;));</pre><p>Output:</p><pre>300<br>Error: Enter valid numbers.<br>Error: Price and quantity are required.</pre><p>Notice that the function checks for empty strings before calling Number(). Without that check, Number(&quot;&quot;) would return zero.</p><h3>Solution 5: Discount calculator</h3><pre>function calculateDiscountedTotal(<br>    priceInput,<br>    quantityInput,<br>    discountInput<br>) {<br>    if (<br>        [priceInput, quantityInput, discountInput].some(<br>            value =&gt;<br>                typeof value === &quot;string&quot; &amp;&amp;<br>                value.trim() === &quot;&quot;<br>        )<br>    ) {<br>        return &quot;Error: All fields are required.&quot;;<br>    }</pre><pre>    const price = Number(priceInput);<br>    const quantity = Number(quantityInput);<br>    const discountPercent = Number(discountInput);</pre><pre>    if (<br>        !Number.isFinite(price) ||<br>        !Number.isFinite(quantity) ||<br>        !Number.isFinite(discountPercent)<br>    ) {<br>        return &quot;Error: Enter valid numeric values.&quot;;<br>    }</pre><pre>    if (<br>        price &lt; 0 ||<br>        quantity &lt; 1 ||<br>        !Number.isInteger(quantity) ||<br>        discountPercent &lt; 0 ||<br>        discountPercent &gt; 100<br>    ) {<br>        return &quot;Error: Check price, quantity, and discount.&quot;;<br>    }</pre><pre>    const subtotal = price * quantity;</pre><pre>    if (!Number.isFinite(subtotal)) {<br>        return &quot;Error: Subtotal is outside the supported range.&quot;;<br>    }</pre><pre>    const automaticDiscount = subtotal &gt;= 1000 ? 10 : 0;<br>    const finalDiscount = Math.max(<br>        discountPercent,<br>        automaticDiscount<br>    );</pre><pre>    const discountAmount = subtotal * finalDiscount / 100;<br>    const total = subtotal - discountAmount;</pre><pre>    if (!Number.isFinite(total)) {<br>        return &quot;Error: Total is outside the supported range.&quot;;<br>    }</pre><pre>    return {<br>        subtotal: subtotal.toFixed(2),<br>        discountPercent: finalDiscount,<br>        discountAmount: discountAmount.toFixed(2),<br>        total: total.toFixed(2)<br>    };<br>}</pre><pre>console.log(calculateDiscountedTotal(&quot;250&quot;, &quot;4&quot;, &quot;5&quot;));<br>console.log(calculateDiscountedTotal(&quot;100&quot;, &quot;2&quot;, &quot;5&quot;));</pre><p>Output:</p><pre>{<br>    subtotal: &quot;1000.00&quot;,<br>    discountPercent: 10,<br>    discountAmount: &quot;100.00&quot;,<br>    total: &quot;900.00&quot;<br>}</pre><pre>{<br>    subtotal: &quot;200.00&quot;,<br>    discountPercent: 5,<br>    discountAmount: &quot;10.00&quot;,<br>    total: &quot;190.00&quot;<br>}</pre><p>For this example, the automatic 10% discount is applied whenever the subtotal reaches ₹1,000, and the final discount is the greater of the user-entered discount and the automatic discount.</p><p>In a real billing system, you would need to decide explicitly whether discounts should be combined, maximized, or applied in a particular order.</p><h3>16. What Have We Learned?</h3><p>Let’s quickly review the important concepts from this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkrkZSOWqhCniw9L4D7GvQ.png" /></figure><p>The biggest lesson is simple: <strong>Always understand the type of a value before using it in a calculation or comparison.</strong></p><p>A form input containing &quot;100&quot; and a number containing 100 may look identical on the screen, but JavaScript can treat them differently.</p><p>Learning to recognize these differences will make your code more predictable, your calculations safer, and your debugging much easier.</p><p><strong>Previously — Part 4: </strong><a href="https://medium.com/@dhruvil.unofficial/javascript-operators-explained-arithmetic-comparison-logical-operators-and-more-eaf1c493952a?sharedUserId=dhruvil.unofficial">JavaScript Operators Explained — Arithmetic, Comparison, Logical Operators, and More</a></p><p><strong>Next — Part 6: JavaScript Conditions Explained — </strong><strong>if, </strong><strong>else, </strong><strong>else if, and </strong><strong>switch with Real Examples</strong></p><p>In the next part, we will learn how to make programs take different actions based on conditions, validate user input, and build decision-making logic.</p><p>Follow along with the series so you can practise each concept in order.</p><h3>Keep Learning</h3><p>Learning JavaScript is not about memorizing every rule. It is about understanding what your code is doing, testing your assumptions, and learning how to fix mistakes.</p><p>Run the examples, change the values, break the code, and see what happens. That is how the concepts start to make sense.</p><p><strong>Your task:</strong> Before moving to Part 6, build the bill calculator yourself without copying the complete solution. If you can explain why &quot;10&quot; + 5 becomes &quot;105&quot; and prevent that problem in your calculator, you have understood one of JavaScript&#39;s most important fundamentals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0768b0f10dc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Operators Explained — Arithmetic, Comparison, Logical Operators, and More]]></title>
            <link>https://medium.com/@dhruvil.unofficial/javascript-operators-explained-arithmetic-comparison-logical-operators-and-more-eaf1c493952a?source=rss-c2f1b6068e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaf1c493952a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[logicaloperators]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[arithmetic-operations]]></category>
            <dc:creator><![CDATA[Dhruvil Bhuva]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 11:58:14 GMT</pubDate>
            <atom:updated>2026-10-14T10:37:50.235Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*472V0FF-cLZ_u-PK90eJ8A.png" /></figure><p><strong>JavaScript From Zero to Advanced — Part 4 of 35</strong></p><p>Imagine you’re building a shopping website.</p><p>A customer adds two products to their cart. You need to calculate the total price, check whether they qualify for a discount, and decide whether to allow checkout.</p><p>Or maybe you’re building a login page. You need to check whether the user has entered the correct email and password.</p><p>How would you write these conditions in JavaScript?</p><p>This is where <strong>operators</strong> come in.</p><p>Operators are symbols or keywords that tell JavaScript to perform an operation on one or more values. You’ve already used some of them in earlier examples, such as +, =, and ===.</p><p>Let’s understand the operators you’ll use regularly, with examples you can run yourself.</p><h3>1. Arithmetic Operators — Performing Calculations</h3><p>Arithmetic operators help us perform mathematical calculations.</p><p>Let’s start with a simple example.</p><pre>let price = 500;<br>let quantity = 3;</pre><pre>let total = price * quantity;</pre><pre>console.log(total);</pre><p><strong>Output:</strong></p><pre>1500</pre><p>Here, price * quantity multiplies the price by the quantity. JavaScript stores the result in total, and console.log() displays it.</p><p>Here are the main arithmetic operators:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YU3eypZfVikcRfLgExUpXw.png" /></figure><p>Let’s try them in one program.</p><pre>let a = 10;<br>let b = 3;</pre><pre>console.log(a + b);<br>console.log(a - b);<br>console.log(a * b);<br>console.log(a / b);<br>console.log(a % b);<br>console.log(a ** b);</pre><p><strong>Output:</strong></p><pre>13<br>7<br>30<br>3.3333333333333335<br>1<br>1000</pre><p>Notice that 10 / 3 produces a decimal, while 10 % 3 gives the remainder.</p><p>The remainder operator is particularly useful when checking whether a number is even or odd.</p><pre>let number = 7;</pre><pre>console.log(number % 2);</pre><p><strong>Output:</strong></p><pre>1</pre><p>If a number is divisible by 2, its remainder is 0.</p><pre>let number = 8;</pre><pre>if (number % 2 === 0) {<br>    console.log(&quot;Even number&quot;);<br>} else {<br>    console.log(&quot;Odd number&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>Even number</pre><p>We’ll explore if...else in more detail in a future article.</p><h3>2. Assignment Operators — Storing and Updating Values</h3><p>You’ve already used the assignment operator =.</p><pre>let score = 10;</pre><p>This assigns the value 10 to the variable score.</p><p>But what if you want to increase the score without writing the variable name repeatedly?</p><p>JavaScript provides shorthand assignment operators.</p><pre>let score = 10;</pre><pre>score += 5;</pre><pre>console.log(score);</pre><p><strong>Output:</strong></p><pre>15</pre><p>The expression score += 5 is equivalent to score = score + 5 in this example.</p><p>Here are the operators you’ll commonly encounter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UW5piVnRHVluWNcgfxtHPg.png" /></figure><p>Let’s use a few together.</p><pre>let balance = 1000;</pre><pre>balance += 500;<br>console.log(balance);</pre><pre>balance -= 200;<br>console.log(balance);</pre><pre>balance *= 2;<br>console.log(balance);</pre><p><strong>Output:</strong></p><pre>1500<br>1300<br>2600</pre><p>The variable is updated after every operation. That’s why the next calculation uses the previous result.</p><p>One important distinction: = assigns a value, while === compares values. We&#39;ll cover that next.</p><h3>3. Comparison Operators — Comparing Values</h3><p>Comparison operators compare two values and return a Boolean: true or false.</p><p>For example, an application might need to check whether a customer is old enough to access a particular feature.</p><pre>let age = 22;</pre><pre>console.log(age &gt; 18);</pre><p><strong>Output:</strong></p><pre>true</pre><p>Since 22 is greater than 18, the result is true.</p><p>The main comparison operators are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1dvFGvI4DuQd6_EIhS6GQ.png" /></figure><p>Let’s look at a common beginner mistake.</p><p>== vs. ===</p><p>Both operators compare values, but they behave differently.</p><pre>console.log(5 == &quot;5&quot;);<br>console.log(5 === &quot;5&quot;);</pre><p><strong>Output:</strong></p><pre>true<br>false</pre><p>Why?</p><p>In the first comparison, == allows type conversion before comparing the values.</p><p>In the second comparison, === checks both the value and the type. One value is a number, while the other is a string, so they aren&#39;t strictly equal.</p><p>For example:</p><pre>let enteredAge = &quot;18&quot;;<br>let requiredAge = 18;</pre><pre>console.log(enteredAge == requiredAge);<br>console.log(enteredAge === requiredAge);</pre><p><strong>Output:</strong></p><pre>true<br>false</pre><p>In most everyday JavaScript code, <strong>prefer </strong><strong>=== and </strong><strong>!==</strong> unless you deliberately need the type conversion performed by the loose equality operators.</p><p>It makes your code easier to reason about and helps prevent unexpected comparisons.</p><h3>4. Logical Operators — Combining Conditions</h3><p>Sometimes a single condition isn’t enough.</p><p>Imagine a login form. A user should be allowed to log in only when their email and password are both valid.</p><p>You can combine conditions using logical operators.</p><p>JavaScript has three main logical operators:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_LyUXHefBBAlBOwVxV1yA.png" /></figure><p>Let’s understand each one.</p><h3>AND (&amp;&amp;)</h3><p>The AND operator requires both conditions to be true for the overall result to be true.</p><pre>let emailValid = true;<br>let passwordValid = true;</pre><pre>console.log(emailValid &amp;&amp; passwordValid);</pre><p><strong>Output:</strong></p><pre>true</pre><p>Now change the password condition.</p><pre>let emailValid = true;<br>let passwordValid = false;</pre><pre>console.log(emailValid &amp;&amp; passwordValid);</pre><p><strong>Output:</strong></p><pre>false</pre><p>Even though the email is valid, the password isn’t. Therefore, the combined condition is false.</p><h3>OR (||)</h3><p>The OR operator returns a truthy result if at least one condition is truthy.</p><pre>let isAdmin = false;<br>let isManager = true;</pre><pre>console.log(isAdmin || isManager);</pre><p><strong>Output:</strong></p><pre>true</pre><p>The result is true because isManager is true.</p><p>This can be useful when multiple roles are permitted to access a feature.</p><h3>NOT (!)</h3><p>The NOT operator reverses the truthiness of a value.</p><pre>let isLoggedIn = false;</pre><pre>console.log(!isLoggedIn);</pre><p><strong>Output:</strong></p><pre>true</pre><p>Since isLoggedIn is false, !isLoggedIn evaluates to true.</p><p>Here’s another example:</p><pre>let hasPermission = true;</pre><pre>if (!hasPermission) {<br>    console.log(&quot;Access denied&quot;);<br>} else {<br>    console.log(&quot;Access granted&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>Access granted</pre><p>The condition !hasPermission is false, so JavaScript executes the else block.</p><h3>5. Increment and Decrement Operators</h3><p>Increment and decrement operators are often used with counters and loops.</p><p>The increment operator ++ increases a variable by one.</p><pre>let count = 5;</pre><pre>count++;</pre><pre>console.log(count);</pre><p><strong>Output:</strong></p><pre>6</pre><p>The decrement operator -- decreases a variable by one.</p><pre>let count = 5;</pre><pre>count--;</pre><pre>console.log(count);</pre><p><strong>Output:</strong></p><pre>4</pre><h3>What’s the difference between count++ and ++count?</h3><p>Both increase the variable by one, but the value of the expression differs.</p><pre>let a = 5;<br>let b = 5;</pre><pre>console.log(a++);<br>console.log(++b);</pre><p><strong>Output:</strong></p><pre>5<br>6</pre><p>Here’s what’s happening:</p><ul><li>a++ is post-increment. It produces the old value first, then increments a.</li><li>++b is pre-increment. It increments b first, then produces the new value.</li></ul><p>After these statements, both a and b equal 6.</p><p>If you’re only writing count++ as a standalone statement, both styles of increment will update the variable. The difference matters when the expression&#39;s value is used elsewhere.</p><h3>6. The String Concatenation Operator</h3><p>You’ve already seen that + can add numbers. It can also join strings.</p><pre>let firstName = &quot;Dhruvil&quot;;<br>let lastName = &quot;Bhuva&quot;;</pre><pre>let fullName = firstName + &quot; &quot; + lastName;</pre><pre>console.log(fullName);</pre><p><strong>Output:</strong></p><pre>Dhruvil Bhuva</pre><p>But there’s something worth remembering: when a string and a number are used with +, JavaScript may concatenate them instead of adding them.</p><pre>console.log(10 + 5);<br>console.log(&quot;10&quot; + 5);</pre><p><strong>Output:</strong></p><pre>15<br>105</pre><p>This is one reason it’s important to understand data types before working with operators.</p><p>If you’re dealing with user input from a form, don’t assume a numeric-looking string is already a number.</p><p>For example:</p><pre>let firstValue = &quot;10&quot;;<br>let secondValue = &quot;5&quot;;</pre><pre>console.log(Number(firstValue) + Number(secondValue));</pre><p><strong>Output:</strong></p><pre>15</pre><p>Here, Number() converts both strings into numbers before addition.</p><p>Always validate user input appropriately when building real applications.</p><h3>7. The Ternary Operator — A Shorter Conditional Expression</h3><p>The ternary operator provides a compact way to choose between two expressions based on a condition.</p><p>Its syntax is:</p><pre>condition ? valueIfTrue : valueIfFalse</pre><p>Let’s see an example.</p><pre>let age = 20;</pre><pre>let message = age &gt;= 18 ? &quot;Adult&quot; : &quot;Minor&quot;;</pre><pre>console.log(message);</pre><p><strong>Output:</strong></p><pre>Adult</pre><p>Read the expression like this:</p><ul><li>If age &gt;= 18 is true, use &quot;Adult&quot;.</li><li>Otherwise, use &quot;Minor&quot;.</li></ul><p>The same logic can be written with if...else.</p><pre>let age = 20;<br>let message;</pre><pre>if (age &gt;= 18) {<br>    message = &quot;Adult&quot;;<br>} else {<br>    message = &quot;Minor&quot;;<br>}</pre><pre>console.log(message);</pre><p>Both examples produce the same output.</p><p>The ternary operator is useful for simple choices. If the logic becomes complicated or involves multiple steps, an ordinary if...else statement is usually easier to read.</p><h3>8. The Nullish Coalescing Operator (??)</h3><p>This operator is especially useful when working with optional values.</p><p>The nullish coalescing operator returns the value on the right only when the value on the left is null or undefined.</p><pre>let username = null;</pre><pre>let displayName = username ?? &quot;Guest&quot;;</pre><pre>console.log(displayName);</pre><p><strong>Output:</strong></p><pre>Guest</pre><p>Since username is null, JavaScript uses &quot;Guest&quot;.</p><p>Now consider this example:</p><pre>let username = &quot;&quot;;</pre><pre>let displayName = username ?? &quot;Guest&quot;;</pre><pre>console.log(displayName);</pre><p><strong>Output:</strong></p><pre>Guest</pre><p>The output is an empty line because an empty string is neither null nor undefined.</p><p>This is different from the OR operator (||).</p><pre>console.log(&quot;&quot; || &quot;Guest&quot;);<br>console.log(&quot;&quot; ?? &quot;Guest&quot;);</pre><p><strong>Output:</strong></p><pre>Guest</pre><p>The first expression uses &quot;Guest&quot; because an empty string is falsy. The second keeps the empty string because it isn&#39;t nullish.</p><p>Use ?? when you want to provide a default specifically for missing values without replacing valid values such as 0, false, or &quot;&quot;.</p><h3>9. The typeof Operator</h3><p>In Part 3, we used typeof to check data types. It&#39;s worth revisiting because it helps explain how operators work with different values.</p><pre>let name = &quot;Dhruvil&quot;;<br>let age = 25;<br>let isDeveloper = true;</pre><pre>console.log(typeof name);<br>console.log(typeof age);<br>console.log(typeof isDeveloper);</pre><p><strong>Output:</strong></p><pre>string<br>number<br>boolean</pre><p>You can use typeof when debugging or inspecting a value whose type you&#39;re unsure about.</p><p>Remember that typeof null returns &quot;object&quot; because of a historical JavaScript quirk. To check whether something is an array, use Array.isArray() instead.</p><h3>10. Operator Precedence — Which Operation Happens First?</h3><p>Consider this expression:</p><pre>console.log(10 + 5 * 2);</pre><p>What do you think the output will be?</p><p>You might calculate 10 + 5 first and then multiply by 2. But JavaScript follows operator precedence.</p><p><strong>Output:</strong></p><pre>20</pre><p>Multiplication has higher precedence than addition, so JavaScript evaluates the expression as:</p><pre>10 + (5 * 2)</pre><p>The result is 20.</p><p>If you want addition to happen first, use parentheses.</p><pre>console.log((10 + 5) * 2);</pre><p><strong>Output:</strong></p><pre>30</pre><p>Parentheses make the intended order clear.</p><p>When an expression contains several operators, don’t rely on memory alone. Use parentheses to make complicated calculations easier to understand.</p><h3>11. A Practical Example — Shopping Cart Total</h3><p>Let’s put several operators together in a small example.</p><p>Suppose a customer buys three items at ₹500 each. They receive a ₹200 discount if their total is at least ₹1,000.</p><pre>let price = 500;<br>let quantity = 3;</pre><pre>let subtotal = price * quantity;<br>let discount = subtotal &gt;= 1000 ? 200 : 0;<br>let finalTotal = subtotal - discount;</pre><pre>console.log(&quot;Subtotal: ₹&quot; + subtotal);<br>console.log(&quot;Discount: ₹&quot; + discount);<br>console.log(&quot;Final total: ₹&quot; + finalTotal);</pre><p><strong>Output:</strong></p><pre>Subtotal: ₹1500<br>Discount: ₹200<br>Final total: ₹1300</pre><p>Let’s break it down:</p><ol><li>price * quantity calculates the subtotal.</li><li>subtotal &gt;= 1000 checks whether the order qualifies for the discount.</li><li>The ternary operator selects either 200 or 0.</li><li>subtotal - discount calculates the final total.</li><li>console.log() displays the result.</li></ol><p>This example combines arithmetic, comparison, and conditional operators in a way you might encounter in a real application.</p><p>For production billing systems, monetary calculations need additional care to avoid floating-point precision issues. This example uses whole-rupee amounts to keep the basic logic easy to follow.</p><h3>12. Practice Tasks</h3><p>Now it’s your turn. Try to solve these without immediately looking back at the examples.</p><h3>Task 1: Basic calculations</h3><p>Create two variables, a = 20 and b = 6.</p><p>Print their sum, difference, product, quotient, and remainder.</p><h3>Task 2: Comparison challenge</h3><p>Predict the output of each expression before running the code.</p><pre>console.log(10 &gt; 5);<br>console.log(10 === &quot;10&quot;);<br>console.log(7 !== 3);<br>console.log(15 &lt;= 15);</pre><h3>Task 3: Login validation</h3><p>Create two Boolean variables:</p><pre>let emailValid = true;<br>let passwordValid = false;</pre><p>Use &amp;&amp; to check whether both are valid. Then change the values and test again.</p><h3>Task 4: Even or odd</h3><p>Create a variable called number.</p><p>Use the remainder operator and an if...else statement to print whether the number is even or odd.</p><p>Your solution should work when you change the number.</p><h3>Task 5: Discount calculator</h3><p>Write a program with these rules:</p><ul><li>Store a product price and quantity.</li><li>Calculate the subtotal.</li><li>If the subtotal is ₹2,000 or more, apply a ₹250 discount.</li><li>Otherwise, apply no discount.</li><li>Print the subtotal, discount, and final amount.</li></ul><p>Test your code with different prices and quantities.</p><h3>Task 6: Predict before running</h3><p>What will this program print?</p><pre>let score = 10;</pre><pre>console.log(score++);<br>console.log(score);<br>console.log(++score);<br>console.log(score);</pre><p>Write down your prediction, run the program, and explain why each result appears.</p><p><strong>A small challenge:</strong> Try to explain each answer in your own words. If you can explain why the output occurs instead of just memorizing it, you’re making real progress.</p><h3>Conclusion</h3><p>Operators may look like small symbols, but they’re part of almost every JavaScript program.</p><p>You’ll use them to calculate totals, compare values, validate forms, combine conditions, update counters, and make decisions.</p><p>You don’t need to memorize every operator today. Start with arithmetic, assignment, comparison, and logical operators. Once those feel comfortable, practise the ternary and nullish coalescing operators.</p><p>The best way to learn is simple: change the values, predict the output, run the program, and investigate anything that surprises you.</p><p>In the next part, we’ll move on to <strong>JavaScript Type Conversion and Coercion</strong> to understand how JavaScript converts values between strings, numbers, and Booleans — and why expressions such as &quot;10&quot; + 5 can produce unexpected results.</p><h3>Continue the JavaScript Series</h3><p><strong>Previously — Part 3:</strong> <a href="https://medium.com/@dhruvil.unofficial/javascript-variables-and-data-types-strings-numbers-booleans-and-more-3562817c361f?sharedUserId=dhruvil.unofficial">JavaScript Variables and Data Types — Strings, Numbers, Booleans, and More.</a></p><p><strong>Next — Part 5: </strong><a href="https://medium.com/@dhruvil.unofficial/javascript-type-conversion-and-coercion-why-10-5-becomes-105-0768b0f10dc5?sharedUserId=dhruvil.unofficial">JavaScript Type Conversion and Coercion — Why </a><a href="https://medium.com/@dhruvil.unofficial/javascript-type-conversion-and-coercion-why-10-5-becomes-105-0768b0f10dc5?sharedUserId=dhruvil.unofficial">&quot;10&quot; + 5 Becomes </a><a href="https://medium.com/@dhruvil.unofficial/javascript-type-conversion-and-coercion-why-10-5-becomes-105-0768b0f10dc5?sharedUserId=dhruvil.unofficial">&quot;105&quot;.</a></p><p><em>If you’re following this series, save this article for practice and follow along as we work through JavaScript one concept at a time.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaf1c493952a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Variables and Data Types — Strings, Numbers, Booleans, and More]]></title>
            <link>https://medium.com/@dhruvil.unofficial/javascript-variables-and-data-types-strings-numbers-booleans-and-more-3562817c361f?source=rss-c2f1b6068e6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3562817c361f</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dhruvil Bhuva]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 10:23:44 GMT</pubDate>
            <atom:updated>2026-10-13T10:30:13.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-52UcxRLfHTZts_homi8g.png" /></figure><p><strong>JavaScript From Zero to Advanced — Part 3 of 35</strong></p><p>Have you ever wondered how JavaScript knows whether something is a name, a number, or a simple true or false value?</p><p>For example:</p><pre>let name = &quot;Dhruvil&quot;;<br>let age = 25;<br>let isDeveloper = true;</pre><p>All three variables store different kinds of information.</p><ul><li>&quot;Dhruvil&quot; is text.</li><li>25 is a number.</li><li>true is a Boolean value.</li></ul><p>These different kinds of values are called <strong>data types</strong>.</p><p>In this article, we’ll understand JavaScript data types with simple examples, practical tasks, and explanations of what happens when we run the code.</p><h3>1. What Is a Data Type?</h3><p>A data type describes the kind of value a variable contains.</p><p>Consider this example:</p><pre>let username = &quot;Dhruvil&quot;;<br>let followers = 1200;<br>let isFollowing = false;</pre><pre>console.log(username);<br>console.log(followers);<br>console.log(isFollowing);</pre><p><strong>Output:</strong></p><pre>Dhruvil<br>1200<br>false</pre><p>Let’s understand it line by line.</p><ul><li>let username = &quot;Dhruvil&quot;; stores text in the username variable.</li><li>let followers = 1200; stores a number in the followers variable.</li><li>let isFollowing = false; stores a Boolean value in the isFollowing variable.</li><li>The console.log() statements display the stored values.</li></ul><p>JavaScript determines the type of each value automatically.</p><h3>2. String — Working with Text</h3><p>A <strong>String</strong> is used to represent text.</p><p>Examples include names, email addresses, messages, and product titles.</p><pre>let firstName = &quot;Dhruvil&quot;;<br>let company = &#39;Shivvilon Solutions&#39;;<br>let message = &quot;Welcome to JavaScript!&quot;;</pre><pre>console.log(firstName);<br>console.log(company);<br>console.log(message);</pre><p><strong>Output:</strong></p><pre>Dhruvil<br>Shivvilon Solutions<br>Welcome to JavaScript!</pre><p>Strings can be written using single quotes (&#39; &#39;), double quotes (&quot; &quot;), or backticks (` `).</p><h3>Combining strings</h3><p>Suppose you want to display a welcome message using a person’s name.</p><pre>let name = &quot;Dhruvil&quot;;</pre><pre>let message = &quot;Hello, &quot; + name + &quot;!&quot;;</pre><pre>console.log(message);</pre><p><strong>Output:</strong></p><pre>Hello, Dhruvil!</pre><p>The + operator joins the strings together. This process is called <strong>string concatenation</strong>.</p><h3>A cleaner approach: Template literals</h3><p>JavaScript also supports template literals using backticks.</p><pre>let name = &quot;Dhruvil&quot;;<br>let company = &quot;Shivvilon Solutions&quot;;</pre><pre>let message = `Hello, ${name}! Welcome to ${company}.`;</pre><pre>console.log(message);</pre><p><strong>Output:</strong></p><pre>Hello, Dhruvil! Welcome to Shivvilon Solutions.</pre><p>The ${...} syntax lets you insert a variable or expression directly into a string.</p><p><strong>Remember:</strong> Normal quotes and backticks are not interchangeable when using ${...} interpolation. Template literals require backticks.</p><h3>3. Number — Working with Numbers</h3><p>The Number type is used for both integers and decimal values.</p><pre>let age = 22;<br>let price = 499.99;<br>let temperature = -5;</pre><pre>console.log(age);<br>console.log(price);<br>console.log(temperature);</pre><p><strong>Output:</strong></p><pre>22<br>499.99<br>-5</pre><p>You can also perform mathematical operations.</p><pre>let firstNumber = 10;<br>let secondNumber = 5;</pre><pre>console.log(firstNumber + secondNumber);<br>console.log(firstNumber - secondNumber);<br>console.log(firstNumber * secondNumber);<br>console.log(firstNumber / secondNumber);</pre><p><strong>Output:</strong></p><pre>15<br>5<br>50<br>2</pre><p>The operators mean:</p><ul><li>+ — Addition</li><li>- — Subtraction</li><li>* — Multiplication</li><li>/ — Division</li><li>% — Remainder after division</li></ul><p>For example:</p><pre>console.log(10 % 3);</pre><p><strong>Output:</strong></p><pre>1</pre><p>Why? Because 10 divided by 3 leaves a remainder of 1.</p><h3>An important JavaScript detail</h3><p>JavaScript’s Number type handles both integers and decimal numbers. Unlike some other programming languages, you generally don&#39;t need separate types for integers and floating-point numbers.</p><p>However, calculations involving decimal values can sometimes produce unexpected-looking results.</p><pre>console.log(0.1 + 0.2);</pre><p><strong>Output:</strong></p><pre>0.30000000000000004</pre><p>This happens because many decimal fractions cannot be represented exactly in binary floating-point arithmetic.</p><p>It’s a useful detail to remember when working with money or precise calculations.</p><h3>4. Boolean — True or False</h3><p>A <strong>Boolean</strong> has only two possible values:</p><ul><li>true</li><li>false</li></ul><p>Booleans are commonly used for conditions, login status, permissions, and decision-making.</p><pre>let isLoggedIn = true;<br>let hasPermission = false;</pre><pre>console.log(isLoggedIn);<br>console.log(hasPermission);</pre><p><strong>Output:</strong></p><pre>true<br>false</pre><p>Let’s use a Boolean in a real-world example.</p><pre>let isLoggedIn = true;</pre><pre>if (isLoggedIn) {<br>    console.log(&quot;Welcome back!&quot;);<br>} else {<br>    console.log(&quot;Please log in.&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>Welcome back!</pre><p>Because isLoggedIn is true, JavaScript executes the first block.</p><p>We’ll explore if...else statements in more detail in a later part of this series.</p><h3>5. Undefined — A Value That Has Not Been Assigned</h3><p>When you declare a variable without assigning it a value, its value is undefined.</p><pre>let email;</pre><pre>console.log(email);</pre><p><strong>Output:</strong></p><pre>undefined</pre><p>JavaScript knows that the variable exists, but no value has been assigned to it.</p><p>You can check its type:</p><pre>let email;</pre><pre>console.log(typeof email);</pre><p><strong>Output:</strong></p><pre>undefined</pre><p>Here, typeof is an operator that tells us the type of a value.</p><h3>6. Null — Intentionally Empty</h3><p>null represents an intentionally empty or absent value.</p><pre>let selectedProduct = null;</pre><pre>console.log(selectedProduct);</pre><p><strong>Output:</strong></p><pre>null</pre><p>Imagine an online shopping website where a user hasn’t selected a product yet. You might use null to represent that state.</p><h3>undefined vs. null</h3><p>These values are related, but they are not the same.</p><pre>let firstValue;<br>let secondValue = null;</pre><pre>console.log(firstValue);<br>console.log(secondValue);</pre><p><strong>Output:</strong></p><pre>undefined<br>null</pre><p>A simple way to remember the difference:</p><ul><li>undefined: A value hasn&#39;t been assigned.</li><li>null: An empty value has been intentionally assigned.</li></ul><p>One interesting JavaScript quirk:</p><pre>console.log(typeof null);</pre><p><strong>Output:</strong></p><pre>object</pre><p>This is a long-standing historical behavior in JavaScript. It does not mean that null is actually an object; null is a primitive value.</p><h3>7. Object — Grouping Related Information</h3><p>An <strong>Object</strong> lets you group related information using key-value pairs.</p><p>Instead of creating separate variables for every detail about a user, you can store the details together.</p><pre>let user = {<br>    name: &quot;Dhruvil&quot;,<br>    age: 22,<br>    isDeveloper: true<br>};</pre><pre>console.log(user);</pre><p><strong>Output:</strong></p><pre>{<br>    name: &quot;Dhruvil&quot;,<br>    age: 22,<br>    isDeveloper: true<br>}</pre><p>You can access individual properties using dot notation.</p><pre>console.log(user.name);<br>console.log(user.age);<br>console.log(user.isDeveloper);</pre><p><strong>Output:</strong></p><pre>Dhruvil<br>22<br>true</pre><p>This is especially useful when building websites, APIs, dashboards, and applications that work with user or product data.</p><h3>8. Array — Storing Multiple Values</h3><p>An <strong>Array</strong> stores an ordered collection of values.</p><p>For example, a list of programming languages:</p><pre>let languages = [&quot;JavaScript&quot;, &quot;Python&quot;, &quot;Java&quot;, &quot;PHP&quot;];</pre><pre>console.log(languages);</pre><p><strong>Output:</strong></p><pre>[&quot;JavaScript&quot;, &quot;Python&quot;, &quot;Java&quot;, &quot;PHP&quot;]</pre><p>Array positions are called indexes, and they start at 0.</p><pre>console.log(languages[0]);<br>console.log(languages[1]);<br>console.log(languages[2]);</pre><p><strong>Output:</strong></p><pre>JavaScript<br>Python<br>Java</pre><p>The first item is at index 0, the second at index 1, and the third at index 2.</p><p>You can also find how many items an array contains:</p><pre>console.log(languages.length);</pre><p><strong>Output:</strong></p><pre>4</pre><p>Arrays are objects in JavaScript, but they are designed specifically for ordered collections of values.</p><h3>9. Symbol and BigInt — Two More Types</h3><p>JavaScript has two additional primitive types that you’ll encounter as you progress.</p><h3>Symbol</h3><p>A Symbol creates a unique value, often used as a special property key.</p><pre>let id = Symbol(&quot;id&quot;);</pre><pre>console.log(typeof id);</pre><p><strong>Output:</strong></p><pre>symbol</pre><p>You don’t need to use Symbols every day as a beginner, but it’s good to know they exist.</p><h3>BigInt</h3><p>A BigInt represents integers larger than the range that JavaScript&#39;s regular Number type can represent safely.</p><pre>let largeNumber = 123456789012345678901234567890n;</pre><pre>console.log(largeNumber);<br>console.log(typeof largeNumber);</pre><p><strong>Output:</strong></p><pre>123456789012345678901234567890n<br>bigint</pre><p>The n at the end tells JavaScript that this is a BigInt literal.</p><p>For everyday calculations, regular numbers are usually sufficient.</p><h3>10. Check Data Types with typeof</h3><p>The typeof operator is one of the easiest ways to inspect a value while learning JavaScript.</p><pre>console.log(typeof &quot;Hello&quot;);<br>console.log(typeof 100);<br>console.log(typeof true);<br>console.log(typeof undefined);<br>console.log(typeof 10n);<br>console.log(typeof Symbol(&quot;id&quot;));<br>console.log(typeof {});<br>console.log(typeof []);</pre><p><strong>Output:</strong></p><pre>string<br>number<br>boolean<br>undefined<br>bigint<br>symbol<br>object<br>object</pre><p>Notice that both {} and [] return &quot;object&quot;.</p><p>That is because arrays are objects in JavaScript. To check whether a value is an array, use:</p><pre>console.log(Array.isArray([]));<br>console.log(Array.isArray({}));</pre><p><strong>Output:</strong></p><pre>true<br>false</pre><p>This is more reliable than using typeof alone to identify arrays.</p><h3>11. Primitive vs. Non-Primitive Values</h3><p>JavaScript’s data types are commonly grouped into two broad categories.</p><p><strong>Primitive types:</strong></p><ul><li>String</li><li>Number</li><li>Boolean</li><li>Undefined</li><li>Null</li><li>BigInt</li><li>Symbol</li></ul><p><strong>Objects and other reference-based values:</strong></p><ul><li>Objects</li><li>Arrays</li><li>Functions</li><li>Other object types, such as dates</li></ul><p>Primitive values represent individual values. Objects can group information or provide more complex behavior.</p><p>For now, focus on recognizing the types and understanding when to use them. We’ll explore how they behave when assigned or passed around in a later article.</p><h3>12. Common Beginner Mistakes</h3><h3>Mistake 1: Writing text without quotes</h3><p>Incorrect:</p><pre>let name = Dhruvil;</pre><p>JavaScript treats Dhruvil as an identifier rather than text. If no such variable exists, this causes a ReferenceError.</p><p>Correct:</p><pre>let name = &quot;Dhruvil&quot;;</pre><h3>Mistake 2: Confusing a number with a string</h3><pre>console.log(10 + 5);<br>console.log(&quot;10&quot; + 5);</pre><p><strong>Output:</strong></p><pre>15<br>105</pre><p>In the second example, the string and number are combined into a string. The + operator can perform either addition or concatenation, depending on the values.</p><h3>Mistake 3: Using quotes around a Boolean</h3><pre>let firstValue = true;<br>let secondValue = &quot;true&quot;;</pre><pre>console.log(typeof firstValue);<br>console.log(typeof secondValue);</pre><p><strong>Output:</strong></p><pre>boolean<br>string</pre><p>true is a Boolean, while &quot;true&quot; is text.</p><h3>Mistake 4: Assuming null and undefined are identical</h3><p>They may both represent an absence of useful data, but JavaScript treats them as distinct values.</p><pre>console.log(null === undefined);</pre><p><strong>Output:</strong></p><pre>false</pre><p>The === operator checks strict equality without converting the types.</p><h3>13. Practice Tasks</h3><p>Now it’s your turn to practise. Try these tasks before looking at the solutions.</p><h3>Task 1: Identify the data types</h3><p>Create five variables:</p><ul><li>Your name</li><li>Your age</li><li>Whether you are learning JavaScript</li><li>Your favourite programming language</li><li>A variable with no assigned value</li></ul><p>Print each value and its type using console.log() and typeof.</p><h3>Task 2: Build a simple product card</h3><p>Create an object named product with these properties:</p><ul><li>name</li><li>price</li><li>inStock</li></ul><p>Print each property separately.</p><h3>Task 3: Work with arrays</h3><p>Create an array containing five programming languages.</p><p>Print the first item, the third item, and the total number of items.</p><h3>Task 4: Predict the output</h3><p>Before running the code, write down what you think each line will print.</p><pre>console.log(typeof &quot;22&quot;);<br>console.log(typeof 22);<br>console.log(typeof false);<br>console.log(typeof null);<br>console.log(typeof []);<br>console.log(5 + &quot;5&quot;);</pre><p>Then run the code and compare your answers.</p><h3>Task 5: Mini challenge — User profile</h3><p>Create an object named user containing:</p><ul><li>name</li><li>age</li><li>isStudent</li><li>skills (an array of three skills)</li><li>email (set to null)</li></ul><p>Print every property and use typeof to inspect the relevant values. Also use Array.isArray() to check the skills property.</p><p>Try completing all five tasks independently. Understanding comes from writing and running the code, not just reading it.</p><h3>Conclusion</h3><p>JavaScript data types are the foundation of everything you’ll build with the language.</p><p>You now know how to work with strings, numbers, Booleans, undefined, null, objects, arrays, Symbols, and BigInts. You also learned how to inspect values using typeof and avoid common beginner mistakes.</p><p>Don’t worry about memorizing every detail immediately. Write small programs, change the values, predict the output, and run the code to see what happens.</p><p>The more you practise, the more natural these concepts will become.</p><h3>Continue the JavaScript Series</h3><p><strong>Previously — Part 2: </strong><a href="https://medium.com/@dhruvil.unofficial/javascript-let-const-and-var-explained-line-by-line-which-one-should-you-actually-use-984186fa9325?sharedUserId=dhruvil.unofficial">JavaScript </a><a href="https://medium.com/@dhruvil.unofficial/javascript-let-const-and-var-explained-line-by-line-which-one-should-you-actually-use-984186fa9325?sharedUserId=dhruvil.unofficial">let, </a><a href="https://medium.com/@dhruvil.unofficial/javascript-let-const-and-var-explained-line-by-line-which-one-should-you-actually-use-984186fa9325?sharedUserId=dhruvil.unofficial">const, and </a><a href="https://medium.com/@dhruvil.unofficial/javascript-let-const-and-var-explained-line-by-line-which-one-should-you-actually-use-984186fa9325?sharedUserId=dhruvil.unofficial">var Explained Line by Line — Which One Should You Actually Use?</a></p><p><strong>Next — Part 4: </strong>JavaScript Operators Explained — Arithmetic, Comparison, Logical Operators, and More.</p><p>Follow along with the series as we progress from JavaScript fundamentals to practical projects.</p><p><em>If this article helped you, clap for it, share it with another beginner, and follow for the next part of the series.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3562817c361f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>