<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: gautam kumar</title>
    <description>The latest articles on Forem by gautam kumar (@gautam_kumar_d3daad738680).</description>
    <link>https://forem.com/gautam_kumar_d3daad738680</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2340321%2F2ef2bb05-dc84-4f78-be29-e8d0bdefdc38.jpg</url>
      <title>Forem: gautam kumar</title>
      <link>https://forem.com/gautam_kumar_d3daad738680</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/gautam_kumar_d3daad738680"/>
    <language>en</language>
    <item>
      <title>LangChain + Supabase Vector Store (pgvector) - A Beginner‑Friendly Guide</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Wed, 10 Sep 2025 18:05:32 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/langchain-supabase-vector-store-pgvector-a-beginner-friendly-guide-5h33</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/langchain-supabase-vector-store-pgvector-a-beginner-friendly-guide-5h33</guid>
      <description>&lt;h2&gt;
  
  
  LangChain + Supabase Vector Store (pgvector) - A Beginner‑Friendly Guide
&lt;/h2&gt;

&lt;p&gt;This guide walks you through building a tiny semantic search demo using:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;LangChain.js&lt;/strong&gt; - to orchestrate embeddings and vector search
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Supabase&lt;/strong&gt; (Postgres + &lt;strong&gt;pgvector&lt;/strong&gt;) - to store your vectors and query them efficiently
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;OpenAI embeddings&lt;/strong&gt; - we’ll use &lt;code&gt;text-embedding-3-small&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By the end, you’ll be able to &lt;strong&gt;insert documents&lt;/strong&gt; into a Supabase table and &lt;strong&gt;query similar text&lt;/strong&gt; with just a few lines of code.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Never hardcode real API keys&lt;/strong&gt; in code. Use environment variables. Also, &lt;strong&gt;do not expose your Supabase Service Role Key&lt;/strong&gt; to the browser-keep it server-side only.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  What you’ll build
&lt;/h2&gt;

&lt;p&gt;We’ll index 4 short facts into a &lt;code&gt;documents&lt;/code&gt; table and then ask a question:  &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;“Mitochondria are made of what?”  &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The code will return the most similar document (spoiler: the one explaining mitochondria).&lt;/p&gt;

&lt;h2&gt;
  
  
  How vector search works (in plain English)
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Embed text&lt;/strong&gt;: Convert text into high‑dimensional vectors using an embedding model.
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Store vectors&lt;/strong&gt;: Save those vectors in Postgres via &lt;strong&gt;pgvector&lt;/strong&gt; (the &lt;code&gt;vector&lt;/code&gt; data type).
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Search&lt;/strong&gt;: Embed the user’s query and &lt;strong&gt;find nearest neighbors&lt;/strong&gt; (cosine similarity / distance).
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That’s it. No keywords, no exact string matching-&lt;strong&gt;semantic&lt;/strong&gt; similarity does the heavy lifting.&lt;/p&gt;




&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Node.js 18+&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;Supabase project&lt;/strong&gt; (free tier is fine)&lt;/li&gt;
&lt;li&gt;An &lt;strong&gt;OpenAI API key&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Basic terminal familiarity&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  1) Create a new project
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;mkdir &lt;/span&gt;lc-supabase-demo
&lt;span class="nb"&gt;cd &lt;/span&gt;lc-supabase-demo
npm init &lt;span class="nt"&gt;-y&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use ESM imports (since our code uses &lt;code&gt;import&lt;/code&gt;). Add &lt;code&gt;"type": "module"&lt;/code&gt; to your &lt;code&gt;package.json&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"lc-supabase-demo"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"version"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"1.0.0"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"module"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="nl"&gt;"scripts"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"dev"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"node index.mjs"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"seed"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"node seed.mjs"&lt;/span&gt;&lt;span class="w"&gt;
  &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2) Install dependencies
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm i @langchain/community @langchain/openai @supabase/supabase-js dotenv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;@langchain/community&lt;/code&gt; – community integrations (Supabase vector store lives here)
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;@langchain/openai&lt;/code&gt; – OpenAI embeddings and chat models for LangChain
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;@supabase/supabase-js&lt;/code&gt; – Supabase client SDK
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;dotenv&lt;/code&gt; – load env variables from &lt;code&gt;.env&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3) Create your &lt;code&gt;.env&lt;/code&gt; (do &lt;strong&gt;not&lt;/strong&gt; commit this)
&lt;/h2&gt;

&lt;p&gt;Create a file named &lt;code&gt;.env&lt;/code&gt; in the project root:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="nb"&gt;touch&lt;/span&gt; .env
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Put the following into &lt;code&gt;.env&lt;/code&gt; (replace with your values):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# OpenAI&lt;/span&gt;
&lt;span class="nv"&gt;OPENAI_API_KEY&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;sk-your-openai-key

&lt;span class="c"&gt;# Supabase&lt;/span&gt;
&lt;span class="nv"&gt;SUPABASE_URL&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;https://your-project-id.supabase.co
&lt;span class="c"&gt;# Service role key must be kept server-side only (NEVER expose in frontend code)&lt;/span&gt;
&lt;span class="nv"&gt;SUPABASE_SERVICE_ROLE_KEY&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;your-service-role-key
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4) Prepare your database (Supabase)
&lt;/h2&gt;

&lt;p&gt;Open your Supabase dashboard -&amp;gt; &lt;strong&gt;SQL Editor&lt;/strong&gt;. Run the SQL below to enable pgvector, create a table, index it, and add an RPC function for searching.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you prefer &lt;strong&gt;UUID&lt;/strong&gt; ids, use the first block and &lt;strong&gt;don’t&lt;/strong&gt; pass custom &lt;code&gt;ids&lt;/code&gt; when inserting. If you want to pass string ids like &lt;code&gt;"1"&lt;/code&gt;, use the &lt;strong&gt;Text ID&lt;/strong&gt; variant.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  4.1 Enable &lt;code&gt;pgvector&lt;/code&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- The extension name is "vector"&lt;/span&gt;
&lt;span class="k"&gt;create&lt;/span&gt; &lt;span class="n"&gt;extension&lt;/span&gt; &lt;span class="n"&gt;if&lt;/span&gt; &lt;span class="k"&gt;not&lt;/span&gt; &lt;span class="k"&gt;exists&lt;/span&gt; &lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.2 Create the &lt;code&gt;documents&lt;/code&gt; table (UUID id)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;create&lt;/span&gt; &lt;span class="k"&gt;table&lt;/span&gt; &lt;span class="n"&gt;if&lt;/span&gt; &lt;span class="k"&gt;not&lt;/span&gt; &lt;span class="k"&gt;exists&lt;/span&gt; &lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;documents&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="n"&gt;uuid&lt;/span&gt; &lt;span class="k"&gt;primary&lt;/span&gt; &lt;span class="k"&gt;key&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="n"&gt;gen_random_uuid&lt;/span&gt;&lt;span class="p"&gt;(),&lt;/span&gt;
  &lt;span class="n"&gt;content&lt;/span&gt; &lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;metadata&lt;/span&gt; &lt;span class="n"&gt;jsonb&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;embedding&lt;/span&gt; &lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1536&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="c1"&gt;-- matches OpenAI text-embedding-3-small&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;OR&lt;/strong&gt; (Text ID, if you plan to insert ids like "1","2"):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;create&lt;/span&gt; &lt;span class="k"&gt;table&lt;/span&gt; &lt;span class="n"&gt;if&lt;/span&gt; &lt;span class="k"&gt;not&lt;/span&gt; &lt;span class="k"&gt;exists&lt;/span&gt; &lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;documents&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="nb"&gt;text&lt;/span&gt; &lt;span class="k"&gt;primary&lt;/span&gt; &lt;span class="k"&gt;key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;content&lt;/span&gt; &lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;metadata&lt;/span&gt; &lt;span class="n"&gt;jsonb&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;embedding&lt;/span&gt; &lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1536&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;1536&lt;/code&gt; matches the default dimensionality for &lt;code&gt;text-embedding-3-small&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  4.3 Optional index for faster search (cosine)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;create&lt;/span&gt; &lt;span class="k"&gt;index&lt;/span&gt; &lt;span class="n"&gt;if&lt;/span&gt; &lt;span class="k"&gt;not&lt;/span&gt; &lt;span class="k"&gt;exists&lt;/span&gt; &lt;span class="n"&gt;documents_embedding_idx&lt;/span&gt;
&lt;span class="k"&gt;on&lt;/span&gt; &lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;documents&lt;/span&gt;
&lt;span class="k"&gt;using&lt;/span&gt; &lt;span class="n"&gt;ivfflat&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;embedding&lt;/span&gt; &lt;span class="n"&gt;vector_cosine_ops&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;with&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;lists&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;IVFFlat speeds up ANN (approximate nearest neighbor) search. You can tune &lt;code&gt;lists&lt;/code&gt; later.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  4.4 Create the &lt;code&gt;match_documents&lt;/code&gt; RPC
&lt;/h3&gt;

&lt;p&gt;This function returns the &lt;em&gt;top‑N most similar&lt;/em&gt; rows using &lt;strong&gt;cosine distance&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;create&lt;/span&gt; &lt;span class="k"&gt;or&lt;/span&gt; &lt;span class="k"&gt;replace&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;match_documents&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="n"&gt;query_embedding&lt;/span&gt; &lt;span class="n"&gt;vector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1536&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
  &lt;span class="n"&gt;match_count&lt;/span&gt; &lt;span class="nb"&gt;int&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;filter&lt;/span&gt; &lt;span class="n"&gt;jsonb&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="s1"&gt;'{}'&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;returns&lt;/span&gt; &lt;span class="k"&gt;table&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
  &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;content&lt;/span&gt; &lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;metadata&lt;/span&gt; &lt;span class="n"&gt;jsonb&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="n"&gt;similarity&lt;/span&gt; &lt;span class="nb"&gt;float&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;language&lt;/span&gt; &lt;span class="n"&gt;plpgsql&lt;/span&gt;
&lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="err"&gt;$$&lt;/span&gt;
&lt;span class="k"&gt;begin&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt;
  &lt;span class="k"&gt;select&lt;/span&gt;
    &lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;::&lt;/span&gt;&lt;span class="nb"&gt;text&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;content&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;embedding&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;query_embedding&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;as&lt;/span&gt; &lt;span class="n"&gt;similarity&lt;/span&gt;
  &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="k"&gt;public&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;documents&lt;/span&gt; &lt;span class="n"&gt;d&lt;/span&gt;
  &lt;span class="k"&gt;where&lt;/span&gt; &lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;metadata&lt;/span&gt; &lt;span class="o"&gt;@&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;filter&lt;/span&gt;
  &lt;span class="k"&gt;order&lt;/span&gt; &lt;span class="k"&gt;by&lt;/span&gt; &lt;span class="n"&gt;d&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;embedding&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;query_embedding&lt;/span&gt;  &lt;span class="c1"&gt;-- cosine distance (smaller is closer)&lt;/span&gt;
  &lt;span class="k"&gt;limit&lt;/span&gt; &lt;span class="n"&gt;match_count&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;end&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="err"&gt;$$&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;If you used &lt;code&gt;uuid&lt;/code&gt; for &lt;code&gt;id&lt;/code&gt;, you can still cast to &lt;code&gt;text&lt;/code&gt; in the return shape as shown.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  5) Project structure
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lc-supabase-demo/
├─ .env
├─ package.json
├─ startup.mjs
├─ seed.mjs
└─ index.mjs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  6) &lt;code&gt;startup.mjs&lt;/code&gt; - initialize clients and vector store
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// startup.mjs&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;dotenv/config&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;createClient&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;@supabase/supabase-js&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;OpenAIEmbeddings&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;@langchain/openai&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;SupabaseVectorStore&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;@langchain/community/vectorstores/supabase&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;OPENAI_API_KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;SUPABASE_URL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;SUPABASE_SERVICE_ROLE_KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;OPENAI_API_KEY&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;SUPABASE_URL&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;SUPABASE_SERVICE_ROLE_KEY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Missing required env vars. Check your .env.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;embeddings&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;OpenAIEmbeddings&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;model&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;text-embedding-3-small&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;apiKey&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;OPENAI_API_KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="c1"&gt;// Optional: dimensions: 1536, // stick to default 1536&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;supabase&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;createClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;SUPABASE_URL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;SUPABASE_SERVICE_ROLE_KEY&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Table and RPC function names must match what you created in SQL&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;SupabaseVectorStore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;embeddings&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;client&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;supabase&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;tableName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;documents&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;queryName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;match_documents&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  7) &lt;code&gt;seed.mjs&lt;/code&gt; - add documents
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// seed.mjs&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;./startup.mjs&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;doc1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;pageContent&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;The powerhouse of the cell is the mitochondria.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;// fixed typo&lt;/span&gt;
  &lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;page&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://example.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;doc2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;pageContent&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Buildings are commonly made out of brick.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;page&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://example.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;doc3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;pageContent&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Mitochondria membranes are rich in lipids.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;page&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://example.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;doc4&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;pageContent&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;The 2024 Olympics were hosted in Paris.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;page&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://example.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;documents&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;doc1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;doc2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;doc3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;doc4&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="c1"&gt;// Option A) Let DB auto-generate ids (use UUID schema)&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addDocuments&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;documents&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Option B) If you created a text id column and want custom ids:&lt;/span&gt;
&lt;span class="c1"&gt;// await vectorStore.addDocuments(documents, { ids: ["1", "2", "3", "4"] });&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Seeded documents!&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  8) &lt;code&gt;index.mjs&lt;/code&gt; - run a similarity search
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// index.mjs&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;./startup.mjs&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;query&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Mitochondria are made of what?&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;k&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;similaritySearch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;query&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;k&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;results&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="cm"&gt;/*
Example shape:
[
  {
    pageContent: 'Mitochondria membranes are rich in lipids.',
    metadata: { page: 3, source: 'https://example.com' },
    id: '...'
  }
]
*/&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  9) Run it
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# 1) Seed the data (one-time or whenever you change documents)&lt;/span&gt;
npm run seed

&lt;span class="c"&gt;# 2) Query&lt;/span&gt;
npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Troubleshooting &amp;amp; common gotchas
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;code&gt;PGRST202 could not find function public.match_documents&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
You didn’t create the RPC, or it’s not in the &lt;code&gt;public&lt;/code&gt; schema, or the name mismatches your &lt;code&gt;queryName&lt;/code&gt; option.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Dimension mismatch&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Ensure your table column and RPC &lt;strong&gt;vector dimensions&lt;/strong&gt; match your embedding model (1536 for &lt;code&gt;text-embedding-3-small&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Service role key exposure&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Use &lt;code&gt;SUPABASE_SERVICE_ROLE_KEY&lt;/code&gt; only on the &lt;strong&gt;server&lt;/strong&gt;. For browser apps, create a secure backend route that proxies requests.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Inconsistent ids&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
If your table uses &lt;code&gt;uuid&lt;/code&gt;, don’t pass custom &lt;code&gt;ids&lt;/code&gt; in &lt;code&gt;addDocuments&lt;/code&gt;. If you want to pass your own ids, define &lt;code&gt;id text primary key&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Performance&lt;/strong&gt;&lt;br&gt;&lt;br&gt;
Create the &lt;code&gt;ivfflat&lt;/code&gt; index (cosine ops), and consider increasing &lt;code&gt;lists&lt;/code&gt; and &lt;code&gt;probes&lt;/code&gt; depending on data size and latency targets.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Why this works
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;LangChain.js&lt;/strong&gt; ships a &lt;strong&gt;SupabaseVectorStore&lt;/strong&gt; integration in &lt;code&gt;@langchain/community&lt;/code&gt;, which expects a &lt;code&gt;documents&lt;/code&gt; table and an RPC (default &lt;code&gt;match_documents&lt;/code&gt;) to perform similarity search.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;pgvector&lt;/strong&gt; provides the &lt;code&gt;vector&lt;/code&gt; type, distance operators, and ANN indexes for fast semantic search.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;OpenAI &lt;code&gt;text-embedding-3-small&lt;/code&gt;&lt;/strong&gt; gives high‑quality, low‑cost embeddings with &lt;strong&gt;1536 dimensions&lt;/strong&gt;, perfect for quick demos and many production workloads.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Next steps
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Add &lt;strong&gt;metadata filters&lt;/strong&gt; (e.g., &lt;code&gt;filter: { source: "https://example.com" }&lt;/code&gt;) to scope search.
&lt;/li&gt;
&lt;li&gt;Batch insert larger datasets and tweak ANN index parameters.
&lt;/li&gt;
&lt;li&gt;Swap in other embedding providers (Cohere, Voyage, local models) if needed.
&lt;/li&gt;
&lt;li&gt;Build a RAG pipeline: chunk PDFs/HTML -&amp;gt; store -&amp;gt; query -&amp;gt; &lt;strong&gt;rerank&lt;/strong&gt; -&amp;gt; answer with citations.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Full source (copy‑paste friendly)
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;startup.mjs&lt;/code&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;dotenv/config&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;createClient&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;@supabase/supabase-js&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;OpenAIEmbeddings&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;@langchain/openai&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;SupabaseVectorStore&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;@langchain/community/vectorstores/supabase&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;OPENAI_API_KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;SUPABASE_URL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="nx"&gt;SUPABASE_SERVICE_ROLE_KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;OPENAI_API_KEY&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;SUPABASE_URL&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;SUPABASE_SERVICE_ROLE_KEY&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Missing required env vars. Check your .env.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;embeddings&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;OpenAIEmbeddings&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
  &lt;span class="na"&gt;model&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;text-embedding-3-small&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;apiKey&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;OPENAI_API_KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;supabase&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;createClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;SUPABASE_URL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;SUPABASE_SERVICE_ROLE_KEY&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;SupabaseVectorStore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;embeddings&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;client&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;supabase&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;tableName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;documents&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;queryName&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;match_documents&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;code&gt;seed.mjs&lt;/code&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;./startup.mjs&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;document1&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;pageContent&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;The powerhouse of the cell is the mitochondria.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;page&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://example.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;document2&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;pageContent&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Buildings are commonly made out of brick.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;page&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://example.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;document3&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;pageContent&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Mitochondria membranes are rich in lipids.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;page&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://example.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;document4&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="na"&gt;pageContent&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;The 2024 Olympics were hosted in Paris.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="na"&gt;page&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;4&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="na"&gt;source&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://example.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;documents&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="nx"&gt;document1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;document2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;document3&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;document4&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

&lt;span class="c1"&gt;// Option A: auto UUID&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;addDocuments&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;documents&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Option B: custom ids (if table uses text id)&lt;/span&gt;
&lt;span class="c1"&gt;// await vectorStore.addDocuments(documents, { ids: ["1", "2", "3", "4"] });&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Seed complete.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;code&gt;index.mjs&lt;/code&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;./startup.mjs&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;query&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Mitochondria are made of what?&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;results&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;vectorStore&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;similaritySearch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;query&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;results&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Security checklist
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt; API keys live in &lt;strong&gt;.env&lt;/strong&gt;, not source files.
&lt;/li&gt;
&lt;li&gt; Service role key is used only on &lt;strong&gt;trusted servers&lt;/strong&gt; (Node, serverless function, etc.).
&lt;/li&gt;
&lt;li&gt; Rate limit and auth‑gate any routes that call your vector store.
&lt;/li&gt;
&lt;li&gt; Consider &lt;strong&gt;Row Level Security (RLS)&lt;/strong&gt; and custom filters in &lt;code&gt;match_documents&lt;/code&gt; to restrict result visibility.
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Happy building!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>ai</category>
      <category>javascript</category>
      <category>programming</category>
    </item>
    <item>
      <title>How Hirenom Helps You Ace Interviews with AI-Powered Mock Sessions &amp; Smart Resume Tools</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Fri, 20 Jun 2025 15:47:02 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/how-hirenom-helps-you-ace-interviews-with-ai-powered-mock-sessions-smart-resume-tools-3b02</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/how-hirenom-helps-you-ace-interviews-with-ai-powered-mock-sessions-smart-resume-tools-3b02</guid>
      <description>&lt;h2&gt;
  
  
  Ace Your Dream Job with Hirenom: AI-Powered Mock Interviews, Resume Builder &amp;amp; LinkedIn Optimization
&lt;/h2&gt;

&lt;p&gt;Are you preparing for job interviews but not sure where to start? Struggling with resume writing or optimizing your LinkedIn profile? &lt;strong&gt;Hirenom&lt;/strong&gt; is your one-stop platform powered by AI to help you prepare confidently, apply smartly, and stand out from the competition.&lt;/p&gt;




&lt;h2&gt;
  
  
  What Is Hirenom?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.hirenom.com" rel="noopener noreferrer"&gt;&lt;strong&gt;Hirenom.com&lt;/strong&gt;&lt;/a&gt; is an AI-powered platform built for job seekers, freshers, and professionals who want to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Practice &lt;strong&gt;mock interviews&lt;/strong&gt; with real-time AI feedback&lt;/li&gt;
&lt;li&gt;Generate &lt;strong&gt;ATS-friendly resumes&lt;/strong&gt; using smart prompts&lt;/li&gt;
&lt;li&gt;Improve their &lt;strong&gt;LinkedIn profiles&lt;/strong&gt; for better recruiter visibility&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  AI Mock Interviews: Practice Like a Pro
&lt;/h2&gt;

&lt;p&gt;Our AI Interview Assistant simulates &lt;strong&gt;real interview scenarios&lt;/strong&gt; technical, behavioral, or domain-specific and provides &lt;strong&gt;instant feedback&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Key features:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Voice-based interviews powered by LLMs (like GPT-4)&lt;/li&gt;
&lt;li&gt;Feedback on your responses (clarity, relevance, confidence)&lt;/li&gt;
&lt;li&gt;Custom interview types: React, Java, System Design &amp;amp; more&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Helps reduce real interview anxiety&lt;br&gt;&lt;br&gt;
Speeds up preparation with tailored questions  &lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  AI Resume Builder: Impress with Every Word
&lt;/h2&gt;

&lt;p&gt;Tired of confusing resume templates? Hirenom generates &lt;strong&gt;professional resumes&lt;/strong&gt; based on your:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Skills&lt;/li&gt;
&lt;li&gt;Work experience&lt;/li&gt;
&lt;li&gt;Job roles you’re targeting&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Highlights:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Custom sections with AI-generated content&lt;/li&gt;
&lt;li&gt;Export as PDF or Docx&lt;/li&gt;
&lt;li&gt;Designed to pass &lt;strong&gt;ATS (Applicant Tracking Systems)&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://www.hirenom.com/dashboard" rel="noopener noreferrer"&gt;Try the Resume Builder →&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  LinkedIn Optimizer: Be More Visible to Recruiters
&lt;/h2&gt;

&lt;p&gt;Recruiters search LinkedIn with very specific filters. We help you:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Optimize your &lt;strong&gt;headline and summary&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Add &lt;strong&gt;relevant skills&lt;/strong&gt; and certifications&lt;/li&gt;
&lt;li&gt;Rephrase your experience with &lt;strong&gt;impact-driven language&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Outcome? More visibility. Better inbound messages.&lt;/p&gt;




&lt;h2&gt;
  
  
  How Hirenom Works
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Sign up&lt;/strong&gt; (Free account available)&lt;/li&gt;
&lt;li&gt;Choose a tool: Mock Interview / Resume / LinkedIn&lt;/li&gt;
&lt;li&gt;Follow prompts or upload your data&lt;/li&gt;
&lt;li&gt;Download, practice, and apply!&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  Who Should Use Hirenom?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Final-year students preparing for placements&lt;/li&gt;
&lt;li&gt;Working professionals switching jobs&lt;/li&gt;
&lt;li&gt;Tech enthusiasts brushing up on interviews&lt;/li&gt;
&lt;li&gt;Freshers without professional coaching access&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Why Hirenom Stands Out
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;AI-powered real-time coaching
&lt;/li&gt;
&lt;li&gt;Designed by engineers &amp;amp; hiring managers
&lt;/li&gt;
&lt;li&gt;Super simple UI no tech skills required
&lt;/li&gt;
&lt;li&gt;Used by 2,000+ users monthly &amp;amp; growing&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Try Hirenom Today
&lt;/h2&gt;

&lt;p&gt;Give yourself the best shot at your dream job with &lt;strong&gt;AI on your side&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.hirenom.com" rel="noopener noreferrer"&gt;Get started with Hirenom →&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Whether you're a fresher or an experienced professional, consistent practice and smart tools make all the difference. &lt;strong&gt;Hirenom combines both&lt;/strong&gt; so you save time, improve faster, and interview with confidence.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Follow us on &lt;a href="https://x.com/gautamk104" rel="noopener noreferrer"&gt;Twitter&lt;/a&gt;for tips, updates &amp;amp; career hacks!&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Caching Techniques Explained: How to Speed Up Data Retrieval Efficiently</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Thu, 06 Mar 2025 11:28:24 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/caching-techniques-explained-how-to-speed-up-data-retrieval-efficiently-2bek</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/caching-techniques-explained-how-to-speed-up-data-retrieval-efficiently-2bek</guid>
      <description>&lt;p&gt;Caching is a technique used to store frequently accessed data in a temporary storage location (cache) to improve performance and speed up data retrieval. Instead of fetching data from the main source (like a database or server) repeatedly, caching keeps a copy of the data closer to where it's needed.&lt;/p&gt;

&lt;p&gt;However, since cache storage is limited, we need strategies to decide which data to keep and which to remove when the cache is full. The following are some common cache eviction policies:&lt;/p&gt;

&lt;h2&gt;
  
  
  1. LRU (Least Recently Used)
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt;&lt;br&gt;
LRU removes the least recently used item from the cache when it reaches its limit.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-Life Example:&lt;/strong&gt;&lt;br&gt;
Imagine a small bookshelf that can hold only 5 books. You keep replacing the books based on how recently you read them. If you pick a book and read it today, it stays. But if a book hasn’t been read for weeks, it gets removed first to make space for a new one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt;&lt;br&gt;
LRU is used in web browsers to manage cached pages. If you visit multiple websites, but some haven’t been accessed in a while, the browser removes the oldest ones to store new ones.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Algorithm Pseudocode&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Initialize an empty cache with a fixed size.&lt;br&gt;
Use a HashMap to store key-value pairs.&lt;br&gt;
Use a Doubly Linked List to maintain access order (most recent at the front).&lt;br&gt;
When accessing an item:&lt;br&gt;
    - If it exists, move it to the front (most recently used).&lt;br&gt;
    - If it's missing, add it to the front.&lt;br&gt;
    - If the cache is full, remove the least recently used item from the back.&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Node.js Express Implementation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const app = express();
const PORT = 3000;

class LRUCache {
    constructor(size) {
        this.size = size;
        this.map = new Map();
    }

    get(key) {
        if (!this.map.has(key)) return null;
        const value = this.map.get(key);
        this.map.delete(key);
        this.map.set(key, value); 
        return value;
    }

    put(key, value) {
        if (this.map.has(key)) this.map.delete(key);
        else if (this.map.size &amp;gt;= this.size) this.map.delete(this.map.keys().next().value); 
        this.map.set(key, value);
    }
}

const cache = new LRUCache(3);

app.get('/users/:id', (req, res) =&amp;gt; {
    const userId = req.params.id;
    let user = cache.get(userId);

    if (!user) {
        user = { id: userId, name: `User_${userId}` };
        cache.put(userId, user);
    }

    res.json({ cachedUsers: Array.from(cache.map.values()) });
});

app.listen(PORT, () =&amp;gt; console.log(`Server running on port ${PORT}`));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. MRU (Most Recently Used)
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt;&lt;br&gt;
MRU removes the most recently used item first when the cache is full.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-Life Example:&lt;/strong&gt;&lt;br&gt;
Think of a music playlist with limited slots. You recently played a song, and now you want to add a new one. Instead of removing an old song, you remove the most recently played song because you assume it won’t be played again soon.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt;&lt;br&gt;
MRU is useful in cases where the older data is more valuable than the most recently used one, such as databases where the most recent queries are likely temporary.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Algorithm Pseudocode&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Use a HashMap to store key-value pairs.&lt;br&gt;
Use a Doubly Linked List to maintain access order.&lt;br&gt;
When accessing an item:&lt;br&gt;
    - If it exists, move it to the front.&lt;br&gt;
    - If it’s missing, add it to the front.&lt;br&gt;
    - If the cache is full, remove the most recently used item (from the front).&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Node.js Express Implementation&lt;/strong&gt;&lt;br&gt;
Use Case: &lt;strong&gt;Session management&lt;/strong&gt; (removing the last logged-in user first)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MRUCache {
    constructor(size) {
        this.size = size;
        this.map = new Map();
    }

    get(key) {
        if (!this.map.has(key)) return null;
        const value = this.map.get(key);
        this.map.delete(key);
        this.map.set(key, value);
        return value;
    }

    put(key, value) {
        if (this.map.has(key)) this.map.delete(key);
        else if (this.map.size &amp;gt;= this.size) {
            let lastKey = Array.from(this.map.keys()).pop();
            this.map.delete(lastKey);
        }
        this.map.set(key, value);
    }
}

const sessionCache = new MRUCache(3);

app.get('/login/:user', (req, res) =&amp;gt; {
    const user = req.params.user;
    sessionCache.put(user, { username: user, loggedInAt: new Date() });

    res.json({ activeSessions: Array.from(sessionCache.map.values()) });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. LFU (Least Frequently Used)
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt;&lt;br&gt;
LFU removes the least frequently used items first. It keeps track of how often each item is used and removes the ones that are used the least.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-Life Example:&lt;/strong&gt;&lt;br&gt;
Imagine a cafeteria menu where some dishes are more popular than others. If space is limited, the manager removes the least ordered dishes from the menu while keeping the bestsellers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt;&lt;br&gt;
LFU is used in content delivery networks (CDNs) where the most accessed web pages and media files are cached, and less accessed ones are removed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Algorithm Pseudocode&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Use a HashMap to store key-value pairs.&lt;br&gt;
Maintain a frequency counter for each item.&lt;br&gt;
When adding new items:&lt;br&gt;
    - If the cache is full, remove the least frequently used item.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Node.js Express Implementation&lt;/strong&gt;&lt;br&gt;
Use Case: &lt;strong&gt;Caching most used products in an e-commerce API&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class LFUCache {
    constructor(size) {
        this.size = size;
        this.map = new Map();
        this.freq = new Map();
    }

    get(key) {
        if (!this.map.has(key)) return null;
        this.freq.set(key, (this.freq.get(key) || 0) + 1);
        return this.map.get(key);
    }

    put(key, value) {
        if (this.map.size &amp;gt;= this.size) {
            let lfuKey = [...this.freq.entries()].reduce((a, b) =&amp;gt; (a[1] &amp;lt; b[1] ? a : b))[0];
            this.map.delete(lfuKey);
            this.freq.delete(lfuKey);
        }
        this.map.set(key, value);
        this.freq.set(key, 1);
    }
}

const productCache = new LFUCache(3);

app.get('/product/:id', (req, res) =&amp;gt; {
    const productId = req.params.id;
    let product = productCache.get(productId);

    if (!product) {
        product = { id: productId, name: `Product_${productId}` };
        productCache.put(productId, product);
    }

    res.json({ cachedProducts: Array.from(productCache.map.values()) });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. FIFO (First In, First Out)
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt;&lt;br&gt;
FIFO removes the oldest item first, just like a queue.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-Life Example:&lt;/strong&gt;&lt;br&gt;
Think of a vending machine where snacks are loaded from the back. The first snack placed inside is the first one that comes out.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt;&lt;br&gt;
FIFO is commonly used in message queues and task scheduling where processing happens in the order requests arrive.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Algorithm Pseudocode&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Use a queue to store items.&lt;br&gt;
When adding a new item:&lt;br&gt;
    - If the cache is full, remove the oldest item (first added).&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Node.js Express Implementation&lt;/strong&gt;&lt;br&gt;
Use Case: &lt;strong&gt;Queueing user requests in a rate limiter&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class FIFOCache {
    constructor(size) {
        this.size = size;
        this.queue = [];
    }

    put(value) {
        if (this.queue.length &amp;gt;= this.size) this.queue.shift();
        this.queue.push(value);
    }

    getAll() {
        return this.queue;
    }
}

const requestCache = new FIFOCache(5);

app.get('/request/:id', (req, res) =&amp;gt; {
    requestCache.put(`Request_${req.params.id}`);
    res.json({ recentRequests: requestCache.getAll() });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. LIFO (Last In, First Out)
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt;&lt;br&gt;
LIFO removes the most recently added item first. It works like a stack where the last item placed is the first to be removed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-Life Example:&lt;/strong&gt;&lt;br&gt;
Imagine a stack of plates in a restaurant. The waiter always places clean plates on top, and the next customer takes the topmost plate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt;&lt;br&gt;
LIFO is used in undo operations in text editors, where the most recent action is undone first.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Algorithm Pseudocode&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Use a stack (array) to store items.&lt;br&gt;
When adding a new item:&lt;br&gt;
    - If the cache is full, remove the last added item.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Node.js Express Implementation&lt;/strong&gt;&lt;br&gt;
Use Case: &lt;strong&gt;Tracking the last performed API request&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class LIFOCache {
    constructor(size) {
        this.size = size;
        this.stack = [];
    }

    put(value) {
        if (this.stack.length &amp;gt;= this.size) this.stack.pop();
        this.stack.push(value);
    }

    getLast() {
        return this.stack[this.stack.length - 1];
    }
}

const actionCache = new LIFOCache(3);

app.get('/action/:name', (req, res) =&amp;gt; {
    actionCache.put(req.params.name);
    res.json({ lastAction: actionCache.getLast() });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  6. RR (Round Robin)
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Concept:&lt;/strong&gt;&lt;br&gt;
Round Robin cycles through items in order, giving each a fair chance before repeating.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real-Life Example:&lt;/strong&gt;&lt;br&gt;
Imagine a queue of people waiting to ask questions in a classroom. The teacher answers one question per student before moving to the next, ensuring everyone gets a turn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Case:&lt;/strong&gt;&lt;br&gt;
RR is commonly used in load balancing for servers to distribute incoming requests fairly across multiple servers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Algorithm Pseudocode&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Use a circular queue.&lt;br&gt;
Each request gets assigned to the next available server in order.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Node.js Express Implementation&lt;/strong&gt;&lt;br&gt;
Use Case: &lt;strong&gt;Load balancing incoming requests to different servers&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const servers = ['Server_1', 'Server_2', 'Server_3'];
let index = 0;

app.get('/request', (req, res) =&amp;gt; {
    const assignedServer = servers[index];
    index = (index + 1) % servers.length; 
    res.json({ assignedServer });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Each caching technique has its advantages and is useful in different scenarios. If you need fast access to recent data, LRU is a good choice. If older data is important, MRU or LFU might be better. FIFO and LIFO are useful for queues and stacks, while RR is great for fair resource distribution.&lt;br&gt;
Please ignore any typos, and let me know your thoughts on this.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
      <category>ai</category>
    </item>
    <item>
      <title>Understanding the DOM Tree: A Beginner's Guide to Understanding Web Page Structure</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Mon, 27 Jan 2025 07:43:20 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/understanding-the-dom-tree-a-beginners-guide-to-understanding-web-page-structure-2ncd</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/understanding-the-dom-tree-a-beginners-guide-to-understanding-web-page-structure-2ncd</guid>
      <description>&lt;p&gt;The &lt;strong&gt;DOM (Document Object Model)&lt;/strong&gt; is a representation of an HTML document as a &lt;strong&gt;tree structure&lt;/strong&gt;. It allows programming languages (like JavaScript) to interact with, modify, and manipulate web pages dynamically.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;What is the DOM Tree?&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Imagine a webpage as a family tree where:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The entire document (HTML) is the root.&lt;/li&gt;
&lt;li&gt;Different parts of the document (head, body, elements) are like branches and leaves.&lt;/li&gt;
&lt;li&gt;Each element inside the page is a &lt;strong&gt;node&lt;/strong&gt; in this tree.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;How the DOM Tree Represents the HTML&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Example 1: With new line and space&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;title&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;My Page&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;title&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;h1&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Hello, World!&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;h1&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;This is a paragraph.&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;Document&lt;/span&gt;
&lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="nx"&gt;html&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="nx"&gt;head&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="nx"&gt;title&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;My Page&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;  &lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;  &lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="nx"&gt;body&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;       &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;    &lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;       &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="nx"&gt;h1&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;       &lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Hello, World!&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;       &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;    &lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;       &lt;span class="err"&gt;├──&lt;/span&gt; &lt;span class="nx"&gt;p&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;       &lt;span class="err"&gt;│&lt;/span&gt;   &lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;This is a paragraph.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="err"&gt;│&lt;/span&gt;       &lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="s2"&gt;  &lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;span class="err"&gt;└──&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="se"&gt;\n&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;you can see for each new line there is a &lt;strong&gt;TextNodes &lt;code&gt;"\n  "&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2: Without and new line and space&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;title&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;My Page&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;title&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;h1&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Hello, World!&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;h1&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;This is a paragraph.&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                [Document]
                    |
                &amp;lt;html&amp;gt;
                /     \\
          &amp;lt;head&amp;gt;       &amp;lt;body&amp;gt;
             |             |
          &amp;lt;title&amp;gt;         &amp;lt;h1&amp;gt;     &amp;lt;p&amp;gt;
             |              |       |
        "My Page"     "Hello,..." "This is..."

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this scenario, there are no new lines (TextNodes)&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Breaking it down:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Root Node:&lt;/strong&gt; &lt;code&gt;Document&lt;/code&gt; – The whole page (browser creates it automatically).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Element Nodes:&lt;/strong&gt; &lt;code&gt;&amp;lt;html&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt; – Represent HTML tags.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Text Nodes:&lt;/strong&gt; Inside elements, like &lt;code&gt;"\n "&lt;/code&gt;, &lt;code&gt;"My Page"&lt;/code&gt;, &lt;code&gt;"Hello, World!"&lt;/code&gt;, and &lt;code&gt;"This is a paragraph."&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Attributes (not shown in tree):&lt;/strong&gt; Elements can have attributes like &lt;code&gt;id&lt;/code&gt;, &lt;code&gt;class&lt;/code&gt;, etc.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Types of Nodes in the DOM Tree&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The DOM tree consists of different types of nodes:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Document Node:&lt;/strong&gt; Represents the entire document (&lt;code&gt;document&lt;/code&gt; in JS).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Element Nodes:&lt;/strong&gt; HTML elements (e.g., &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Text Nodes:&lt;/strong&gt; Text inside elements (e.g., &lt;code&gt;"\n "&lt;/code&gt;,  &lt;code&gt;Hello, World!&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Attribute Nodes:&lt;/strong&gt; Represent element attributes (e.g., &lt;code&gt;class="example"&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Comment Nodes:&lt;/strong&gt; Represent HTML comments (&lt;code&gt;&amp;lt;!-- This is a comment --&amp;gt;&lt;/code&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Accessing the DOM Using JavaScript&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;JavaScript allows us to manipulate the DOM using methods like:&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;1. Accessing Elements&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;documentElement&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Gets &amp;lt;html&amp;gt; element&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;body&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;            &lt;span class="c1"&gt;// Gets &amp;lt;body&amp;gt; element&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;title&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;           &lt;span class="c1"&gt;// Gets page title&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Selecting Specific Elements&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;heading&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;querySelector&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;h1&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Select &amp;lt;h1&amp;gt;&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;heading&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;textContent&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;  &lt;span class="c1"&gt;// Output: Hello, World!&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;DOM Tree Relationships&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The DOM tree has relationships between nodes:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Parent Node:&lt;/strong&gt; A node that contains other nodes inside it.

&lt;ul&gt;
&lt;li&gt;Example: &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt; is the parent of &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Child Nodes:&lt;/strong&gt; Nodes inside a parent node.

&lt;ul&gt;
&lt;li&gt;Example: &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt; are children of &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sibling Nodes:&lt;/strong&gt; Nodes at the same level under the same parent.

&lt;ul&gt;
&lt;li&gt;Example: &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt; are siblings.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Example (Relationships)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;h1&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Hello&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;h1&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Welcome&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;p&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Parent:&lt;/strong&gt; &lt;code&gt;&amp;lt;html&amp;gt;&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Children:&lt;/strong&gt; &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Siblings:&lt;/strong&gt; &lt;code&gt;&amp;lt;h1&amp;gt;&lt;/code&gt; and &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Get different elements&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;rootElement&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;document&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getRootNode&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// To get the root node&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;rootElement&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Output: #document object&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;childNodesOfRoot&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;rootElement&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;childNodes&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="c1"&gt;// To get all the child nodes of any Element&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;childNodesOfRoot&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// Output: #html object&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;childNodesOfHTML&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;childNodesOfRoot&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;].&lt;/span&gt;&lt;span class="nx"&gt;childNodes&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="c1"&gt;// To get all the child nodes of any Element&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;childNodesOfHTML&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;// Output: #head object,  #textNode("\n ") object,  #body object&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The DOM represents the structure of an HTML document in a tree format.&lt;/li&gt;
&lt;li&gt;JavaScript can be used to manipulate the DOM to update content dynamically.&lt;/li&gt;
&lt;li&gt;Understanding DOM relationships helps in selecting and modifying elements easily.&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>How JavaScript Executes Code: A Step-by-Step Breakdown of Program Execution</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Sun, 26 Jan 2025 07:03:02 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/how-javascript-executes-code-a-step-by-step-breakdown-of-program-execution-46j</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/how-javascript-executes-code-a-step-by-step-breakdown-of-program-execution-46j</guid>
      <description>&lt;p&gt;JavaScript is a &lt;strong&gt;high-level, interpreted, and just-in-time (JIT) compiled&lt;/strong&gt; programming language that follows a process to execute code in a structured way. Understanding how JavaScript executes a program helps in writing efficient code and avoiding potential issues.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;JavaScript Execution Flow Overview&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;When you write JavaScript code, the JavaScript engine (e.g., V8 for Chrome and Node.js, SpiderMonkey for Firefox) processes it in multiple steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Parsing (Syntax Analysis)&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Early Error Checking&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Compilation (JIT Compilation)&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Execution (Execution Context Creation and Code Execution)&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Step-by-Step Execution Process&lt;/strong&gt;
&lt;/h2&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Step 1: Parsing (Syntax Analysis)&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The first thing the JavaScript engine does is parse the code.&lt;/li&gt;
&lt;li&gt;It breaks the source code into &lt;strong&gt;tokens&lt;/strong&gt; (small meaningful units like keywords, identifiers, etc.).&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;syntax tree (AST - Abstract Syntax Tree)&lt;/strong&gt; is generated from these tokens.&lt;/li&gt;
&lt;li&gt;If the syntax is incorrect, an &lt;strong&gt;early error&lt;/strong&gt; occurs, and execution is stopped.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example: Syntax Error&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("Hello, World");
console.log("test line) // Missing quotes or closing parenthesis
console.log("last line")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the engine finds a syntax error during parsing, the script will not run.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Step 2: Early Error Checking&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Before execution, JavaScript performs &lt;strong&gt;early error checking&lt;/strong&gt;, such as:

&lt;ul&gt;
&lt;li&gt;Variable declarations and re-declarations.&lt;/li&gt;
&lt;li&gt;Reserved keyword usage.&lt;/li&gt;
&lt;li&gt;Block scoping violations (e.g., using &lt;code&gt;let&lt;/code&gt; variables before declaration).&lt;/li&gt;
&lt;li&gt;Incorrect function calls.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example: Early Error Checking&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;x&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="c1"&gt;// Early error: 'x' has already been declared&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;y&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;    &lt;span class="c1"&gt;// Missing initializer in const declaration&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If an early error is detected, execution is stopped immediately, and an error is thrown.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Step 3: Compilation (JIT Compilation)&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;JavaScript is not purely interpreted language. Modern engines like &lt;strong&gt;V8&lt;/strong&gt; (Chrome, Node.js) and &lt;strong&gt;SpiderMonkey&lt;/strong&gt; (Firefox) use &lt;strong&gt;Just-In-Time (JIT) Compilation&lt;/strong&gt; to optimize code execution.&lt;/p&gt;

&lt;p&gt;The compilation happens in two stages:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Interpreter (Baseline Compiler)&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;Quickly converts code into machine code for fast startup.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Optimizer (JIT Compiler)&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;Analyzes repeated code patterns and optimizes them for performance.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Thus, JavaScript has a mix of &lt;strong&gt;interpreted and compiled behavior&lt;/strong&gt;, improving speed.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Step 4: Execution (Execution Context Creation and Code Execution)&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Before running the program, JavaScript prepares the environment by setting up &lt;strong&gt;Execution Contexts&lt;/strong&gt;, where each script runs inside a &lt;strong&gt;Global Execution Context&lt;/strong&gt; (GEC).&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Execution Context Creation Steps:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Creation Phase:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The global execution context is created.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;this&lt;/code&gt; keyword is assigned a value (e.g., &lt;code&gt;window&lt;/code&gt; in the browser, &lt;code&gt;global&lt;/code&gt; in Node.js) in the GEC (global execution context)&lt;/li&gt;
&lt;li&gt;Memory is allocated for variables and functions (but they are not executed yet).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Define Scope Before Execution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before the code runs, JavaScript sets up the &lt;strong&gt;scope&lt;/strong&gt; of variables, which determines their visibility and accessibility. This happens in the &lt;strong&gt;creation phase&lt;/strong&gt; of the execution context.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variables declared with &lt;code&gt;var&lt;/code&gt; are hoisted&lt;/strong&gt; to the top of their scope and initialized with &lt;code&gt;undefined&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variables declared with &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; are hoisted but not initialized&lt;/strong&gt; (this results in a &lt;strong&gt;Temporal Dead Zone (TDZ)&lt;/strong&gt; error if accessed before declaration).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Variable Hoisting&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// undefined (due to hoisting with `var`)&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// ReferenceError (due to temporal dead zone)&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Execution Phase:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The code is executed line by line.&lt;/li&gt;
&lt;li&gt;Variables and function calls are resolved.&lt;/li&gt;
&lt;li&gt;The call stack is used to track execution.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Understanding Call Stack in Execution&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;JavaScript has a &lt;strong&gt;single-threaded&lt;/strong&gt; execution model, meaning it can execute one command at a time using the &lt;strong&gt;Call Stack&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;When a function is called, it gets pushed onto the stack.&lt;/p&gt;

&lt;p&gt;When it completes execution, it is popped from the stack.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Call Stack&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Hello&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;sayGoodbye&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Goodbye&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nf"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nf"&gt;sayGoodbye&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;&lt;strong&gt;Execution order in the call stack:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;greet()&lt;/code&gt; → Push to stack → Execute → Pop&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;sayGoodbye()&lt;/code&gt; → Push to stack → Execute → Pop&lt;/li&gt;
&lt;/ol&gt;


&lt;/li&gt;

&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Example: Putting It All Together&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Let's consider a simple code snippet and understand how it runs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Start&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;multiply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;multiply&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Result:&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;End&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Execution Steps:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Parsing:&lt;/strong&gt; No syntax errors, move to the next step.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Early Error Checking:&lt;/strong&gt; No variable scope or redeclaration issues.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Compilation:&lt;/strong&gt; Functions and variables are set in memory.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Execution:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;"Start"&lt;/code&gt; is printed.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;multiply(2, 3)&lt;/code&gt; is called.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"Result: 6"&lt;/code&gt; is printed.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;"End"&lt;/code&gt; is printed.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Key Takeaways&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Execution Phases:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;JavaScript code goes through parsing, compilation, and execution.&lt;/li&gt;
&lt;li&gt;Early error checking prevents runtime crashes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Scope Handling:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Variables are hoisted before execution.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;var&lt;/code&gt; vs. &lt;code&gt;let&lt;/code&gt;/&lt;code&gt;const&lt;/code&gt; differences affect how the code behaves.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Efficient Execution:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;JavaScript's JIT compilation speeds up repeated operations.&lt;/li&gt;
&lt;li&gt;Call stack manages function execution order.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Summary&lt;/strong&gt;
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Phase&lt;/th&gt;
&lt;th&gt;Description&lt;/th&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Parsing&lt;/td&gt;
&lt;td&gt;Code is broken into tokens and checked for syntax&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Early Error Check&lt;/td&gt;
&lt;td&gt;Detects issues like re-declarations and scoping&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Compilation&lt;/td&gt;
&lt;td&gt;JIT compiles code for optimized performance&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Execution&lt;/td&gt;
&lt;td&gt;Code runs in an execution context&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;td&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

</description>
    </item>
    <item>
      <title>JavaScript Hoisting Explained in details: var, let, const, and Functions</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Wed, 22 Jan 2025 06:42:31 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/javascript-hoisting-explained-in-details-var-let-const-and-functions-3eim</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/javascript-hoisting-explained-in-details-var-let-const-and-functions-3eim</guid>
      <description>&lt;p&gt;&lt;strong&gt;Hoisting&lt;/strong&gt; is a JavaScript mechanism where &lt;strong&gt;variables and function declarations&lt;/strong&gt; are moved to the top of their containing scope during the compile phase, before code execution.&lt;/p&gt;

&lt;p&gt;This means you can use variables and functions before they are declared in your code.&lt;br&gt;
However, &lt;strong&gt;only the declarations are hoisted, not the initializations.&lt;/strong&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  &lt;strong&gt;Hoisting with &lt;code&gt;var&lt;/code&gt;&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;When using &lt;code&gt;var&lt;/code&gt;, the variable declaration is hoisted to the top of its scope (global or function scope), but the initialization remains in place. If you try to access the variable before initialization, it will return &lt;code&gt;undefined&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1: Hoisting with &lt;code&gt;var&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// undefined&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// 10&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;br&gt;
Behind the scenes, JavaScript interprets the code like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;      &lt;span class="c1"&gt;// Declaration is hoisted to the top&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// undefined (since initialization hasn't happened yet)&lt;/span&gt;
&lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;     &lt;span class="c1"&gt;// Initialization remains in place&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// 10&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Key Points for &lt;code&gt;var&lt;/code&gt; hoisting:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The declaration is hoisted, but the assignment is &lt;strong&gt;not&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Variables declared with &lt;code&gt;var&lt;/code&gt; have &lt;strong&gt;function scope&lt;/strong&gt;, meaning they are accessible anywhere inside the function they are declared in.&lt;/li&gt;
&lt;li&gt;Accessing the variable before declaration results in &lt;code&gt;undefined&lt;/code&gt; instead of a &lt;code&gt;ReferenceError&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Hoisting with &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt;&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Variables declared with &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; are &lt;strong&gt;hoisted&lt;/strong&gt;, but they are &lt;strong&gt;not initialized&lt;/strong&gt;. Accessing them before declaration results in a &lt;strong&gt;ReferenceError&lt;/strong&gt; due to the "Temporal Dead Zone (TDZ)."&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 2: Hoisting with &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// ReferenceError: Cannot access 'b' before initialization&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// 20&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;c&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// ReferenceError: Cannot access 'c' before initialization&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;c&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;c&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// 30&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt;&lt;br&gt;
Behind the scenes, JavaScript hoists the declarations but doesn't initialize them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Declarations are hoisted, but they are in the Temporal Dead Zone (TDZ)&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="c1"&gt;// Hoisted, but inaccessible before initialization&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;c&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;  &lt;span class="c1"&gt;// Hoisted, but inaccessible before initialization&lt;/span&gt;

&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// ReferenceError&lt;/span&gt;
&lt;span class="nx"&gt;b&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;20&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// 20&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Key Points for &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; hoisting:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The declaration is hoisted, but initialization is &lt;strong&gt;not&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Accessing them before initialization throws a &lt;strong&gt;ReferenceError.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Variables have &lt;strong&gt;block scope&lt;/strong&gt;, meaning they are only accessible within the block &lt;code&gt;{}&lt;/code&gt; they are defined in.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const&lt;/code&gt; must be initialized at the time of declaration, unlike &lt;code&gt;let&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Hoisting in Function Declarations vs Function Expressions&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Function Declarations (Hoisted)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Function declarations are hoisted &lt;strong&gt;entirely&lt;/strong&gt;, meaning they can be called before their declaration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nf"&gt;sayHello&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// Works fine&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;sayHello&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Hello!&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Function Expressions (Not Hoisted Fully)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Function expressions (assigned to variables) are subject to variable hoisting rules.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nf"&gt;greet&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt; &lt;span class="c1"&gt;// TypeError: greet is not a function&lt;/span&gt;
&lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="nx"&gt;greet&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Hi!&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above case, &lt;code&gt;greet&lt;/code&gt; is hoisted, but it is treated as &lt;code&gt;undefined&lt;/code&gt; before initialization.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Temporal Dead Zone (TDZ) with &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt;&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;Temporal Dead Zone (TDZ)&lt;/strong&gt; is the period between the start of a block and when a variable is declared. During this period, any access to the variable results in a &lt;code&gt;ReferenceError&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;myVar&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// ReferenceError&lt;/span&gt;
&lt;span class="kd"&gt;let&lt;/span&gt; &lt;span class="nx"&gt;myVar&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;myVar&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// 50&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, the area before the &lt;code&gt;let myVar&lt;/code&gt; declaration is the &lt;strong&gt;TDZ&lt;/strong&gt;, meaning you cannot access &lt;code&gt;myVar&lt;/code&gt; before it's declared.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Comparison of &lt;code&gt;var&lt;/code&gt;, &lt;code&gt;let&lt;/code&gt;, and &lt;code&gt;const&lt;/code&gt; in Hoisting&lt;/strong&gt;
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;var&lt;/th&gt;
&lt;th&gt;let&lt;/th&gt;
&lt;th&gt;const&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Hoisted?&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Initialization?&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;undefined&lt;/code&gt; (default)&lt;/td&gt;
&lt;td&gt;No (TDZ occurs)&lt;/td&gt;
&lt;td&gt;No (TDZ occurs)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Scope&lt;/td&gt;
&lt;td&gt;Function Scope&lt;/td&gt;
&lt;td&gt;Block Scope&lt;/td&gt;
&lt;td&gt;Block Scope&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Reassignment?&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Must initialize?&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Hoisting moves variable and function declarations to the top of the scope.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;var&lt;/code&gt; is hoisted and initialized with &lt;code&gt;undefined&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; are hoisted but not initialized (TDZ applies).&lt;/li&gt;
&lt;li&gt;Function declarations are hoisted, but function expressions are not fully hoisted.&lt;/li&gt;
&lt;li&gt;Always follow best practices to write predictable and maintainable code.&lt;/li&gt;
&lt;/ul&gt;

</description>
    </item>
    <item>
      <title>4 Effective Ways to Use the &lt;script&gt; Tag in HTML for Better Web Development</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Tue, 21 Jan 2025 17:42:48 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/4-effective-ways-to-use-the-tag-in-html-for-better-web-development-fg9</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/4-effective-ways-to-use-the-tag-in-html-for-better-web-development-fg9</guid>
      <description>&lt;p&gt;Using the &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag in different parts of an HTML document affects how and when the JavaScript code is executed relative to the HTML content. Let's go through the &lt;strong&gt;four ways&lt;/strong&gt; to use the &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag, explaining how HTML and JavaScript are processed in each scenario.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;1. Script inside the &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt; tag&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Script in Head&amp;lt;/title&amp;gt;
    &amp;lt;script src="script.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Hello, World!&amp;lt;/h1&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Execution Process:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;The browser reads and loads the HTML document &lt;strong&gt;from top to bottom&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;When it reaches the &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag inside &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;, it &lt;strong&gt;pauses rendering&lt;/strong&gt; of the HTML to fetch and execute the script.&lt;/li&gt;
&lt;li&gt;Once the script is fully loaded and executed, it resumes processing the rest of the HTML (e.g., the &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt; content).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Downside:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;If the script is large or slow to load, it can &lt;strong&gt;delay the page rendering&lt;/strong&gt;, leading to a blank screen until the script finishes.&lt;/li&gt;
&lt;li&gt;If the script tries to manipulate elements in the &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt;, it may fail because they have not been loaded yet. The DOM manipulation does not work properly as the HTML elements have not rendered yet.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;When to use:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;When the script contains functions that are not needed immediately, like analytics or configuration code.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;2. Script at the end of the &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt; tag&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;html lang="en"&amp;gt;
  &amp;lt;head&amp;gt;
    &amp;lt;title&amp;gt;Script at Bottom&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body&amp;gt;
    &amp;lt;h1&amp;gt;Hello, World!&amp;lt;/h1&amp;gt;
    &amp;lt;script src="script.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Execution Process:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;The browser loads and displays the entire HTML content first.&lt;/li&gt;
&lt;li&gt;After rendering the page, it reaches the &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag at the bottom and executes the script.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Advantages:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Ensures the HTML content is fully loaded before the script runs.&lt;/li&gt;
&lt;li&gt;No delay in rendering the page, improving the user experience.&lt;/li&gt;
&lt;li&gt;Ideal for manipulating DOM elements because they are already available.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Disadvantages:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Ensures Since the entire html first render and then the JavaScript loads and execute, it takes time and the response in more.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;When to use:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Recommended for scripts that interact with the page content (e.g., adding event listeners, modifying elements).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;3. Script inside the &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt; tag with &lt;code&gt;async&lt;/code&gt; attribute&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt; &lt;span class="na"&gt;lang&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"en"&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;title&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Script with Async&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;title&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;script&lt;/span&gt; &lt;span class="na"&gt;src&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"script.js"&lt;/span&gt; &lt;span class="na"&gt;async&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;script&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;h1&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Hello, World!&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;h1&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Execution Process:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;The browser loads the HTML sequentially.&lt;/li&gt;
&lt;li&gt;When it encounters the &lt;code&gt;async&lt;/code&gt; script, it starts &lt;strong&gt;loading the script in parallel&lt;/strong&gt; while continuing to load the rest of the HTML.&lt;/li&gt;
&lt;li&gt;Once the script is fully loaded, it will pause rendering and execute the script &lt;strong&gt;immediately&lt;/strong&gt;, then continue loading the HTML.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Advantages:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Non-blocking: The script loads in the background without delaying the page.&lt;/li&gt;
&lt;li&gt;Faster page load because the browser does not pause waiting for the script to load.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Downside:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Scripts may execute in &lt;strong&gt;random order&lt;/strong&gt; if multiple &lt;code&gt;async&lt;/code&gt; scripts are included.&lt;/li&gt;
&lt;li&gt;If the script depends on the HTML structure, it might run too soon and cause errors.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;When to use:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Good for independent scripts like analytics, advertisements, or social media widgets that don't depend on other scripts or HTML elements.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;4. Script inside the &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt; tag with &lt;code&gt;defer&lt;/code&gt; attribute&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight jsx"&gt;&lt;code&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt; &lt;span class="na"&gt;lang&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"en"&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;title&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Script with Defer&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;title&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;script&lt;/span&gt; &lt;span class="na"&gt;src&lt;/span&gt;&lt;span class="p"&gt;=&lt;/span&gt;&lt;span class="s"&gt;"script.js"&lt;/span&gt; &lt;span class="na"&gt;defer&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;script&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;head&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nt"&gt;h1&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;Hello, World!&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;h1&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;body&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="nt"&gt;html&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Execution Process:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;The browser loads the HTML sequentially.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;defer&lt;/code&gt; script is &lt;strong&gt;downloaded in parallel&lt;/strong&gt; with the HTML but &lt;strong&gt;executed only after the entire HTML is parsed&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;The script runs just before the &lt;code&gt;DOMContentLoaded&lt;/code&gt; event.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Advantages:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Ensures the script executes &lt;strong&gt;after&lt;/strong&gt; the page has fully loaded.&lt;/li&gt;
&lt;li&gt;Maintains the order of script execution if multiple &lt;code&gt;defer&lt;/code&gt; scripts are used.&lt;/li&gt;
&lt;li&gt;Good for scripts that rely on the full DOM being available.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;When to use:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Perfect for scripts that manipulate the DOM after it's fully loaded.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Comparison Table&lt;/strong&gt;
&lt;/h2&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Method&lt;/th&gt;
&lt;th&gt;Execution Time&lt;/th&gt;
&lt;th&gt;Blocks Rendering&lt;/th&gt;
&lt;th&gt;Best Use Case&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Script in &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Before HTML is loaded&lt;/td&gt;
&lt;td&gt;Yes&lt;/td&gt;
&lt;td&gt;Configuration, early execution logic&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Script at end of &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;After HTML is loaded&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;DOM manipulation, event handling&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Script in &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt; with &lt;code&gt;async&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;When script is downloaded&lt;/td&gt;
&lt;td&gt;No (except during execution)&lt;/td&gt;
&lt;td&gt;Analytics, ads, independent scripts&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Script in &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt; with &lt;code&gt;defer&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;After entire HTML is parsed&lt;/td&gt;
&lt;td&gt;No&lt;/td&gt;
&lt;td&gt;DOM-dependent scripts&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion (Best Practices)&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Use &lt;code&gt;&amp;lt;script defer&amp;gt;&lt;/code&gt;&lt;/strong&gt; for scripts that interact with page content and require the full DOM.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Use &lt;code&gt;&amp;lt;script async&amp;gt;&lt;/code&gt;&lt;/strong&gt; for independent scripts like analytics and ads that don’t depend on the DOM.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Place scripts at the bottom&lt;/strong&gt; of the &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt; if no attributes are used, ensuring smooth page loading.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Avoid placing scripts in the &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;&lt;/strong&gt; without &lt;code&gt;async&lt;/code&gt; or &lt;code&gt;defer&lt;/code&gt; unless absolutely necessary to prevent blocking page rendering.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Understanding the different ways to use the  tag in HTML is essential for optimizing your web applications. Whether you choose to include scripts inline, internally within the document, externally via a separate file, or asynchronously/defer to enhance performance, each approach has its own advantages depending on your project needs. By strategically using the &amp;lt;script&amp;gt; tag, you can improve code maintainability, boost page load speed, and ensure a better user experience.&amp;lt;/p&amp;gt;
&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Understanding Call Stack, Callback Queue, Event Loop, and Microtask Queue in JavaScript</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Sat, 11 Jan 2025 16:24:55 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/understanding-call-stack-callback-queue-event-loop-and-microtask-queue-in-javascript-2c7n</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/understanding-call-stack-callback-queue-event-loop-and-microtask-queue-in-javascript-2c7n</guid>
      <description>&lt;p&gt;JavaScript is known for its single-threaded, non-blocking nature, which is made possible by the efficient coordination of the call stack, callback queue, event loop, and microtask queue. If these terms sound confusing, don’t worry! In this blog, we’ll break them down with beginner-friendly explanations and examples.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Call Stack
&lt;/h2&gt;

&lt;p&gt;The call stack is like a "to-do list" that JavaScript uses to keep track of function execution. It manages the order in which functions are called and ensures they run one at a time in a synchronous manner.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How it works:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When a function is called, it gets added (or "pushed") to the top of the stack.&lt;/li&gt;
&lt;li&gt;Once the function finishes executing, it is removed (or "popped") from the stack.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function fun() {
  console.log("Hello!");
}

function check() {
  console.log("Goodbye!");
}

fun();       // ADDED TO THE STACK, EXECUTED, THEN REMOVED 
check();  // ADDED TO THE STACK, EXECUTED, THEN REMOVED
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;Hello!&lt;br&gt;
Goodbye!&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Here, each function is executed one at a time, in the order they’re called.&lt;/p&gt;
&lt;h2&gt;
  
  
  2. Callback Queue
&lt;/h2&gt;

&lt;p&gt;The callback queue holds tasks (like callbacks from setTimeout) that need to be executed after the call stack is empty. These tasks are asynchronous and wait their turn to be processed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How it works:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When an asynchronous operation (e.g., setTimeout) completes, its callback is sent to the callback queue.&lt;/li&gt;
&lt;li&gt;The event loop ensures these tasks are executed only when the call stack is empty.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("Start");

setTimeout(() =&amp;gt; {
  console.log("Inside setTimeout");
}, 1000);

console.log("End");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;code&gt;Start&lt;br&gt;
End&lt;br&gt;
Inside setTimeout&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here’s what happens:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;“Start” and “End” are logged immediately because they’re in the call stack.&lt;/p&gt;

&lt;p&gt;setTimeout schedules a callback to run after 1 second, placing it in the callback queue.&lt;/p&gt;

&lt;p&gt;After the call stack is empty, the event loop moves the callback from the queue to the stack for execution.&lt;/p&gt;
&lt;h2&gt;
  
  
  3. Event Loop
&lt;/h2&gt;

&lt;p&gt;The event loop is the unsung hero that coordinates the execution of JavaScript code. It ensures the call stack, callback queue, and microtask queue work seamlessly together.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0r8dsohcb97y2kdngres.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0r8dsohcb97y2kdngres.png" alt="Image description" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How it works:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The event loop checks if the call stack is empty.&lt;/li&gt;
&lt;li&gt;If the stack is empty, it processes tasks from the microtask queue (if any) and then from the callback queue.&lt;/li&gt;
&lt;li&gt;This process continues indefinitely, ensuring tasks are executed in the correct order.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  4. Microtask Queue
&lt;/h2&gt;

&lt;p&gt;The microtask queue is similar to the callback queue but with higher priority. It holds tasks such as Promise callbacks and MutationObserver callbacks. Microtasks are executed before any tasks in the callback queue.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How it works:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;After the call stack is empty, the event loop processes all microtasks before moving on to the callback queue.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("Start");

setTimeout(() =&amp;gt; {
  console.log("Inside setTimeout");
}, 0);

Promise.resolve().then(() =&amp;gt; {
  console.log("Inside Promise");
});

console.log("End");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt; &lt;br&gt;
&lt;code&gt;Start&lt;br&gt;
End&lt;br&gt;
Inside Promise&lt;br&gt;
Inside setTimeout&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Here’s why:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;"&lt;code&gt;Start&lt;/code&gt;" and "&lt;code&gt;End&lt;/code&gt;" run first because they’re synchronous.&lt;/li&gt;
&lt;li&gt;The promise’s .then() callback is added to the microtask queue.&lt;/li&gt;
&lt;li&gt;The setTimeout callback is added to the callback queue.&lt;/li&gt;
&lt;li&gt;The event loop processes the microtask queue (Promise) before the callback queue (setTimeout).&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Lets Summarize this
&lt;/h2&gt;

&lt;p&gt;JavaScript handles asynchronous operations using the &lt;code&gt;call stack&lt;/code&gt;, &lt;code&gt;callback queue&lt;/code&gt;, &lt;code&gt;event loop&lt;/code&gt;, and &lt;code&gt;microtask queue&lt;/code&gt;. The call stack runs synchronous code, while the event loop coordinates asynchronous tasks. Promises (microtask queue) are prioritized over setTimeout callbacks (callback queue), ensuring efficient and orderly execution of code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Top 10 Interview Questions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here’s a set of 10 most-asked interview questions related to the topics of the call stack, callback queue, event loop, and microtask queue in JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. What is the call stack in JavaScript, and how does it work?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
The call stack is a data structure that keeps track of function execution in JavaScript. It follows the Last In, First Out (LIFO) principle:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When a function is called, it is pushed onto the stack.&lt;/li&gt;
&lt;li&gt;When the function execution completes, it is popped off the stack.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. What is the role of the callback queue in JavaScript?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
The callback queue holds tasks (callbacks) from asynchronous operations, like setTimeout or event listeners, that are ready to be executed after the call stack is empty.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. What is the event loop, and why is it important?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
The event loop is a mechanism that continuously checks whether the call stack is empty. If it is, the event loop pushes tasks from the callback queue or microtask queue onto the stack for execution. It enables JavaScript to perform non-blocking operations in a single-threaded environment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. What is the microtask queue, and how is it different from the callback queue?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
The microtask queue holds high-priority tasks such as Promise resolutions and MutationObserver callbacks. These tasks are executed before any task in the callback queue.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. How does setTimeout work in JavaScript?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
setTimeout schedules a callback to execute after a specified delay. The callback is added to the callback queue and waits for the event loop to push it to the call stack after the delay.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Why does Promise execute its .then() before setTimeout?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
The .then() of a Promise is a microtask, which is handled before any tasks in the callback queue, including setTimeout. This prioritization ensures that critical tasks like Promises are handled promptly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. What happens if a microtask continuously queues another microtask?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
If a microtask queues another microtask, it creates a loop where the event loop keeps executing microtasks indefinitely before moving to the callback queue. This can cause a delay in executing tasks in the callback queue.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. What is the difference between synchronous and asynchronous code in JavaScript?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
Synchronous code is executed sequentially, blocking subsequent tasks until the current task is completed.&lt;br&gt;
Asynchronous code allows other tasks to run while waiting for operations like I/O or timers. Callbacks handle the result when the operation completes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;9. Can you explain the order of execution in the following code?&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("A");
setTimeout(() =&amp;gt; console.log("B"), 0);
Promise.resolve().then(() =&amp;gt; console.log("C"));
console.log("D");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;“A” and “D” are synchronous and executed first.&lt;/li&gt;
&lt;li&gt;The .then() callback is a microtask, so “C” is executed next.&lt;/li&gt;
&lt;li&gt;The setTimeout callback is in the callback queue, so “B” is executed last.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt;&lt;br&gt;
&lt;code&gt;A  &lt;br&gt;
D  &lt;br&gt;
C  &lt;br&gt;
B&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;10. What is the difference between blocking and non-blocking code in JavaScript?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt;&lt;br&gt;
Blocking code prevents further execution until it completes. Example: a while loop that runs indefinitely.&lt;br&gt;
Non-blocking code allows other tasks to execute while waiting for a task to complete. Example: setTimeout or fetch operations.&lt;/p&gt;

&lt;p&gt;These questions and answers will help you master the foundational concepts of JavaScript's execution model and confidently tackle technical interviews. &lt;/p&gt;

</description>
    </item>
    <item>
      <title>Shallow Copy vs. Deep Copy in JavaScript</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Sat, 23 Nov 2024 11:39:02 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/shallow-copy-vs-deep-copy-in-javascript-3efn</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/shallow-copy-vs-deep-copy-in-javascript-3efn</guid>
      <description>&lt;h2&gt;
  
  
  Overview
&lt;/h2&gt;

&lt;p&gt;In JavaScript, copying objects or arrays can be categorized into shallow copy and deep copy. Understanding the difference is critical when dealing with complex data structures, especially those containing nested objects or arrays.&lt;/p&gt;

&lt;p&gt;This guide explains these concepts, their characteristics, methods to implement them, and when to use each.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Shallow Copy
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Definition&lt;/strong&gt;&lt;br&gt;
A shallow copy creates a duplicate of the top-level properties of an object or array. However, for nested objects or arrays, only the references are copied, not the actual data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Characteristics&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Copies only the first level of properties or elements.&lt;/li&gt;
&lt;li&gt;Nested objects or arrays share references with the original object/array.&lt;/li&gt;
&lt;li&gt;Lightweight and efficient for simple structures but not suitable for independent duplication of nested data.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;1.1 Using &lt;code&gt;Object.assign()&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const original = { a: 1, b: { c: 2 } };
const shallowCopy = Object.assign({}, original);

shallowCopy.b.c = 42; 
console.log(original.b.c); // OUTPUT: 42 (The original object also affected due to shared reference)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;1.2 Using the &lt;code&gt;Spread Operator (...)&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original };

shallowCopy.b.c = 90;
console.log(original.b.c); // OUTPUT: 90

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;1.3 Lets see an example of shallow copy on &lt;code&gt;Array Methods (slice, concat)&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const original = [1, 2, [3, 4]];
const shallowCopy = original.slice();

shallowCopy[2][0] = 10; 
console.log(original[2][0]); // OUTPUT: 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Deep Copy
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Definition&lt;/strong&gt;&lt;br&gt;
A deep copy creates a fully independent duplicate of an object or array. All levels, including nested structures, are recursively copied. Changes to the copied structure do not affect the original, and vice versa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Characteristics&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Recursively copies all levels of the structure.&lt;/li&gt;
&lt;li&gt;Nested objects or arrays are independent of the original.&lt;/li&gt;
&lt;li&gt;Computationally heavier than shallow copies.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2.1 Using &lt;code&gt;JSON.stringify()&lt;/code&gt; and &lt;code&gt;JSON.parse()&lt;/code&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Converts the object into a JSON string and then back into a new object.&lt;/li&gt;
&lt;li&gt;Limitations: Does not handle functions, Date, RegExp, or circular references.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const original = { a: 1, b: { c: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));

deepCopy.b.c = 42;
console.log(original.b.c); // OUTPUT: 2 (original remains unaffected)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;2.2 Using &lt;code&gt;structuredClone()&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
A modern method for deep copying that supports circular references and special objects like Date.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const original = { a: 1, b: { c: 2 }, date: new Date() };
const deepCopy = structuredClone(original);

deepCopy.b.c = 42;
console.log(original.b.c); // OUTPUT: 2
console.log(original.date === deepCopy.date); // FALSE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2.3 Using a Custom &lt;code&gt;Recursive Function&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
A flexible solution for handling complex cases manually.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function deepCopy(obj) {
  if (obj === null || typeof obj !== "object") return obj; 

  if (Array.isArray(obj)) return obj.map(deepCopy); 

  const copy = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      copy[key] = deepCopy(obj[key]);
    }
  }
  return copy;
}

const original = { a: 1, b: { c: 2 } };
const deepCopyObj = deepCopy(original);

deepCopyObj.b.c = 42;
console.log(original.b.c); // OUTPUT: 2

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. When to Use Each?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Shallow Copy&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;For flat objects or arrays without nested structures.&lt;/li&gt;
&lt;li&gt;When performance is critical, and shared references for nested objects are acceptable.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Deep Copy&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;For complex, deeply nested objects/arrays.&lt;/li&gt;
&lt;li&gt;When you need true independence between the copy and the original.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4. Summary
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Shallow Copy&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Simple and efficient.&lt;/li&gt;
&lt;li&gt;Suitable for flat structures or when shared references are acceptable.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Deep Copy&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Robust and ensures full independence.&lt;/li&gt;
&lt;li&gt;Ideal for deeply nested or complex structures.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is an in depth explanation of the Shallow copy and Deep copy of objects in the JavaScript. Choose the appropriate method based on your use case and performance requirements.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Goodbye Exceptions! Mastering Error Handling in JavaScript with the Result Pattern</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Fri, 22 Nov 2024 07:58:27 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/goodbye-exceptions-mastering-error-handling-in-javascript-with-the-result-pattern-26kb</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/goodbye-exceptions-mastering-error-handling-in-javascript-with-the-result-pattern-26kb</guid>
      <description>&lt;p&gt;The Result Pattern is a functional programming approach used in many programming languages like &lt;code&gt;Rust&lt;/code&gt;, &lt;code&gt;Go&lt;/code&gt;, &lt;code&gt;C#&lt;/code&gt; (and other languages) to handle errors without relying on &lt;code&gt;try-catch&lt;/code&gt; blocks. It involves representing the result of an operation as an object that explicitly indicates success or failure. This pattern is particularly useful in asynchronous programming.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the Result Pattern?
&lt;/h2&gt;

&lt;p&gt;The Result Pattern represents the outcome of an operation using two explicit states:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Success (Ok)&lt;/strong&gt;: Contains the successful value.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Failure (Err)&lt;/strong&gt;: Contains the error or failure reason&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to Implement the Result Pattern
&lt;/h2&gt;

&lt;p&gt;lets create a Result Utility object&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Result = {
  Ok: (value) =&amp;gt; ({ isOk: true, value }),
  Err: (error) =&amp;gt; ({ isOk: false, error }),
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;lets use this Result Pattern in an Async Function&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fetchData = async (url) =&amp;gt; {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      return Result.Err(`HTTP error: ${response.status}`);
    }
    const data = await response.json();
    return Result.Ok(data);
  } catch (err) {
    return Result.Err(err.message);
  }
};

const main = async () =&amp;gt; {
  const result = await fetchData("https://jsonplaceholder.typicode.com/posts");
  if (result.isOk) {
    console.log("Success:", result.value);
  } else {
    console.error("Error:", result.error);
  }
};

main();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Benefits of the Result Pattern
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Improved Readability: Avoids Nested try-catch Blocks&lt;/strong&gt;&lt;br&gt;
Problem with try-catch:&lt;br&gt;
Using &lt;code&gt;try-catch&lt;/code&gt; for error handling can lead to deeply nested code when handling multiple operations. This makes the code harder to read and maintain.&lt;/p&gt;

&lt;p&gt;The main benefits of the Result Pattern is that the Result Pattern encapsulates errors as part of the return value, eliminating the need for nested try-catch blocks. The error handling logic becomes cleaner and more structured.&lt;/p&gt;

&lt;p&gt;Lets see an example of nested &lt;code&gt;try-catch&lt;/code&gt; exception&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const process = async (data) =&amp;gt;{
    // YOUR LOGIC TO PROCESS THE DATA
    return result
}

const processData = async () =&amp;gt; {
    try {
      const response = await fetch("https://jsonplaceholder.typicode.com/posts");
      const data = await response.json();
      try {
        const processedData = process(data);
        return processedData;
      } catch (processError) {
        console.error("Error processing data:", processError);
      }
    } catch (fetchError) {
      console.error("Error fetching data:", fetchError);
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now lets implemented the same data fetching logic using Result Pattern&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const process = async (data) =&amp;gt;{
    // YOUR LOGIC TO PROCESS THE DATA
    return result
}

const processData = async () =&amp;gt; {
  const fetchResult = await fetchData("https://jsonplaceholder.typicode.com/posts");
  if (!fetchResult.isOk) return fetchResult;

  const processResult = process(fetchResult.value);
  return processResult;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Explicitness: Clearly Communicates the Possibility of Failure&lt;/strong&gt;&lt;br&gt;
Problem with Implicit Error Handling:&lt;br&gt;
JavaScript functions can throw errors implicitly, making it unclear if a function might fail unless explicitly documented. This can lead to unexpected runtime errors.&lt;/p&gt;

&lt;p&gt;How the Result Pattern Helps:&lt;br&gt;
The Result Pattern explicitly returns Ok or Err, signaling whether an operation succeeded or failed. This makes the function's behavior predictable and easier to reason about.&lt;/p&gt;

&lt;p&gt;Example of the Implicit error handling&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const processUserInput = (input) =&amp;gt; {
  if (!input || input.trim() === "") {
    throw new Error("Input cannot be empty");
  }
  return `Processed: ${input}`;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example of the Explicit error handling with Result Pattern&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const processUserInput = (input) =&amp;gt; {
  if (!input || input.trim() === "") {
    return Result.Err("Input cannot be empty");
  }
  return Result.Ok(`Processed: ${input}`);
};

const userInput = "  ";
const result = processUserInput(userInput);

if (result.isOk) {
  console.log("Success:", result.value);
} else {
  console.error("Failure:", result.error);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Composability: Easier to Chain Operations&lt;/strong&gt;&lt;br&gt;
Problem with try-catch:&lt;br&gt;
When chaining multiple operations, one exception can disrupt the entire flow. Handling these exceptions with try-catch adds significant boilerplate.&lt;/p&gt;

&lt;p&gt;How the Result Pattern Helps:&lt;br&gt;
The Result Pattern simplifies composition by passing Ok values forward and stopping execution at the first Err. This ensures a clean and predictable flow of operations.&lt;/p&gt;

&lt;p&gt;Example of Without Result Pattern&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fetchAndProcessData = async () =&amp;gt; {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");
    const data = await response.json();
    const processedData = process(data);
    const result = await save(processedData);
    return result;
  } catch (error) {
    console.error("Error in workflow:", error);
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example With Result Pattern&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fetchAndProcessData = async () =&amp;gt; {
  const fetchResult = await fetchData("https://jsonplaceholder.typicode.com/posts");
  if (!fetchResult.isOk) return fetchResult;

  const processResult = process(fetchResult.value);
  if (!processResult.isOk) return processResult;

  const saveResult = await save(processResult.value);
  return saveResult;
};

const result = await fetchAndProcessData();
if (result.isOk) {
  console.log("Workflow succeeded:", result.value);
} else {
  console.error("Workflow failed:", result.error);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The Result Pattern offers a powerful and elegant alternative to &lt;code&gt;try-catch&lt;/code&gt; for error handling in JavaScript. By providing improved readability, explicit error handling, and composability, it enhances the robustness and predictability of asynchronous workflows.&lt;/p&gt;

&lt;p&gt;If you're working with complex logic or multiple asynchronous operations, consider using the &lt;code&gt;Result Pattern&lt;/code&gt; to make your code cleaner and more maintainable.&lt;/p&gt;

&lt;p&gt;Feel free to give your opinion on this pattern, apologies for any typos.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How to use express-validator as a middleware in Express App</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Sun, 10 Nov 2024 17:32:37 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/how-to-use-express-validator-as-a-middleware-in-express-app-3mb4</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/how-to-use-express-validator-as-a-middleware-in-express-app-3mb4</guid>
      <description>&lt;p&gt;Hello everyone, In this article we will learn how can we setup the &lt;code&gt;express-validator&lt;/code&gt; as a middleware, also we will deep dive in details about the proper use case of &lt;code&gt;check&lt;/code&gt;and &lt;code&gt;body&lt;/code&gt; methods in express-validator.&lt;br&gt;
express-validator is a powerful library for validating and sanitizing inputs in Express applications. It provides a robust set of validation and sanitization functions that can be used to ensure incoming data meets specific requirements. This documentation will guide you through setting up validation middleware and illustrate the key differences between the check and body methods for validation.&lt;/p&gt;

&lt;p&gt;After installing the express-validator, follow the below steps&lt;/p&gt;
&lt;h2&gt;
  
  
  Setting Up Validation Rules
&lt;/h2&gt;

&lt;p&gt;You can either use &lt;code&gt;body()&lt;/code&gt; or &lt;code&gt;check()&lt;/code&gt; to setup the validation rules.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;check()&lt;/strong&gt;: A flexible validator that can check data across various parts of a request (such as &lt;code&gt;req.body&lt;/code&gt;, &lt;code&gt;req.query&lt;/code&gt;, and &lt;code&gt;req.params&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;body()&lt;/strong&gt;: A more targeted validator that focuses specifically on validating data within &lt;code&gt;req.body&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;validationResult()&lt;/strong&gt;: To retrieve and handle validation results in a middleware function.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Defining Validation Middleware
&lt;/h2&gt;

&lt;p&gt;To make your validation reusable and keep your routes clean, define validation rules in a middleware function. Here’s an example middleware function for a user registration route that checks the &lt;code&gt;email&lt;/code&gt; and &lt;code&gt;password&lt;/code&gt; fields.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { check, validationResult } from 'express-validator';

// DEFINE VALIDATION RULES
const validateRegistration = [
    check('email')
        .isEmail()
        .withMessage('Please enter a valid email address')
        .isLength({ max: 100 })
        .withMessage('Email cannot exceed 100 characters'),

    check('password')
        .isLength({ min: 6 })
        .withMessage('Password must be at least 6 characters long')
        .isLength({ max: 255 })
        .withMessage('Password cannot exceed 255 characters'),

    // CHECK FOR VALIDATION ERRORS
    (req, res, next) =&amp;gt; {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        // IF NO ERRORS, MOVE TO NEXT MIDDLEWARE
        next(); 
    }
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Using Middleware in Routes
&lt;/h2&gt;

&lt;p&gt;After defining your validation middleware, use it in the route that handles the incoming request. This keeps validation separate from the route logic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import express from 'express';
const app = express();

app.use(express.json());

app.post('/register', validateRegistration, (req, res) =&amp;gt; {
    // USE YOUR REGISTRATIO LOGIC HERE
    res.status(201).json({ message: 'User registered successfully' });
});

app.listen(3000, () =&amp;gt; {
    console.log('Server running on http://localhost:8080');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How It Works
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Define validation rules&lt;/strong&gt;: Specify each field’s validation requirements (such as length and format) using &lt;code&gt;check()&lt;/code&gt; or &lt;code&gt;body()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Check for errors&lt;/strong&gt;: Use &lt;code&gt;validationResult()&lt;/code&gt; to determine if any validation errors exist. If errors are found, they’re returned to the client with a 400 status code.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Continue&lt;/strong&gt;: If no errors are found, &lt;code&gt;next()&lt;/code&gt; is called to proceed with the route handler logic or to the next middleware.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, any requests to &lt;code&gt;/register&lt;/code&gt; will be validated according to the rules in &lt;code&gt;validateRegistration&lt;/code&gt; before the registration logic executes.&lt;/p&gt;

&lt;h2&gt;
  
  
  Detailed Comparison: &lt;code&gt;check&lt;/code&gt; vs &lt;code&gt;body&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;Both &lt;code&gt;check()&lt;/code&gt; and &lt;code&gt;body()&lt;/code&gt; are functions within express-validator that define validation rules for incoming data. However, they differ in where they look for data within the request and how they’re typically used.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;check()&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Scope&lt;/strong&gt;: General-purpose validator.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Validation Areas&lt;/strong&gt;: Can check for data across multiple request parts (such as &lt;code&gt;req.body&lt;/code&gt;, &lt;code&gt;req.query&lt;/code&gt;, &lt;code&gt;req.params&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Typical Use Cases&lt;/strong&gt;: Useful when you need flexibility, such as when a field might be present in the URL, query string, or body depending on the request.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example Usage of check()&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { check } from 'express-validator';

const validateEmail = [
    check('email')
        .isEmail()
        .withMessage('Invalid email address'),

    (req, res, next) =&amp;gt; {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        next();
    }
];

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;check('email')&lt;/code&gt; will look for the email field in all parts of the request, including &lt;code&gt;req.body&lt;/code&gt;, &lt;code&gt;req.query&lt;/code&gt;, and &lt;code&gt;req.params&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;body()&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Scope&lt;/strong&gt;: Specifically targets req.body.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Validation Area&lt;/strong&gt;: Looks only at the request body, making it ideal for requests that carry data within the body (such as POST, PUT, or PATCH requests).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Typical Use Cases&lt;/strong&gt;: Preferred when handling form submissions or JSON payloads, where you know the data will only be in the request body.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example Usage of body()&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { body } from 'express-validator';

const validateBodyEmail = [
    body('email')
        .isEmail()
        .withMessage('Invalid email address'),

    (req, res, next) =&amp;gt; {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }
        next();
    }
];

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, &lt;code&gt;body('email')&lt;/code&gt; will only check for the email field within &lt;code&gt;req.body&lt;/code&gt;, so it won’t detect it if it’s in &lt;code&gt;req.query&lt;/code&gt; or &lt;code&gt;req.params&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to Use Each&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;check()&lt;/strong&gt;: When the data location may vary, such as in a URL parameter, query string, or body.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;body()&lt;/strong&gt;: When you’re only interested in validating data in req.body, which is common for APIs that accept form data or JSON payloads.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example with Both&lt;/strong&gt;&lt;br&gt;
You can use both check() and body() in the same validation array to handle data from different parts of the request.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { check, body, validationResult } from 'express-validator';

app.post('/submit-form', [
    body('email').isEmail().withMessage('Please provide a valid email'),
    check('token').notEmpty().withMessage('Token is required')
], (req, res) =&amp;gt; {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    // YOUR ROUTE LOGIC
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example:&lt;br&gt;
&lt;code&gt;body('email')&lt;/code&gt; only validates email in the request body.&lt;br&gt;
&lt;code&gt;check('token')&lt;/code&gt; searches for token across req.body, req.query, and req.params.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Using express-validator in this way keeps validation clean, manageable, and flexible enough to handle a variety of input formats and sources, helping ensure data integrity and security in your application.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>beginners</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>User Authentication API with Express, JWT, Bcrypt, and MySQL</title>
      <dc:creator>gautam kumar</dc:creator>
      <pubDate>Mon, 04 Nov 2024 06:53:14 +0000</pubDate>
      <link>https://forem.com/gautam_kumar_d3daad738680/secure-user-authentication-api-with-express-jwt-bcrypt-and-mysql-16aj</link>
      <guid>https://forem.com/gautam_kumar_d3daad738680/secure-user-authentication-api-with-express-jwt-bcrypt-and-mysql-16aj</guid>
      <description>&lt;p&gt;This application is a simple authentication server built with Express, using JSON Web Tokens (JWT) for session management and bcrypt for securely storing passwords. Users can register and log in to access protected routes. MySQL is used for storing user data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Steps for &lt;code&gt;Register Route&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Check If the input email is already registered.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If yes return("User already exists"). &lt;/li&gt;
&lt;li&gt;If no Insert the User details in the DB, return("Success") &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Steps for &lt;code&gt;Login Route&lt;/code&gt;&lt;/strong&gt;&lt;br&gt;
Check if the input email exists in the DB or not&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If NO return("Invalid email")&lt;/li&gt;
&lt;li&gt;If YES check if the input password is correct for the email or not If NO return("Invalid password").If YES Create the JWT token and send it either in the &lt;code&gt;Cookie&lt;/code&gt; or in the &lt;code&gt;response&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;&lt;code&gt;VarifyAuthToken&lt;/code&gt; Middleware for Protected Route&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Get the token either from the req.cookie or from the req.headers.&lt;/li&gt;
&lt;li&gt;Valid ate the token using the SECRET_KEY. If it matches return a success response and send the user details. Else send the Invalid Token error.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Technologies Used
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Express.js&lt;/strong&gt;: Web framework for handling routes and middleware.&lt;br&gt;
&lt;strong&gt;2. bcrypt.js&lt;/strong&gt;: Library for hashing passwords securely.&lt;br&gt;
&lt;strong&gt;3. jsonwebtoken&lt;/strong&gt;: Library for creating and verifying JWT tokens.&lt;br&gt;
&lt;strong&gt;4. mysql2&lt;/strong&gt;: MySQL client for Node.js with support for Promises.&lt;br&gt;
&lt;strong&gt;5. cookie-parser&lt;/strong&gt;: Middleware for parsing cookies.&lt;/p&gt;
&lt;h2&gt;
  
  
  Code Breakdown
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Import Required Libraries&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const cookieParser = require('cookie-parser');
const mysql = require('mysql2/promise');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;express&lt;/strong&gt;: Provides functions to create routes and handle HTTP requests.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;jsonwebtoken&lt;/strong&gt;: Used to create and verify JWTs for user sessions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;bcryptjs&lt;/strong&gt;: Used for hashing passwords before storing them in the database.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;cookie-parser&lt;/strong&gt;: Middleware to parse cookies from incoming HTTP requests.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;mysql2/promise&lt;/strong&gt;: MySQL client with promise support, allowing asynchronous operations.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Initialize Express App and Define Constants
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const app = express();
const PORT = 3000;
const JWT_SECRET = 'your_jwt_secret_key';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;app&lt;/strong&gt;: The Express application instance.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;PORT&lt;/strong&gt;: The port the server will listen on.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;JWT_SECRET&lt;/strong&gt;: A secret key used to sign JWTs. Replace this with a secure, randomly generated value in production.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Database Connection Setup
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const db = await mysql.createConnection({
    host: 'localhost',
    user: 'your_MySql_username',
    password: 'your_MySql_password',
    database: 'users'
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;db&lt;/strong&gt;: The MySQL database connection object.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;mysql.createConnection()&lt;/strong&gt;: Establishes a connection to the MySQL database using async/await, which is needed for non-blocking queries.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;host&lt;/strong&gt;: Yout MySql application hostname, If you are running it on localhost, put localhost only, if you have deployed your MySql to a server, use the server hostname with PORT.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;user&lt;/strong&gt;: Your MySql Username&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;password&lt;/strong&gt;: Your MySql Password&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;database&lt;/strong&gt;: The Database name&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4. Middleware Setup
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(express.json());
app.use(cookieParser());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;express.json()&lt;/strong&gt;: Middleware to parse JSON request bodies.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;cookieParser()&lt;/strong&gt;: Middleware to parse cookies, allowing us to read cookies from req.cookies.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  5. Register Route
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;/register&lt;/code&gt;&lt;br&gt;
This route registers a new user by hashing their password and saving it in the database.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.post('/register', async (req, res) =&amp;gt; {
    const { name, email, password } = req.body;

    try {
        // CHECK IF USER ALREADY EXISTS
        const [rows] = await db.execute('SELECT * FROM users WHERE email = ?', [email]);
        if (rows.length &amp;gt; 0) {
            return res.status(400).json({ message: 'User already exists' });
        }

        // HASH THE PASSWORD
        const hashedPassword = await bcrypt.hash(password, 10);

        // SAVE THE USER IN THE DATABASE 
        const result = await db.query('INSERT INTO userDB (name, email, password) VALUES (?, ?, ?)', [user.name, user.email, hashedPassword]);
        if(result[0].insertId){
            res.status(201).json({ message: 'User registered successfully!', insertId: result[0].insertId });
        }
        res.status(500).json({message: 'Something went wrong in DB execution'});
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;db.execute()&lt;/strong&gt;: Executes a query to check if a user with the given email already exists. If they do, return a 400 status.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;bcrypt.hash(password, 10)&lt;/strong&gt;: Hashes the password with a salt rounds value of 10 for security.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;db.execute() (Insert)&lt;/strong&gt;: Saves the user's name, email, and hashed password in the database.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6. Login Route
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;/login&lt;/code&gt;&lt;br&gt;
This route logs in an existing user by checking their credentials and generating a JWT token.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.post('/login', async (req, res) =&amp;gt; {
    const { email, password } = req.body;

    try {
        // CHECK IF USER EXISTS OR NOT
        const [rows] = await db.execute('SELECT * FROM users WHERE email = ?', [email]);
        const user = rows[0];
        if (!user) {
            return res.status(400).json({ message: 'User not found' });
        }

        // CHECK IF INPUT PASSWORD IS VALID FOR INPUT EMAIL
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(400).json({ message: 'Invalid credentials' });
        }

        // CREATE THE JWT TOKEN
        const token = jwt.sign({ id: user.id, name: user.name, email: user.email }, JWT_SECRET, { expiresIn: '1h' });

        // SET THE JWT TOKEN IN THE COOKIE
        res.cookie('token', token, {
            httpOnly: true,
            secure: process.env.NODE_ENV === 'production',
            sameSite: 'Strict',
            maxAge: 3600000 // 1 HR EXPIRATION
        });

        res.json({ message: 'Logged in successfully!' });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;bcrypt.compare(password, user.password)&lt;/strong&gt;: Verifies if the hashed password matches the one stored in the database.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;jwt.sign()&lt;/strong&gt;: Creates a JWT that includes user information (e.g., ID, name, and email). The token expires in 1 hour. jwt.sign() method takes two arguments &lt;strong&gt;payload&lt;/strong&gt;, &lt;strong&gt;JWT_SECRET&lt;/strong&gt;, &lt;strong&gt;options&lt;/strong&gt;(optional)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;res.cookie()&lt;/strong&gt;: Sets a cookie with the JWT, secured by httpOnly (only accessible by the server) and sameSite settings.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  7. JWT Verification Middleware
&lt;/h2&gt;

&lt;p&gt;The verifyAuthToken middleware ensures that only requests with a valid JWT token can access protected routes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const verifyAuthToken = (req, res, next) =&amp;gt; {
    const token = req.cookies.token;
    if (!token) return res.status(403).json({ message: 'Token is missing.' });

    try {
        const decoded = jwt.verify(token, JWT_SECRET);
        req.user = decoded;
        next();
    } catch (err) {
        res.status(401).json({ message: 'Invalid token.' });
    }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;req.cookies.token&lt;/strong&gt;: Extracts the token from cookies.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;jwt.verify(token, JWT_SECRET)&lt;/strong&gt;: Verifies the token using the JWT secret key. If valid, &lt;strong&gt;decoded&lt;/strong&gt; contains the token’s payload, which is assigned to &lt;strong&gt;req.user&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;next()&lt;/strong&gt;: Proceeds to the next middleware if the token is valid.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  8. Protected Route - /protected
&lt;/h2&gt;

&lt;p&gt;A sample protected route accessible only to authenticated users. It returns a personalized greeting using the user’s name from the token.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get('/protected', verifyAuthToken, (req, res) =&amp;gt; {
    res.json({ message: `Hello, ${req.user.name}! This is a protected route.` });
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;verifyAuthToken&lt;/strong&gt;: Middleware applied to check the user’s authentication status.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;req.user.name&lt;/strong&gt;: Accesses the user’s name from the decoded JWT payload.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  9. Start the Server
&lt;/h2&gt;

&lt;p&gt;The server listens on the defined PORT.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.listen(PORT, () =&amp;gt; {
    console.log(`Server is running on http://localhost:${PORT}`);
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Full Code&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const cookieParser = require('cookie-parser');
const mysql = require('mysql2/promise');

const app = express();
const PORT = 3000;
const JWT_SECRET = 'your_jwt_secret_key';

// MySQL CONNECTION SETUP
const db = await mysql.createConnection({
    host: 'localhost',
    user: 'your_MySql_username',
    password: 'your_MySql_password',
    database: 'users'
});

// MIDDLEWARE
app.use(express.json());
app.use(cookieParser());

// ROUTES
app.post('/register', async (req, res) =&amp;gt; {
    const { name, email, password } = req.body;

    try {
        // CHECK IF USER ALREADY EXISTS
        const [rows] = await db.execute('SELECT * FROM users WHERE email = ?', [email]);
        if (rows.length &amp;gt; 0) {
            return res.status(400).json({ message: 'User already exists' });
        }

        // HASH THE PASSWORD
        const hashedPassword = await bcrypt.hash(password, 10);

        // SAVE THE USER IN THE DATABASE
        const result = await db.query('INSERT INTO userDB (name, email, password) VALUES (?, ?, ?)', [user.name, user.email, hashedPassword]);
        if(result[0].insertId){
            res.status(201).json({ message: 'User registered successfully!', insertId: result[0].insertId });
        }
        res.status(500).json({message: 'Something went wrong in DB execution'});
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
});

// LOGIN ROUTE
app.post('/login', async (req, res) =&amp;gt; {
    const { email, password } = req.body;

    try {
        // CHECK IF USER EXISTS OR NOT
        const [rows] = await db.execute('SELECT * FROM users WHERE email = ?', [email]);
        const user = rows[0];
        if (!user) {
            return res.status(400).json({ message: 'User not found' });
        }

        // CHECK IF INPUT PASSWORD IS VALID FOR INPUT EMAIL
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(400).json({ message: 'Invalid credentials' });
        }

        // CREATE THE JWT TOKEN
        const token = jwt.sign({ id: user.id, name: user.name, email: user.email }, JWT_SECRET, { expiresIn: '1h' });

        // SET JWT TOKEN IN THE COOKIE
        res.cookie('token', token, {
            httpOnly: true,
            secure: process.env.NODE_ENV === 'production',
            sameSite: 'Strict',
            maxAge: 3600000 // 1 HR EXPIRATION TIME
        });

        res.json({ message: 'Logged in successfully!' });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: 'Server error' });
    }
});

// MIDDLEWARE TO VERIFY THE JWT TOKEN
const verifyAuthToken = (req, res, next) =&amp;gt; {
    const token = req.cookies.token;
    if (!token) return res.status(403).json({ message: 'Token is missing.' });

    try {
        const decoded = jwt.verify(token, JWT_SECRET);
        req.user = decoded;
        next();
    } catch (err) {
        res.status(401).json({ message: 'Invalid token.' });
    }
};

// PROTECTED ROUTE
app.get('/protected', verifyAuthToken, (req, res) =&amp;gt; {
    res.json({ message: `Hello, ${req.user.name}! This is a protected route.` });
});

// START THE SERVER
app.listen(PORT, () =&amp;gt; {
    console.log(`Server is running on http://localhost:${PORT}`);
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;This application:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Allows user registration by hashing passwords and storing user data in MySQL.&lt;/li&gt;
&lt;li&gt;Supports secure login with JWT authentication.&lt;/li&gt;
&lt;li&gt;Uses cookies to store the JWT on the client side.&lt;/li&gt;
&lt;li&gt;Provides middleware for verifying JWTs before granting access to protected routes.&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>node</category>
    </item>
  </channel>
</rss>
