<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Ashish Kr Jha]]></title><description><![CDATA[Engineering notes on codebase tooling, AI agent retrieval, and the
things that break in production. By Ashish Kr Jha.]]></description><link>https://blog.ashishkrjha.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/62db053c38759e6b49828665/ef7ffad2-dd83-480d-92ff-a581dfe49f2b.png</url><title>Ashish Kr Jha</title><link>https://blog.ashishkrjha.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Thu, 15 Oct 2026 22:21:31 GMT</lastBuildDate><atom:link href="https://blog.ashishkrjha.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[The CORS Error That Was a Race Condition]]></title><description><![CDATA[The browser console said the request had been blocked by CORS policy, that no Access-Control-Allow-Origin header was present on the requested resource. Which is a sentence I have read several hundred ]]></description><link>https://blog.ashishkrjha.dev/the-cors-error-that-was-a-race-condition</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/the-cors-error-that-was-a-race-condition</guid><category><![CDATA[webdev]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[python projects]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Sat, 29 Aug 2026 08:50:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/9f4d7199-b8bd-4b98-9793-e408abe4889c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The browser console said the request had been blocked by CORS policy, that no <code>Access-Control-Allow-Origin</code> header was present on the requested resource. Which is a sentence I have read several hundred times and always means the same thing.</p>
<p>Except it didn't, this time. The CORS configuration was correct. It had been correct all this time. Every other endpoint on the same origin, through the same middleware, with the same credentials, worked. Only <code>/auth/refresh</code> failed, and only sometimes.</p>
<p>I went to the CORS config first anyway. Of course I did. That's what the error said.</p>
<h2>TL;DR</h2>
<p>An unhandled exception produced a 500 that never passed back through the middleware which attaches CORS headers, so the browser saw a header-less response and reported the only thing it could: a CORS failure. The message named the last layer to touch the response, not the layer that broke.</p>
<p>Underneath was a textbook time-of-check-to-time-of-use race in refresh-token rotation. Two tabs, one token, both passing the same "is this blacklisted?" check before either had written its answer.</p>
<p>The fix wasn't a better check. It was giving up on checking, letting a unique index arbitrate, and translating the resulting error. Three separate races in this codebase are now settled the same way.</p>
<p>This codebase was deliberately vibe coded, as a test of how far that approach goes without close architectural steering. This was a different kind of result from the cost one. That constraint lived outside the repository and no amount of reading code would have surfaced it. This one is four lines of source that anyone can read, and it got through anyway.</p>
<h2>Why a 500 arrives as a CORS error</h2>
<p>Worth understanding on its own, because it will cost you an afternoon exactly once and then never again.</p>
<p>CORS headers are attached by middleware. Middleware sits in a stack, each layer wrapping the next, and a response on the way out passes back through every layer that it passed through on the way in. That's how the header gets on there.</p>
<p>An unhandled exception does not come back out that way. It propagates up to the outermost error handler, which generates a 500 above the CORS layer, so the response the browser receives never went through the code that would have added <code>Access-Control-Allow-Origin</code>.</p>
<p>From the browser's side, a response with no CORS header is indistinguishable from a response that was refused on CORS grounds. It has no way to know the server crashed. It reports what it can see, which is a missing header, and you go and read documentation about preflight requests for forty minutes.</p>
<p>The general form is worth keeping:</p>
<p><strong>When a browser reports a CORS failure on an endpoint whose CORS config you have not touched, read the server log before you read the CORS docs.</strong> The browser is describing the shape of the response, not the cause of it.</p>
<p>Worth separating two problems here, because fixing the race only fixes this particular 500. The general fix is a global exception handler that catches anything unhandled and returns a real response from inside your own middleware, so the response travels back out through the whole stack and arrives at the client with headers on it. The framework's own error handler sits above everything you install, which is why responses it generates look nothing like your others. You want the frontend reading a 500 and failing gracefully, not dying on what it thinks is a network error.</p>
<blockquote>
<p><img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/8025a8fc-291f-4a15-a63f-717a2f23afac.svg" alt="A request passing inward through CORS, compression, logging and idempotency middleware to a route that throws, with the resulting 500 generated above the CORS layer and reaching the browser without an Access-Control-Allow-Origin header" /></p>
</blockquote>
<p>The server log said <code>IntegrityError</code>. Nothing to do with CORS at all.</p>
<h2>What the refresh endpoint was doing</h2>
<p>The auth design is short-lived access tokens with rotating refresh tokens. Each refresh consumes the token it was given and issues a new one, and the consumed token goes into a blacklist table keyed by its <code>jti</code>, its unique token identifier. A refresh token is therefore valid exactly once. Present it twice and the second attempt is refused.</p>
<p>That refusal is deliberate, and it isn't only bookkeeping. A rotating refresh token that gets replayed is one of the few signals you get that a token has been stolen, because the legitimate client and the attacker will both eventually present the same one. Rejecting reuse is the entire point of rotation.</p>
<p>The endpoint did the obvious thing:</p>
<pre><code class="language-python">if await blacklist.contains(jti):
    raise Unauthorized("token already used")

new_tokens = issue_pair(user)
await blacklist.add(jti)
return new_tokens
</code></pre>
<p>Read it and it looks correct. It reads correct out loud. Check whether the token has been used, and if it hasn't, use it.</p>
<h2>Two tabs</h2>
<p>The user has the application open in two tabs. Both hold the same refresh token, because it's persisted so a reload can recover the session. The access token expires. Both tabs notice at approximately the same moment and both call <code>/auth/refresh</code>.</p>
<p>Or it isn't two tabs at all, it's one tab and a retry, or a client that fired the refresh twice while the first request was still in flight. It doesn't matter which. What matters is two requests carrying the same <code>jti</code>, close enough together to overlap.</p>
<blockquote>
<p><img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/677d2f06-2efa-4c8c-8ac5-3867e3e1a25b.svg" alt="Two overlapping requests: both query the blacklist and find nothing, both proceed, the first insert succeeds and the second collides with the unique index on jti" /></p>
</blockquote>
<p>Request A checks the blacklist. Not there. Request A proceeds.</p>
<p>Request B checks the blacklist. Also not there, because A hasn't written its row yet. Request B proceeds.</p>
<p>Both issue a new token pair. Both then try to insert the same <code>jti</code>. The first insert lands. The second hits the unique index and Postgres refuses it, SQLAlchemy raises <code>IntegrityError</code>, nothing catches it, and it becomes a 500 that arrives in the browser wearing a CORS costume.</p>
<p>This is time-of-check-to-time-of-use, and it's one of those bugs that's completely obvious in retrospect and completely invisible in review, because the code says what you meant. The gap between the check and the write is where the whole thing lives. On a local machine with one tab, that gap is microseconds and you will never see it. Under any real concurrency, it's just a window, and windows get walked through.</p>
<h2>You cannot fix this with a better check</h2>
<p>The instinct is to tighten the check. Move it closer to the write, wrap it in a transaction, add a lock. Some of that helps. None of it addresses the shape of the problem.</p>
<p><code>SELECT</code> then <code>INSERT</code> is two statements. Whatever you do between them, there is a moment when the first has returned and the second has not yet run, and in that moment another connection can be doing precisely the same thing. You can make the window narrower. You cannot make it not exist, because it is made of the fact that you asked a question and then acted on the answer.</p>
<p>You can go get a lock, and for some problems that's right. But you've now introduced a lock into your hottest auth path to defend against something the database was already going to catch for you, because the unique index on <code>jti</code> was there the whole time. It was doing its job perfectly. The only thing wrong was that nobody was listening to it.</p>
<h2>Let the database decide</h2>
<p>The fix is to stop asking and start attempting:</p>
<pre><code class="language-python">new_tokens = issue_pair(user)
try:
    await blacklist.add(jti)
except IntegrityError as e:
    await session.rollback()          # the transaction is already aborted
    if "ix_blacklist_jti" in str(e.orig):
        raise Unauthorized("please log in again")
    raise                             # a different constraint is a different bug
return new_tokens
</code></pre>
<p>The unique constraint is the arbiter. Exactly one insert can win, the database guarantees it under any amount of concurrency, and the loser gets told so. All that's left is translating a database error into an HTTP response.</p>
<p>The part I find satisfying is that the translation was already decided for us. A duplicate <code>jti</code> means this refresh token has been presented twice. The correct response to a replayed refresh token is to refuse it and make the user authenticate again. So the answer to the race and the answer to a stolen token are the same answer, and the endpoint doesn't need to know which situation it's in. It just needs to be honest that this token is no longer good.</p>
<p>One detail in there is deliberate and looks wasteful. The new token pair is issued before the insert is attempted, so the losing request does work it then throws away. That's fine, and the alternative is worse. Blacklisting first would mean consuming the old token before knowing whether you can successfully issue a replacement, and a failure between those two points logs the user out for no reason at all. Doing the cheap, reversible work first and letting the irreversible step be the one that can fail is the ordering you want whenever you can get it.</p>
<p>The 500 became a 401. The CORS error disappeared, because there was no longer an unhandled exception, and the browser started receiving a response that had passed through the whole middleware stack on its way out.</p>
<h2>Three races, one pattern</h2>
<p>Once the shape is visible you start seeing it. There were three of these in the codebase, and they're now all settled the same way:</p>
<blockquote>
<p><img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/de37fc4d-4c6b-483e-bac3-d037eb1d542c.svg" alt="Three races and their arbiters: a unique jti on the token blacklist yielding a 401, a composite unique on user and story yielding a 409, and an optimistic lock column yielding a 409" /></p>
</blockquote>
<p><strong>Concurrent refresh rotation</strong> is arbitrated by <code>UNIQUE (jti)</code> on the blacklist table. <code>IntegrityError</code> becomes 401, log in again.</p>
<p><strong>Double like or bookmark</strong> is arbitrated by a composite <code>UNIQUE (user_id, story_id)</code>. This is the same bug in a friendlier costume. Someone double-taps a heart on a slow connection, or the client retries a request whose response got lost, and two inserts arrive for a row that should exist at most once. The application version of this guard reads "if the user has already liked it, return early," and it passes for both racers for exactly the same reason the token check did. The composite unique means the database enforces one like per user per story and the application stops pretending to. <code>IntegrityError</code> becomes 409, and the client, which was going to show a filled-in heart either way, carries on.</p>
<p><strong>Concurrent story edits</strong> are arbitrated by an optimistic lock. The stories table carries a <code>row_version</code> column wired to SQLAlchemy's <code>version_id_col</code>, so every update includes the version it read and increments it. Two editors open the same story, both save, and the second <code>UPDATE</code> matches zero rows because the version moved underneath it. SQLAlchemy raises <code>StaleDataError</code>, which becomes a 409 with "this was edited while you were working."</p>
<p>This third one is the one I'd argue hardest for, because its failure mode is the quietest. Without the version column, both saves succeed. The second <code>UPDATE</code> writes the whole row over the top of the first, both requests return 200, both editors see a saved state, and the earlier person's paragraph is simply gone. Nothing errors. Nothing logs. There is no artifact anywhere in the system indicating that an edit was destroyed, and the only way anyone finds out is a human noticing their own work missing and not being believed. A 409 is a small inconvenience by comparison, and it's an inconvenience that arrives at the moment it can still be resolved.</p>
<p>Same structure three times. Don't prevent the race, define what winning means as a constraint, let the database enforce it, and translate the failure into something the client can act on.</p>
<h2>The same experiment, a different kind of failure</h2>
<p>I should say where this code came from, because it changes what the bug means.</p>
<p>I deliberately vibe coded most of this project. I wanted to test the claim that coding agents can build a full-stack app almost end to end, and more importantly to find where that approach failed when nobody was carefully steering the architecture. It's a personal project, which made it a safe place to let the experiment break things.</p>
<p>The first result I got from that was <a href="https://blog.ashishkrjha.dev/my-idle-background-worker-was-the-most-expensive-thing-i-owned">an operational one</a>: an architecture that was entirely conventional and entirely correct, carrying a running cost that appeared nowhere in the source tree.</p>
<p>This one is different, because the defect is in the repository. It's four lines. And it still gets through everything. It type-checks. It can pass review, because there's nothing sloppy to point at. It passes the test suite, and it would pass a test suite twice the size, because the bug does not exist unless two requests overlap and nothing about a normal test run produces overlap. Sequential tests pass. Manual testing passes. Local development, one tab, one request at a time, passes forever.</p>
<p>Check-then-act is the shape you reach for by default, and that's the actual finding. It's how the requirement sounds when you say it out loud. "Don't allow a token to be used twice" becomes "check if it's been used, and if it has, refuse," and the translation from English into code feels lossless. Plenty of straightforward examples use that shape for the same reason, because it mirrors the requirement. It's the readable version, the version that explains itself, and it encodes a single-threaded picture of the world that stops being true the moment two people are using your application.</p>
<p>An agent reproduces convention faithfully, which is usually what you want and is exactly the problem here, because the convention is wrong. There's no sloppiness to catch. It's a correct-looking implementation of a subtly wrong idea about how time works.</p>
<p>A strong reviewer can catch this, and some would have. But ordinary review reads for what the code says, and catching this one requires reading for what two copies of it would do at the same moment, which is a different and more deliberate act. A concurrency test would have made it deterministic instead of leaving it to whether the reviewer happened to be in that mode that day.</p>
<h2>What this costs you</h2>
<p>Not free, and it's worth naming the price rather than presenting this as a pure win.</p>
<p><strong>Your error translation layer becomes load-bearing.</strong> Before, an <code>IntegrityError</code> was an accident. Now it's part of the control flow, which means an uncaught one is a 500 you have chosen to have. Every constraint you rely on needs a handler, and the handler needs to be on the path the error actually takes.</p>
<p><strong>You have to manage the transaction state.</strong> When Postgres raises an <code>IntegrityError</code> it aborts the current transaction. Catch it, return a response, and that connection goes back to the pool still in an aborted state, at which point the next request to pick it up dies immediately with <code>PendingRollbackError</code>. The failure lands on a completely unrelated request, which makes it thoroughly unpleasant to track down. Roll back explicitly in the handler.</p>
<p><strong>You have to know which constraint fired.</strong> Catching <code>IntegrityError</code> broadly and returning 401 is fine when the table has one unique index. When a table has several, a bare <code>except IntegrityError</code> will happily translate a completely unrelated violation into "please log in again," which is a worse bug than the one you fixed because it's misleading. Match on the constraint name.</p>
<p><strong>The error path needs the same care as the happy path.</strong> Which it always did. The difference is that now it's obvious.</p>
<p><strong>And it reads as less safe than it is.</strong> A <code>try/except</code> around a write looks like error handling bolted on. The check looked like a real guard. The intuition is backwards, and if you're working in a team, this is a code-review conversation you'll have more than once.</p>
<h2>What I got wrong</h2>
<p>I spent the first stretch of this in the wrong layer entirely, reading about preflight requests and credentialed origins, because the error message told me to and I believed it. The server log had the answer in it the whole time. I hadn't looked, because the browser had already told me what was wrong with such apparent confidence.</p>
<p>The second thing, and it's the one I'd actually change about how I work: I knew what TOCTOU was. I could have defined it. That didn't help even slightly, because knowing the name of a bug class and recognising it in code you wrote yesterday are unrelated skills. What made it visible was not knowledge, it was reading the traceback and asking why a unique constraint could possibly be violated on a table where the application had just verified the row was absent. That question only has one answer.</p>
<h2>Start smaller than this</h2>
<p>If this is new, you don't need to go and audit everything. One question is enough, and you can ask it about a single endpoint:</p>
<p>Between the moment this code checks a condition and the moment it acts on it, could another request have changed the answer?</p>
<p>If it could, find out what already guarantees correctness underneath. Usually something does, and usually it's a constraint that's been sitting in your schema since the first migration, quietly doing its job while the application asks it questions it already knows the answer to.</p>
<p>You don't have to restructure anything today. Knowing which of your guards are real and which are polite suggestions is most of the value.</p>
<h2>What carries over</h2>
<ol>
<li><strong>A CORS error on an endpoint whose CORS config you haven't touched is probably not a CORS error.</strong> Read the server log first.</li>
<li><strong>Middleware attaches response headers on the way out, and an unhandled exception doesn't take that route.</strong> Every error handler you rely on lives at a specific place in the stack, and errors that escape it produce responses that look nothing like your others.</li>
<li><strong><code>SELECT</code> then <code>INSERT</code> is two statements, and the gap between them is real.</strong> You can narrow it. You cannot close it.</li>
<li><strong>A unique constraint is a decision, not a safety net.</strong> If the database already guarantees the thing you're checking, the check is duplicated logic that's wrong more often than the constraint is.</li>
<li><strong>Attempt, catch, translate.</strong> Let the write fail and turn the failure into an HTTP status the client can act on.</li>
<li><strong>Match on constraint names when a table has more than one.</strong> A broad <code>except IntegrityError</code> will confidently return the wrong error.</li>
<li><strong>Check-then-act passes every test that doesn't have concurrency in it,</strong> which is most tests, which is why this survives review and reaches production.</li>
</ol>
<p>The database was going to enforce it either way. The only question was whether the application found out politely, or as a 500 dressed up as somebody else's problem.</p>
<hr />
<p><em>I'm Ashish Kr Jha, a software engineer. I build things in production and then have to live with them, which is the part that actually teaches you something. More at <a href="https://ashishkrjha.dev">ashishkrjha.dev</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[My Idle Background Worker Was the Most Expensive Thing I Owned]]></title><description><![CDATA[I opened the Cloud Run billing breakdown expecting the database to be the villain. Failing that, the AI generation, which calls out to a model and streams tokens back and feels expensive, in the way t]]></description><link>https://blog.ashishkrjha.dev/my-idle-background-worker-was-the-most-expensive-thing-i-owned</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/my-idle-background-worker-was-the-most-expensive-thing-i-owned</guid><category><![CDATA[Python]]></category><category><![CDATA[devop]]></category><category><![CDATA[Devops articles]]></category><category><![CDATA[DevOps Journey]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Wed, 26 Aug 2026 00:31:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/2368945a-dac3-4814-81f4-ec595f35dd0a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I opened the Cloud Run billing breakdown expecting the database to be the villain. Failing that, the AI generation, which calls out to a model and streams tokens back and <em>feels</em> expensive, in the way that things which visibly do work feel expensive.</p>
<p>Neither. Sitting at the top of the list, by a comfortable margin, was a service that had spent the month doing almost nothing at all.</p>
<p>That service was the background worker, a Celery consumer. Its job is to pick up background tasks: moderate a story when it's published, send a verification email at signup, deliver a webhook, escalate a support ticket. On a personal project with a handful of users, that queue is empty essentially all of the time.</p>
<p>Every other component scaled to zero and cost nothing while idle. This one had been quietly billing me around the clock to sit and wait for work that mostly never arrived. It's a side project, so the bill is mine. I do a regular pass over billing, traffic and error rates for exactly that reason, and this was the week the billing half of it earned its keep.</p>
<h2>TL;DR</h2>
<p>A Celery worker is a polling consumer. Cloud Run only allocates CPU in response to requests. Those two facts are structurally incompatible, and the incompatibility is invisible because everything works perfectly the entire time.</p>
<p>The fix was one environment variable. The interesting part is the four things I had to check about my own codebase before that one variable was safe, and the fact that the obvious cheaper option is broken rather than cheap.</p>
<p>Nothing was broken before I started, and nothing is broken now. What changed is what I'm willing to pay for, and what I gave up to stop paying it.</p>
<p>Most of this project was vibe coded on purpose, as a test of how far that approach goes without close architectural steering. What it produced was a conventional architecture that worked correctly and carried an operational cost nothing in the repository could have told you about.</p>
<h2>What is a worker actually doing when there's nothing to do?</h2>
<p>This is the question I hadn't thought carefully about, and the answer is the entire post.</p>
<p>A web service is easy to reason about on a serverless platform. A request arrives, the platform starts an instance if one isn't running, the instance does the work, and when the traffic stops the platform scales back to zero. You pay for the work. No traffic, no bill. The mental model is clean and it's why scale-to-zero is such a pleasant default.</p>
<p>A Celery worker does not fit that model at all, and it doesn't fit it in a way that is easy to miss.</p>
<p>A worker has no HTTP surface. Nothing can send it a request, because it isn't listening for one. What it does instead is sit in a loop, blocking on <code>BRPOP</code> against Redis, asking the broker over and over whether anything has shown up. Kombu, the transport layer underneath Celery, does this roughly once a second. Forever. That is not a bug or a misconfiguration, it is what a pull-based consumer <em>is</em>.</p>
<p>Now put those two things side by side. Cloud Run allocates CPU in response to requests, and scales up in response to requests. A worker never receives a request. So to keep it alive you have to tell the platform to stop doing the thing it's good at:</p>
<pre><code class="language-plaintext">--min-instances=1 --max-instances=1 --no-cpu-throttling
</code></pre>
<p>Read those flags as a sentence. Always keep exactly one instance running. Never scale it down. Never throttle its CPU when it looks idle, because it always looks idle, right up until the moment it has something to do.</p>
<p>That's one CPU, allocated and billed continuously, whose entire job is to ask an empty queue if anything has happened yet.</p>
<blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/46045d71-591e-497f-b2e3-c1a63cdecf31.svg" alt="Three tracks across one day: a few brief task executions, continuous once-a-second broker polling, and a solid unbroken bar of billed CPU" style="display:block;margin:0 auto" /></blockquote>
<p>And on the other side of the connection, the same loop is generating traffic against Redis all day long. An idle system, producing a steady stream of commands, burning through a free-tier quota to confirm repeatedly that there is nothing to confirm.</p>
<p>The reason this survives so long in a project is that there is no symptom. Nothing is slow. Nothing errors. Tasks run correctly the instant they're enqueued. Every test passes, every dashboard is green, and the only place the problem is visible at all is a billing page you have no particular reason to open.</p>
<h2>The experiment underneath this</h2>
<p>I should say plainly where this architecture came from, because it's the part of the story I find most interesting now.</p>
<p>I deliberately vibe coded most of this project. I wanted to test the claim that coding agents can build a full-stack app almost end to end, and more importantly to find where that approach failed when nobody was carefully steering the architecture. It's a personal project, which made it a safe place to let the experiment break things.</p>
<p>So: an agent wrote the Celery configuration, wired the task modules, set up the broker connection, and deployed the worker as a second service. I reviewed it, it looked right, and it was right.</p>
<p>Ask any competent engineer for background jobs in a Python web app and you'll get Celery, a Redis broker, and a separate worker process. Ask an agent and you'll get the same thing faster, because that is overwhelmingly what the documentation says, what the tutorials say, and what thousands of correct production systems do. It's the right answer on a VM. It's the right answer on ECS, and on a Kubernetes deployment, and on anything with a machine that stays switched on.</p>
<p>It's the wrong answer on Cloud Run, and it's wrong for a reason that does not appear anywhere in the code.</p>
<p>Which is the result the experiment actually returned, and it wasn't the one I expected. The interesting failure wasn't bad code. The generated architecture was conventional, it worked correctly, and left alone it would have kept working correctly for years. The constraint it missed was operational cost, because that information lived outside the repository.</p>
<p>Nothing in that repository is a clue. There's no smell to catch in review, no test that could fail, no lint rule, no type error. Every file is idiomatic. The information you need in order to notice the problem lives in a billing console, in a different browser tab, behind a login the agent doesn't have, describing a pricing model that isn't in the source tree.</p>
<p>An agent optimises for <em>is this the conventional architecture for this stack</em>. That's a good objective and it's usually the one you want. It's just not the same question as <em>what does this cost me every month on this specific platform</em>, and the second question is the one that mattered.</p>
<p>The part I find genuinely instructive is what happened next. When I brought the agent the constraint, once it knew about request-scoped CPU allocation and a personal budget, it reasoned about it perfectly well. The min-instances trap below, the Cloud Tasks alternative, the four safety conditions: that analysis came out of the collaboration, and it's good analysis. The model was never incapable of the reasoning.</p>
<p>It just never raised the question. Nothing prompted it to weigh a running cost, because nothing in the request mentioned one, and an agent will not go looking for a constraint you haven't told it about. That's the same finding as an earlier post of mine about tool loops, arriving from a completely different direction: the model does what the surrounding structure makes it do, and everything outside that structure is invisible.</p>
<blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/a751bb44-65cd-4bd6-a36d-55eec0aab83f.svg" alt="Six steps from a request for background jobs to a continuously billed CPU. The first three sit inside the repository and are all correct; the last three exist only on the billing page" style="display:block;margin:0 auto" /></blockquote>
<p>So this is roughly where I've landed on what the human contributes in a vibe-coded project. Not the code. The code was fine. The contribution is knowing which questions the code cannot answer, and having a habit that puts you in front of the answers anyway.</p>
<h2>Why the obvious fix is broken, not cheap</h2>
<p>The first idea everyone has, including me, is: fine, set <code>--min-instances=0</code> on the worker and let it scale to zero like everything else.</p>
<p>It works. Your bill goes to zero. Your queue silently never drains again.</p>
<p>Think about what would have to happen for that to work. The instance count is zero, so there is no worker running. For a worker to start, something would have to trigger a scale-up. The only thing that triggers a scale-up on Cloud Run is an incoming request. Nothing sends the worker a request, because it has no HTTP surface, because it's a polling consumer. There is no path from "a task was enqueued" to "an instance exists to consume it."</p>
<p>So tasks pile up in Redis. The API keeps accepting work and handing it to the broker perfectly happily. Stories sit in <code>pending</code> and never publish. Verification emails are never sent. Nothing throws, nothing alerts, and every one of those failures looks like a UI problem to whoever reports it.</p>
<p>Guard against this one before it happens, or spend an afternoon staring at a queue depth graph wondering which part of your code is dropping tasks. The answer is none of them.</p>
<p>This is the beat worth taking away from the whole post, and it generalises well past this stack: when you make a pull-based component cheaper, check that anything is still pulling.</p>
<h2>What else was on the table</h2>
<p>Four other options got considered properly before the one I picked.</p>
<p><strong>Cloud Scheduler triggering a Cloud Run Job that drains the queue.</strong> Works, costs about nothing. Keeps Celery, keeps the broker polling, and adds up to N minutes of latency depending on your schedule. More moving parts than the problem deserved.</p>
<p><strong>An e2-micro Always Free VM running the worker.</strong> Viable, and the closest thing to a real alternative. Rejected because it puts a server back in my life, one I'd have to patch and monitor, and because external egress from a VM out to a managed Redis and a managed Postgres is not the kind of free that stays free.</p>
<p><strong>Cloud Tasks pushing to an HTTP endpoint.</strong> This is the right answer. I'll come back to it, because it deserves its own section rather than a table row.</p>
<p><strong>Keeping the worker.</strong> Which is the problem, stated as an option, for completeness. It's worth writing this row down every time you do this exercise. Sometimes the honest conclusion is that the status quo is fine and you should go do something else.</p>
<h2>The one-line fix</h2>
<pre><code class="language-plaintext">CELERY_TASK_ALWAYS_EAGER=true
</code></pre>
<p>In eager mode, <code>.delay()</code> stops being an enqueue. It executes the task immediately, synchronously, inside the calling web process. No broker round-trip, no consumer, no second service. The worker deployment gets deleted outright.</p>
<p>One companion setting matters as much as the flag itself:</p>
<pre><code class="language-plaintext">task_eager_propagates=False
</code></pre>
<p>Without it, an exception inside an eagerly-executed task raises straight into the HTTP request that triggered it. A user signs up, the row is committed, the account exists, the SMTP server has a bad afternoon, and the API returns a 500 for a request that succeeded. The task failing must not be able to convert a completed write into an error response.</p>
<h2>Why inline is safe here, and where it wouldn't be</h2>
<p>This is the part I'd want someone to check before copying the flag into their own project, because "run your background tasks in the foreground" is not universally sound advice. It was sound in this codebase for four specific reasons, and I went and verified each of them rather than assuming.</p>
<p><strong>Every enqueue already happens after the commit.</strong> This is the one that would have bitten hardest. Every call site in the codebase follows the same order:</p>
<pre><code class="language-python">db.commit()
db.refresh(story)
moderate_content.delay(story.id)
</code></pre>
<p>Commit, refresh, then fire. Because the transaction has already closed, the inline task opens its own session and reads a row that exists.</p>
<p>Reverse those two lines and the whole thing falls apart. With <code>.delay()</code> before <code>db.commit()</code>, an inline task runs inside the caller's still-open transaction, opens a separate session, and queries for a row that has not been committed yet. It finds nothing. It has no work to do, so it does nothing, and it does it without complaint. Under the old setup that same ordering mistake would have been survivable, because the network hop to the broker and back bought enough time for the commit to land. Async execution was papering over a latent bug, and eager mode would have torn the paper off.</p>
<p><strong>The tasks are idempotent already.</strong> They were built for at-least-once delivery with <code>task_acks_late</code>, so running one twice is harmless. Inline execution never re-runs anything, but it costs nothing to have confirmed it.</p>
<p><strong>The latency is small where it matters, and I checked the wrong half of that.</strong> <code>moderate_content</code> is a local <code>better_profanity</code> scan. No model call, no network, no IO worth naming. Inline moderation costs milliseconds and the user never perceives it. The mail path is the one with real latency, and this is where I was sloppy. I reasoned about the typical case, put a comfortable number on it, and moved on. The typical case is slower than that in practice and varies with provider and region, signup sends two emails sequentially rather than one, and none of it says anything about the tail. A condition about latency should have been stated as a bound, not as an average</p>
<p><strong>The work happens during a request, which is the whole trick.</strong> Because the task executes inline, it runs while the platform has CPU allocated to serve the request that triggered it. That's the condition the entire approach depends on.</p>
<h2>Why not just use BackgroundTasks?</h2>
<p>FastAPI ships <code>BackgroundTasks</code>, and it looks like the obvious lightweight answer: schedule the work, return the response, let the task run afterwards. On a normal always-on server, that's fine.</p>
<p>On a scale-to-zero platform, it's a trap, and it's a quieter one than the min-instances trap.</p>
<p><code>BackgroundTasks</code> runs your work <em>after</em> the response has been sent. At that moment, from the platform's point of view, the request is finished. CPU gets throttled down to near nothing. Your task doesn't crash and doesn't error, it just gets starved of the CPU it needs to make progress, and if the instance is scaled down before it finishes, it disappears mid-execution.</p>
<p>Inline execution works precisely because it happens <em>before</em> the response, while the request is still open and the CPU is still yours. The distinction between "during the request" and "after the request" carries no weight on a VM and carries all of the weight here.</p>
<h2>The flag is load-bearing, and it fails silently</h2>
<p>Worth stating plainly, because it's the thing most likely to go wrong for someone repeating this: once the worker service is gone, <code>CELERY_TASK_ALWAYS_EAGER=true</code> is not an optimisation. It is required.</p>
<p>Deploy without it and four call sites go back to enqueuing tasks to a broker that nobody is consuming. Story publish stays <code>pending</code> forever. Signup verification emails are never sent. Webhooks are never delivered. Support escalations never escalate. Every one of them fails silently, and every one of them presents as a completely different bug to whoever notices first.</p>
<p>There's a smaller landmine right next to it. The way you set that variable matters:</p>
<pre><code class="language-bash">gcloud run services update ... --update-env-vars CELERY_TASK_ALWAYS_EAGER=true   # correct
gcloud run services update ... --set-env-vars    CELERY_TASK_ALWAYS_EAGER=true   # deletes everything else
</code></pre>
<p><code>--set-env-vars</code> replaces the entire environment list rather than adding to it. Run the second one and you have just silently removed the dozen-odd other variables the service needs, including the database URL. The service then either boots broken or doesn't boot at all, and you get to find out which one on a service you were in the middle of making cheaper.</p>
<h2>So what did it actually cost?</h2>
<p>Nothing broke. That's the honest summary, and it's also less interesting than the trade-off, so here is the trade-off.</p>
<p><strong>Retries went away.</strong> This was the real price and it wasn't a small one. Eager mode does not retry, at all. A transient SMTP failure on signup meant that verification email was lost. At the time I made the call there was no resend path either. Because this is a side project and my availability is strictly capped, I had to make a calculated trade-off between my infrastructure budget and my time budget. I chose to stop the financial bleed immediately and accept a temporarily broken edge case, rather than blocking the cost-fix while I spent weeks building the proper Cloud Tasks push-queue solution. It went straight onto the list of things to fix when time permits.</p>
<p><strong>Time limits went with them, and further than I realised.</strong> <code>task_time_limit</code> is applied by the worker process, so with no worker it isn't loosened, it simply never runs. <code>smtplib</code> doesn't help either: it has no default socket timeout and blocks until the operating system gives up. That leaves the platform's own request timeout as the only remaining bound, which means a hung provider can hold a signup open until that fires and hand the user a gateway timeout on a request whose account row committed successfully. A reader pointed this out after the post went up, and he was right. The fix is two bounds rather than one: a timeout on the client so an attempt fails fast, and a total budget across all attempts and backoff, because attempts multiplied by a per-attempt timeout is the number the user actually experiences.</p>
<p><strong>Task latency became user-visible.</strong> Signup carries the mail round-trip inside the request, twice, since it sends a verification email and an OTP in sequence. It sits in a flow where the user is already waiting and already expects a pause, which is the only reason the trade is tolerable at all. It's also the number I'd look at first if I were doing this again, because two sequential network calls in front of a user is a design decision I never actually made. It arrived as a consequence of one.</p>
<p><strong>Task-level parallelism disappeared.</strong> Background work competes with request handling for the same process.</p>
<p>What I bought with that: idle infrastructure cost goes to zero, broker polling goes to zero, and there is one fewer service to deploy, secure, and monitor. Redis stays in the stack for rate limiting, caching, and the WebSocket pub/sub backplane, so nothing else in the architecture changed.</p>
<p>For a project with this traffic and this budget, that's a good trade. For a project where a lost email is a lost customer, it's a terrible one, and I'd rather be clear about which of those I'm running than pretend the flag is free.</p>
<h2>What I'd build with more time</h2>
<p>The correct answer isn't inline execution. It's push delivery instead of pull.</p>
<p>Replace the polling broker with Cloud Tasks, or Pub/Sub push, targeting an authenticated HTTP endpoint on the backend service that already exists:</p>
<pre><code class="language-plaintext">create story ──► Cloud Tasks enqueue ──► POST /internal/tasks/moderate
                                          └─► Cloud Run cold-starts 0→1,
                                              works, scales back to 0
</code></pre>
<blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/eda47f0c-67da-4547-973c-60094fa9604b.svg" alt="Broker pull versus Cloud Tasks push: a polling consumer that must stay alive to receive work, against an HTTP task that wakes a scaled-to-zero service on delivery" style="display:block;margin:0 auto" /></blockquote>
<p>Every problem in this post dissolves. The task arrives as an HTTP request, which is exactly the thing Cloud Run knows how to wake up for. You keep scale-to-zero <em>and</em> genuine asynchronous execution <em>and</em> managed retries with backoff, which is the thing I gave up. Cloud Tasks' free tier covers a million operations a month, so at this volume it would also be free.</p>
<p>It is strictly better than both the always-on worker and the inline switch. I didn't build it because it's a re-architecture of every enqueue path in the codebase, and the inline flag was a one-line change that solved the bill that week. That's a scheduling decision rather than a technical judgement, and writing it down is how I stop myself pretending otherwise a year from now.</p>
<p>I wrote the revisit conditions down at the time: when task volume grows, when retries start mattering, when a task exceeds about a second of user-visible latency, or when the project is funded by something other than my own wallet.</p>
<h2>Start smaller than this</h2>
<p>If you're reading this with a queue somewhere and a vague sense of unease, you don't need to do any of the above today. Do the cheap part first.</p>
<p>Open your billing breakdown and sort by cost. That's the entire discovery step, and no amount of tooling will do it on your behalf. It's worth making it a habit rather than a reaction, because the failure mode here is a cost that never announces itself: nothing pages you, nothing turns red, and the only signal is a line item that's higher than you'd have guessed.</p>
<p>Then, for whatever's at the top, ask one question: does this thing get woken up, or does it wake itself up? Anything that wakes itself up on a platform that bills for allocated CPU is worth ten minutes of attention. That covers pollers, cron loops inside long-lived processes, websocket keepalives, and any consumer that blocks on a broker.</p>
<p>You don't have to fix it. Knowing which category each of your services falls into is most of the value, and it's the part that transfers to the next platform you use.</p>
<h2>What carries over</h2>
<ol>
<li><p><strong>A pull-based consumer and a request-billed platform are structurally incompatible.</strong> Not a tuning problem. The consumer never receives the thing the platform bills for.</p>
</li>
<li><p><strong>When you make a polling component cheaper, check that anything is still polling.</strong> <code>min-instances=0</code> on a worker is broken, not cheap, and it breaks silently.</p>
</li>
<li><p><strong>"During the request" and "after the request" are different execution environments</strong> on a scale-to-zero platform, even though they look identical in your code.</p>
</li>
<li><p><strong>Enqueue after commit, always.</strong> Async transport hides this bug. Inline execution exposes it immediately.</p>
</li>
<li><p><strong>Before you make async work synchronous, check idempotency, latency, and ordering.</strong> Three questions, and if any answer is wrong the flag is unsafe.</p>
</li>
<li><p><strong>Write down the answer you didn't build.</strong> Deferred is not the same as rejected, and future you will not remember which one it was.</p>
</li>
<li><p><strong>Read the flags you deploy with as a sentence.</strong> <code>--min-instances=1 --no-cpu-throttling</code> says "bill me continuously" out loud, if you let it.</p>
</li>
<li><p><strong>An agent gives you the conventional architecture, which is a different thing from the correct one here.</strong> It will reason about your constraints well and it will not go looking for them. The failure mode to watch for isn't bad code, it's good code carrying a constraint that lives outside the repository.</p>
</li>
</ol>
<p>The cheapest service in your stack is the one that doesn't exist. The second cheapest is the one that only exists when someone asks it to.</p>
<hr />
<p><em>I'm Ashish Kr Jha, a software engineer. I build things in production and then have to live with them, which is the part that actually teaches you something. More at</em> <a href="https://ashishkrjha.dev"><em>ashishkrjha.dev</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[No fetch, No Storage: Shipping Inside a Sandboxed Host]]></title><description><![CDATA[The answer came back in writing, from the vendor, and it amounted to: yes, and you'll be building it yourself.
The question had been a simple one. The platform we build on has an agent feature. Admini]]></description><link>https://blog.ashishkrjha.dev/no-fetch-no-storage-shipping-inside-a-sandboxed-host</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/no-fetch-no-storage-shipping-inside-a-sandboxed-host</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[#ai-tools]]></category><category><![CDATA[ai agents]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Sat, 22 Aug 2026 04:31:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/8dadfff5-127a-4670-874f-efa1bc6e8717.svg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The answer came back in writing, from the vendor, and it amounted to: yes, and you'll be building it yourself.</p>
<p>The question had been a simple one. The platform we build on has an agent feature. Administrators define agents with their own tool queries, their own context rules, their own everything. They're good, and business users had opinions about what they wanted from them.</p>
<p>On the web client, those agents work.</p>
<p>On the native app, which is where the actual users are, they don't. Not a bug, not a roadmap item with a date, just a capability that exists on one client and not the other. So we asked how to close the gap, expecting either a workaround or a wait.</p>
<p>What we got instead was the sentence at the top of this post. The only supported way to reach those agents from the native app is to write the client yourself, as an embedded content package, running inside the host's own sandbox. Not an integration. Not a plugin. A whole application, built under someone else's rules, on a surface designed for dashboards.</p>
<p>So that's what this is about. Not the agents. The sandbox.</p>
<h2>TL;DR</h2>
<p>A locked-down host blocked <code>fetch</code>, blocked XHR, and blocked every form of browser storage. Its own SDK shipped a generic HTTP method, which turned out to be the sanctioned way around its own restriction. Normalise the platform differences at exactly one file, treat the async execution API as a job queue rather than a request, and be generous with your timeout ceiling when you don't control the workload.</p>
<p>The bug worth reading about is the poll loop, which spent a while confidently reporting failure for things that were still working.</p>
<h2>The gap</h2>
<p>This shape is more common than it sounds. A platform ships several clients, they don't reach feature parity at the same time, and the capability you need lives on the one your users aren't holding.</p>
<p><img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/37858ca1-17e2-4f2d-b945-3eec418fc4a5.svg" alt="10-capability-gap" /></p>
<p>Your options when that happens are usually: wait, tell users to switch clients, or build the missing surface yourself. Waiting had no date attached. Users were on tablets all day and weren't switching. So, build.</p>
<p>The catch is that "build it yourself" here doesn't mean a normal web app that calls an API. It means a bundle running inside the host's own embedded content sandbox, under the host's rules.</p>
<h2>What the sandbox takes away</h2>
<p>Three things, and none of them are negotiable.</p>
<p><strong>No <code>fetch</code>, no XHR, no axios.</strong> Direct HTTP from embedded content is blocked. Not CSP-blocked in a way you can argue with, just unavailable.</p>
<p><strong>No storage of any kind.</strong> No <code>localStorage</code>, no <code>sessionStorage</code>, no IndexedDB. Everything lives in memory for the lifetime of the view, or it round-trips through the host's own record API.</p>
<p><strong>No web root.</strong> Content is served from inside a package, so every asset path has to be relative. One <code>base: './'</code> in the build config, which is trivial once you know and confusing for an afternoon if you don't.</p>
<p>For a chat interface, that second one is the sharp edge. Chat is a stateful, conversational thing and the obvious place to keep a thread is local storage. You can't. Either you accept that a thread dies when the view unmounts, or you serialise it into a host record and rehydrate on load. We did the second, but only after building the first and discovering how much people expect a chat to remember.</p>
<h2>The escape hatch is in the box</h2>
<p>Here's the part I'd want someone to tell me earlier.</p>
<p>The host's SDK, the one you're required to load anyway, exposes two methods that together undo the restriction:</p>
<pre><code class="language-js">host.getSessionId()   // → { sessionId, url, isSandbox }
host.request(config)  // → generic HTTP
</code></pre>
<p>That's it. <code>request</code> is a general-purpose HTTP method that takes a URL, a verb, headers, and a body. From its point of view the platform's own API is just another endpoint.</p>
<p><img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/694ae655-9263-428b-bb88-6d5a677b4960.svg" alt="11-escape-hatch" /></p>
<p>This isn't a loophole and it isn't clever. It's the sanctioned path, and it exists for a reason worth internalising: <strong>a host that blocks network access still needs its own embedded content to reach the network.</strong> So it ships a proxy and routes everything through it, where it can be inspected, authenticated, and governed. The restriction isn't "no HTTP," it's "no HTTP we can't see."</p>
<p>If you're ever staring at a platform that seems to have walled off something fundamental, look for the method the platform uses itself. It's usually right there in the SDK, documented, under a name that doesn't sound like what you need.</p>
<p>The other half is authentication. <code>getSessionId</code> hands back a session token, and the documentation is slightly nervous about it. The token is described as intended for exchanging auth with <em>external</em> applications. Using it to call the platform's own API is a reasonable reading, but it isn't the stated purpose.</p>
<p>That went on the validation list as the first thing to prove. If it hadn't worked, everything downstream would have needed a proxy service and the shape of the whole project would have changed. It worked. But it was the right thing to check on day one rather than day twenty.</p>
<h2>One file knows about platforms</h2>
<p>The host runs on more than one platform, and the two wrap the response from <code>request</code> differently. One returns a string. One returns an object with the payload nested inside, under a key that varies.</p>
<p>There is exactly one correct way to handle that, and it's to normalise once:</p>
<pre><code class="language-js">async function rawRequest(path, method = 'GET', body = null) {
  const ctx = await getContext();

  const config = {
    url: `${ctx.baseUrl}/api/${ctx.apiVersion}${path}`,
    method,
    headers: {
      Authorization: ctx.sessionId,
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    timeout: 60,
    expect: 'text',
  };
  if (body) config.body = JSON.stringify(body);

  // one platform needs a string argument; stringifying is safe on both
  const raw = await host.request(JSON.stringify(config));

  // platforms wrap the payload differently. This is the only place that knows.
  const text = typeof raw === 'string'
    ? raw
    : raw.data ?? raw.body ?? raw.response ?? '';

  return JSON.parse(text);
}
</code></pre>
<p>Every other file in the codebase calls a wrapper around this one and has no idea more than one platform exists. That sounds obvious written down. It is obvious. It is also the thing that decays first, because the second time you hit a platform difference you're deep in a component and it's so much faster to add a conditional right there.</p>
<p>Two small things worth stealing from that function. <code>JSON.stringify</code> on the config is unconditional even though only one platform requires it, because a rule with no exceptions survives longer than a rule with one. And session handling sits just above it: cache the session, and on an invalid-session response, clear the cache and retry exactly once before surfacing an error. Once, not in a loop.</p>
<h2>Execution is a job queue, not a request</h2>
<p>The agent API doesn't answer your question. It accepts it.</p>
<pre><code class="language-js">POST /agents/execute
→ { status: 'IN_PROGRESS', executionId: '...' }
</code></pre>
<p>The actual output only exists later, on a separate status endpoint, once the work finishes. So the client has to hold an execution ID, poll, and render a thinking state in between.</p>
<p>Three details that carry real weight:</p>
<p><strong>Idempotency is your job.</strong> Every execution carries a client-generated request ID and the platform rejects duplicates, including against past executions. Generate it per execution, not per session, and make it genuinely unique:</p>
<pre><code class="language-js">requestId: `chat_${Date.now()}_${crypto.randomUUID()}`
</code></pre>
<p><strong>Threading is a token you carry.</strong> The first turn's response includes a chat ID. Pass it into subsequent executions and the platform keeps the conversation coherent. Drop it and every turn is a stranger.</p>
<p><strong>Cancellation is two things.</strong> There's a cancel endpoint on the server, and there's an <code>AbortController</code> for your poll loop. A stop button needs both, or you get a UI that has stopped listening to work that hasn't stopped happening.</p>
<h2>The poll loop was wrong, and it was wrong in an interesting way</h2>
<p>Original settings: poll every 2.5 seconds, give up after 10 attempts. About 25 seconds.</p>
<p>Then it started reporting failures.</p>
<p>Not many, and not reproducibly, which is the worst kind. Some agent actions came back in two seconds. Some took fifteen. Checking the actual execution data, a few ran past thirty.</p>
<p>The obvious read is "your timeout was too short." That's true, and it's also the least interesting thing about it.</p>
<p>Here's the real problem. The loop looked like this:</p>
<pre><code class="language-js">for (let i = 0; i &lt; maxAttempts; i++) {
  const status = await getStatus(executionId);
  if (status !== 'IN_PROGRESS') return status;
  await sleep(intervalMs);
}
throw new Error('Agent execution failed');
</code></pre>
<p>Read that last line again. When the loop runs out, it reports <strong>failure</strong>. But nothing failed. The server never said no. The agent was still working, and would have finished, and probably did finish, into a void where nobody was listening.</p>
<p>The client was reporting a server outcome it had never received.</p>
<p><img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/e1c4c8ca-69cf-43f9-8b3c-8d47aaf5f012.svg" alt="12-poll-outcomes" /></p>
<p>A poll loop has three possible endings and most implementations only encode two:</p>
<ol>
<li>The work completed</li>
<li>The work explicitly failed</li>
<li><strong>I stopped waiting</strong></li>
</ol>
<p>The third is a statement about the client, not the server, and collapsing it into the second means telling users something is broken when it isn't. Worse, it's unfalsifiable from the UI. The user sees "failed," retries, generates a new execution, and now there are two running.</p>
<p>The fix has two parts. Give up much later, with an increasing interval so you're not hammering the status endpoint for four minutes. And when you do give up, say what actually happened: <em>this is taking longer than expected and is still running</em>, not <em>this failed</em>.</p>
<h2>Why the ceiling is generous</h2>
<p>The number we landed on is 100 attempts with a growing interval. That is a lot, and it's deliberate.</p>
<p>This was built to be portable. Zip it, drop it into another org, configure the entry point, and it works. Which means the agents it will be talking to are ones I have never seen, built by administrators I have never met, doing work I cannot predict.</p>
<p>Someone smarter than me is going to build an agent that traverses four levels of related records and calls out to something slow. That agent will take a while. If my client gives up at twenty-five seconds because that was comfortable for the agents <em>I</em> tested against, their agent looks broken and the fault will look like theirs.</p>
<p>So the ceiling isn't tuned. It's generous on purpose, because I don't control the workload. That's not the same as being careful, and I'd rather be honest that 100 is a number I chose to be safely past anything I could imagine, not a bound I measured.</p>
<p><strong>When you're shipping something other people will drop into environments you'll never see, the correct posture on timeouts is cowardice.</strong></p>
<h2>Developing outside the host</h2>
<p><code>host</code> doesn't exist on your laptop. It's injected by the platform's library at runtime, so a local dev server has nothing to call.</p>
<p>Same answer as every embedded-host project: shim it.</p>
<pre><code class="language-js">export function installHostMock() {
  if (window.host) return;   // real environment, do nothing

  window.host = {
    getSessionId: async () =&gt; ({
      sessionId: import.meta.env.VITE_DEV_SESSION,
      url: import.meta.env.VITE_DEV_BASE_URL,
      isSandbox: true,
    }),
    request: async (cfg) =&gt; {
      const c = typeof cfg === 'string' ? JSON.parse(cfg) : cfg;
      const r = await fetch(c.url, {
        method: c.method, headers: c.headers, body: c.body,
      });
      return { success: true, data: await r.text() };
    },
  };
}
</code></pre>
<p>Plus a dev-server proxy so local requests dodge CORS. The guard on the first line matters more than it looks: the mock must be a no-op inside the real host, because the day it isn't, you'll spend an hour wondering why production is reading your laptop's environment variables.</p>
<p>Worth saying: the mock is not a simulator. It gets you a working UI loop and honest network calls, and it will not reproduce the platform response-shape differences, the auth behaviour, or anything about the native runtime. Those only surface in the real thing, which is why the validation list existed before the UI did.</p>
<h2>The validation list</h2>
<p>Before any interface code, six things got proven:</p>
<ul>
<li>The session token is accepted by the target API</li>
<li>All endpoints respond as documented, tested outside the sandbox first with plain HTTP</li>
<li>Actions are exposed to the API at all, since the platform hides ones not explicitly flagged</li>
<li>The authenticated user actually has permission to execute them</li>
<li>Cross-origin behaviour on the web client</li>
<li>The exact response shape from <code>request</code> on each platform, captured as real payloads</li>
</ul>
<p>Two of those turned out to be non-issues. Cross-origin was fine, and the fallback proxy I'd sketched for it never got built. That's not wasted effort. It's a risk that got cheap to dismiss because it was checked early rather than discovered late.</p>
<p>The one that mattered was the last. Capturing the real envelopes from both platforms up front is what let the normalization live in one function instead of being reverse-engineered from bug reports over three weeks.</p>
<p>The general version: <strong>your riskiest assumption should be the first thing you test, and it is almost never the thing you're most excited to build.</strong></p>
<h2>What it turned into</h2>
<p>The thing I didn't anticipate was what happened after the demo.</p>
<p>Business users are now looking at agents that were previously theoretical to them, on the device they actually use. And having seen it, they started proposing things. Could it do this. What about that. Some of those were straightforward, some needed new agents built on top of the platform's own, and several worked.</p>
<p>That loop is worth more than the client is. A chat window is not a hard thing to build. A chat window that puts a capability in front of the people who have opinions about it, on the device they're holding, turns those opinions into a queue of things worth building.</p>
<h2>What carries over</h2>
<p>Strip the vendor out and the transferable bits are short:</p>
<ol>
<li><strong>When a platform blocks something fundamental, look for the method it uses itself.</strong> Constrained hosts ship their own escape hatch, because they need one too.</li>
<li><strong>Prove the auth path on day one.</strong> Everything downstream depends on it and it's the assumption most likely to be wrong.</li>
<li><strong>Normalise platform differences at exactly one file</strong> and let nothing above it know they exist.</li>
<li><strong>Treat async execution as a job queue.</strong> Idempotency keys, a thread token, cancellation on both ends.</li>
<li><strong>A poll loop has three endings, not two.</strong> "I stopped waiting" is not "it failed."</li>
<li><strong>Be a coward about timeouts when you don't control the workload.</strong></li>
<li><strong>Mock the host for local development, and don't mistake the mock for the platform.</strong></li>
</ol>
<p>None of that is specific to any vendor. It's what working inside somebody else's sandbox looks like, and the sandboxes are multiplying.</p>
<hr />
<p><em>I'm Ashish Kr Jha, a software engineer. I build things in production and then have to live with them, which is the part that actually teaches you something. More at <a href="https://ashishkrjha.dev">ashishkrjha.dev</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Instructions Are Hints: Guardrails for an LLM Tool Loop]]></title><description><![CDATA[I wrote the same rule three times.
Once in the tool description, so the model would read it while deciding what to call. Once in the system prompt, in capitals, because the first one wasn't holding. A]]></description><link>https://blog.ashishkrjha.dev/instructions-are-hints-guardrails-for-an-llm-tool-loop</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/instructions-are-hints-guardrails-for-an-llm-tool-loop</guid><category><![CDATA[#ai-tools]]></category><category><![CDATA[Developer Tools]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[ai agents]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Fri, 21 Aug 2026 21:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/e5ee0033-1e7a-4aaf-acd1-717ef89565d4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I wrote the same rule three times.</p>
<p>Once in the tool description, so the model would read it while deciding what to call. Once in the system prompt, in capitals, because the first one wasn't holding. And once in the executor, as four lines of JavaScript that simply refuse.</p>
<p>Only the third one works. That's most of what I learned building this.</p>
<p>The project was an assistant embedded in an enterprise CRM. A user asks a question in plain language, and the model answers from live records rather than from anything it was trained on. No hardcoded queries, no baked-in field lists. It navigates the data model itself.</p>
<p>It never shipped. The vendor released their own agents partway through, they were better suited to the domain than mine, and I stopped. The guardrails below are the part worth keeping, and they had nothing to do with that decision.</p>
<h2>TL;DR</h2>
<p>Publish a filtered schema artifact instead of putting the data model in the prompt. Give the model three tools: list the objects, describe named objects, query one object. Then assume every instruction you write will be ignored eventually, and enforce the ones that matter in the executor. Instructions are advisory. Code is not.</p>
<h2>The problem: 530 objects</h2>
<p>The org's metadata extract describes <strong>530 objects across roughly 13,000 fields</strong>.</p>
<p>You cannot put that in a prompt. You also cannot hardcode the queries, because the whole point was that adding an object shouldn't mean a code change. And you can't let the model guess field names, because it will, confidently, and the query will fail in a way that costs you three hops to recover from.</p>
<p>The field counts are lopsided in a way that matters. The median object has 30 fields. The widest has <strong>232</strong>. So "just fetch the schema for the object you need" is fine right up until the model picks the wrong one and drops 232 field definitions into the conversation.</p>
<h2>Filter first, at build time</h2>
<p>Before anything reaches the model, a Node script pulls the org's metadata extract and cuts it down:</p>
<p><strong>An object allowlist.</strong> 85 API names, hand-picked, covering the parts of the CRM anyone actually asks about. That's 16% of the org. Adding an object is a one-line edit and a re-fetch, which was the design goal.</p>
<p><strong>A system-field blocklist.</strong> Exact names for the obvious ones (<code>created_by</code>, <code>modified_date</code>), plus patterns for the rest: anything ending <code>_share</code>, <code>_history</code>, <code>_feed</code>, <code>_tag</code>, anything starting <code>audit_</code> or <code>system_</code>. Audit metadata is invisible to the model because no user has ever asked a question that needed it.</p>
<p><strong>Picklist values dropped entirely.</strong> This one surprised me. The enumeration of every valid picklist value was roughly 80% of the file, and it's useless. The actual value comes back attached to each record when you query it. All you'd be shipping is a dictionary of cryptic codes for the model to wade through.</p>
<p><img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/347b35f8-4503-4570-81c9-5cc4a3545ada.svg" alt="schema-filter" /></p>
<p>What comes out the other side: <strong>85 objects, 3,482 fields, 487 KB</strong>. Around 120,000 tokens of data model.</p>
<p>Which never enters a context window. The client fetches it, holds it in memory for the session, and answers tool calls from it. The model sees a list of 85 names, then the fields for the two or three objects it actually needs.</p>
<h2>Make the graph closed</h2>
<p>One detail I'd repeat on any project like this.</p>
<p>Each field that points at another object gets a <code>references</code> annotation, and after all objects are built, a second pass populates a <code>referencedBy</code> reverse index. 366 edges, with 49 objects carrying at least one back-reference. So when the model reads any object's schema, it can see what connects to it without asking another question.</p>
<p>The part worth stealing: <strong>a reference is only attached if the target survived the allowlist.</strong></p>
<p>If an object was filtered out, every pointer to it is silently dropped. The model never sees a link it can't follow. Without that, you get a model that reads a schema, spots a promising relationship, asks for the target object, gets told it doesn't exist, and burns two hops recovering from a dead end you created.</p>
<p>The graph the model sees is closed under the filter. That's four lines in the build script and it removes an entire category of confusion.</p>
<h2>Three tools</h2>
<pre><code>list_objects       → every object, API name plus human label
get_object_schema  → fields for one or more named objects
query_records      → records from one object
</code></pre>
<p>The middle one takes an <strong>array</strong>, deliberately. The model needs five objects for a typical question, and five separate calls is five hops. One call with five names is one hop. The whole cost model of a tool loop is round trips, so batching is not a micro-optimisation.</p>
<p>And the loop executes <strong>every tool call in a single response concurrently</strong>. The model routinely groups independent work into one turn: schemas for two objects, a query against a third. If you handle only the first call and ignore the rest, you turn one hop into three, and non-trivial questions hit the cap.</p>
<pre><code class="language-js">const results = await Promise.all(
  calls.map((c) =&gt; executor(c.name, c.args ?? {})),
);
</code></pre>
<p>That's the entire mechanism. Easy to miss, expensive to miss.</p>
<h2>The part I got wrong: instructions are hints</h2>
<p>Here's the rule I wanted enforced: <em>don't ask for a schema you already have.</em></p>
<p>Obvious, right? The earlier response is still in the conversation. Re-requesting it is pure waste, and the model can see its own history.</p>
<p>So I wrote it in the tool description, where the model reads it while choosing what to call:</p>
<blockquote>
<p><em>DO NOT re-request a schema you already have in this conversation.</em></p>
</blockquote>
<p>It kept happening. So I wrote it again in the system prompt, harder:</p>
<blockquote>
<p><em>DO NOT re-request a schema you already have in this conversation. The tool response you got earlier is still in context, so read from there.</em></p>
</blockquote>
<p>It still happened. Less often, and never on short conversations, which is worse in a way, because it meant the failure only appeared when the loop was already long and I'd stopped watching.</p>
<p>So I wrote it a third time, in the executor:</p>
<pre><code class="language-js">const schemasReturned = new Set();

case "get_object_schema": {
  const requested = args?.objects ?? [];
  const fresh = requested.filter((n) =&gt; !schemasReturned.has(n));
  const alreadyFetched = requested.filter((n) =&gt; schemasReturned.has(n));
  fresh.forEach((n) =&gt; schemasReturned.add(n));

  result = getObjectSchema(schema, fresh);
  if (alreadyFetched.length &gt; 0) {
    result.alreadyFetched = alreadyFetched;
    result.note = "Objects listed in `alreadyFetched` were returned in an "
      + "earlier tool response. Consult it instead of re-requesting.";
  }
  break;
}
</code></pre>
<p>A <code>Set</code>. That's it. Ask twice and you get the names back with a note instead of the payload.</p>
<p><img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/376be2cf-83f9-4e4e-9848-b64033df5773.svg" alt="three-layers" /></p>
<p>The three layers do genuinely different jobs, and I'd argue you want all three:</p>
<p><strong>The tool description</strong> is read at decision time, when the model is choosing what to call. Highest leverage per word, and the surface people most often leave as bare API documentation. Mine tells the model when <em>not</em> to call a tool: <em>"if you already have a good guess, skip this and go straight to get_object_schema."</em></p>
<p><strong>The system prompt</strong> sets policy for the whole conversation. Good for things that aren't about any single tool.</p>
<p><strong>The executor</strong> is the only one that's true. Everything above it is a strong suggestion to a system that is, by construction, allowed to ignore you.</p>
<p>I'd got that backwards for a while. I kept editing prose, because editing prose feels like progress and writing a guard feels like admitting the prose didn't work. It didn't work. Four lines of code fixed what two rounds of increasingly emphatic capital letters could not.</p>
<h2>Errors that tell the model what to do next</h2>
<p>The same idea applies to failures. Every guard returns something the model can act on:</p>
<pre><code class="language-js">// object not on the allowlist
{ error: "Unknown object 'x'. Call list_objects first." }

// running outside the host application
{ error: "queryRecord unavailable. Not running inside the CRM." }
</code></pre>
<p>That second half of each message is the useful part. An error saying "unknown object" gets you a model guessing again. An error saying "unknown object, call list_objects first" gets you a model calling <code>list_objects</code> and recovering in one hop.</p>
<p>You are writing error messages for a reader who will act on them immediately and literally. That's a different audience from the one your usual API errors are written for, and it's worth adjusting the tone.</p>
<h2>The token discovery</h2>
<p>This one cost me an afternoon.</p>
<p>I'd set <code>maxOutputTokens</code> to 1024. Seemed generous, given the answers are meant to be short, under 250 words, on a tablet screen.</p>
<p>Responses came back truncated. Sometimes mid-sentence, sometimes empty with <code>finishReason: MAX_TOKENS</code> and no text at all. Which makes no sense for a 250-word answer, until you look at the usage numbers the API returns per call:</p>
<pre><code>tokens in/out/thoughts: 6412/240/1180
</code></pre>
<p>240 tokens of answer. <strong>1,180 tokens of reasoning.</strong> Five times more thinking than output, and on this model family the thinking counts against the same output budget.</p>
<p><img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/834d36b8-cfc8-4d79-812a-8409bc2c7c78.svg" alt="token-split" /></p>
<p>So a 1024 cap wasn't a generous budget for a short answer. It was a budget the model could exhaust entirely on internal reasoning before writing a single word the user would see.</p>
<p>I raised it to 8192 and logged <code>finishReason</code> plus the full usage breakdown on every hop. Two things I'd do from the start next time:</p>
<p><strong>Log the token split per call.</strong> Not just the total. The in/out/thoughts breakdown is what turns "why is this truncated" into an answer in ten seconds.</p>
<p><strong>Filter the reasoning out of what you render.</strong> Those parts arrive flagged, and if you concatenate every text part naively you will ship "let me do a more precise count here…" straight into the user's chat bubble. One filter, easily forgotten:</p>
<pre><code class="language-js">const textParts = parts
  .filter((p) =&gt; typeof p.text === "string" &amp;&amp; !p.thought)
  .map((p) =&gt; p.text);
</code></pre>
<h2>Two kinds of budget</h2>
<p>The loop has a hard ceiling of 10 hops. Past that it throws, and the error carries a trail of which tools ran on which hop, so you can see what the model was doing when it got stuck.</p>
<p>But the system prompt separately says: <em>aim to finish common questions in 2-3 turns.</em></p>
<p>Those aren't the same mechanism. The soft budget shapes behaviour, because the model batches more aggressively when it knows it's meant to be quick. The hard cap is there for when shaping fails. One is a nudge, the other is a wall, and a loop with only one of them is either sloppy or unnecessarily rigid.</p>
<p>Same for the ID rule, which is a user-experience guardrail rather than a cost one:</p>
<blockquote>
<p><em>Never show raw record IDs. If a record has an ID pointing at another object, query that object for its name and use that instead. "Dana Whitfield (12 interactions)", never "rec_8f31c0a4: 12 interactions."</em></p>
</blockquote>
<p>Nothing enforces that in code. It's a genuine soft rule and it mostly holds, because unlike the schema-refetch rule it aligns with what the model is naturally inclined to do.</p>
<p>That's the distinction worth internalising: <strong>soft rules work when they push in the direction the model already leans. Enforce the ones that push against it.</strong></p>
<h2>Keyword tasks over a general assistant</h2>
<p>One structural choice that paid off more than expected.</p>
<p>Rather than one assistant answering anything, four keyword-triggered tasks. Type <code>brief</code> and the system prompt gains a fragment naming exactly which objects to fetch, in what order, and what shape the answer should take. Type nothing special and you get the general mode.</p>
<p>Each task prompt is specific to the point of being boring:</p>
<pre><code>Look up the customer id from the page context. Then, in ONE turn,
batch these schema lookups:
  • get_object_schema for: customer, interactions, orders, open_tasks, notes

Then, in the NEXT turn, emit these queries IN PARALLEL:
  • customer where id = '&lt;id&gt;' (limit 1)
  • interactions where customer = '&lt;id&gt;' order by date desc (limit 5)
  • orders where customer = '&lt;id&gt;' order by date desc (limit 10)
  ...
</code></pre>
<p>That converts an open-ended retrieval problem into a mostly-determined one. The model still resolves IDs and synthesises the answer, but it isn't rediscovering the data model on every request.</p>
<p>The general mode still exists for anything the four tasks don't cover. It's just slower and less reliable, which is the honest trade.</p>
<h2>Do you need a domain-specific model for this?</h2>
<p>The question I got asked most, and the one I'd been expecting to answer yes to.</p>
<p>The answer here was no, and I think the threshold sits further out than people assume. 85 objects and 3,482 fields fit comfortably into retrieval over a general model. The model doesn't need to <em>know</em> the data model. It needs to be able to <em>look it up</em> cheaply, and three tools over a 487 KB artifact does that.</p>
<p>What I deferred, with the trigger written down so it isn't a vibe:</p>
<p><strong>Vector search over the schema.</strong> Worth it if the allowlist grows past roughly 200 objects and matching a question to the right object starts failing on names alone. At 85 it never did.</p>
<p><strong>Curated domain packs.</strong> Named groups of related objects the model could request as a unit. The task prompts already name their objects explicitly, so packs only help if free-form questions start missing cluster boundaries.</p>
<p><strong>A server-side proxy for the model API.</strong> Not optional for production. Client-side environment variables compile into the bundle as plain strings. Fine for a prototype key you rotate, wrong for anything real.</p>
<p>Writing the trigger next to the deferral is the part I'd keep. "We'll add embeddings if we need them" decays into either never revisiting it or adding it because it sounded due. "We'll add embeddings past 200 objects" is a decision you can actually check against.</p>
<h2>What I'd keep</h2>
<p>Strip the domain out and the transferable parts are short:</p>
<ol>
<li><strong>Publish the schema as a versioned artifact.</strong> Filter it hard at build time, and never load it into context.</li>
<li><strong>Close the graph under your filter.</strong> No pointers to things the model can't fetch.</li>
<li><strong>Batch by design.</strong> Array parameters, parallel execution per hop. Round trips are the cost.</li>
<li><strong>Write the rule three times, and mean the third one.</strong> Tool description, system prompt, executor. Only the last is enforcement.</li>
<li><strong>Make errors instructive.</strong> Say what went wrong and what to call next.</li>
<li><strong>Log the token split per hop</strong>, including reasoning tokens.</li>
<li><strong>Two budgets.</strong> A soft one to shape behaviour, a hard one for when shaping fails.</li>
<li><strong>Write the trigger next to every deferral.</strong></li>
</ol>
<p>None of it is clever. All of it came from watching a loop misbehave and fixing the specific thing, which is the only method I know that reliably works.</p>
<h2>This is the third of three on the same idea</h2>
<p>Part 1 built a queryable index over a codebase so a search returns ten lines instead of a repository. Part 2 handed an agent the dependency neighbourhood around a change rather than the whole project. This one hands a model 85 objects out of 530.</p>
<p>Same argument three times: <strong>the win is in what you don't send.</strong> The context window keeps getting bigger and it keeps not being the answer.</p>
<ul>
<li><a href="https://blog.ashishkrjha.dev/build-a-typescript-code-graph-with-the-compiler-api">Build a TypeScript Code Graph with the Compiler API</a></li>
<li><a href="https://blog.ashishkrjha.dev/code-graphs-for-ai-coding-agents-better-repository-context-and-safer-refactoring">Code Graphs for AI Coding Agents</a></li>
</ul>
<hr />
<p><em>I'm Ashish Kr Jha, a software engineer. I build things in production and then have to live with them, which is the part that actually teaches you something. More at <a href="https://ashishkrjha.dev">ashishkrjha.dev</a>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Code Graphs for AI Coding Agents: Better Repository Context and Safer Refactoring]]></title><description><![CDATA[You've probably watched this happen.
You ask an agent to add a rule to checkout. It opens CheckoutPage.tsx, then CheckoutButton.tsx, then checkout.css, because they all have "checkout" in the name, an]]></description><link>https://blog.ashishkrjha.dev/code-graphs-for-ai-coding-agents-better-repository-context-and-safer-refactoring</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/code-graphs-for-ai-coding-agents-better-repository-context-and-safer-refactoring</guid><category><![CDATA[#ai-tools]]></category><category><![CDATA[ai agents]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[AI]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Thu, 20 Aug 2026 22:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/384bee89-488a-45ce-b4a6-092291b2c464.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You've probably watched this happen.</p>
<p>You ask an agent to add a rule to checkout. It opens <code>CheckoutPage.tsx</code>, then <code>CheckoutButton.tsx</code>, then <code>checkout.css</code>, because they all have "checkout" in the name, and after forty seconds of enthusiastic reading it writes a change in the wrong place. The actual logic was in <code>validateOrder</code>, which the agent never opened, because nobody named it <code>checkoutValidation</code>.</p>
<p>What gets me about this isn't the wrong edit. Wrong edits are normal; I make them too.</p>
<p>It's the <em>confidence</em>. A human who doesn't know where the logic lives asks, or hedges, or leaves a comment saying they weren't sure. An agent working from bad context does none of that. It produces something clean and plausible and completely misplaced, and hands it to you like it's finished. You can't debug uncertainty that was never expressed.</p>
<p>And the model wasn't the problem here. <strong>Retrieval was.</strong> The model answered the question it was given. Nobody gave it the right one.</p>
<p>In <a href="https://blog.ashishkrjha.dev/typescript-code-graph-compiler-api">Part 1</a> I built a code graph over a TypeScript codebase: 2,795 nodes, 17,985 edges, reduced to an 873-symbol search index. This article is about pointing that graph at an agent, and what happened when I actually measured it.</p>
<p>Including the case where it made things worse. We'll get there.</p>
<h2>Why "just give it the repo" doesn't work</h2>
<p>Take a real task: <em>add a minimum-order rule to checkout.</em></p>
<p>Search by name and you get <code>CheckoutPage.tsx</code>, <code>CheckoutButton.tsx</code>, <code>checkoutSlice.ts</code>, <code>checkout.css</code>, <code>checkout.test.ts</code>. Everything with the word in it, and almost nothing that matters.</p>
<p>What actually governs the behaviour looks like this:</p>
<pre><code class="language-text">CheckoutPage → calls → createOrder
createOrder  → calls → calculateOrderTotal
             → calls → validateOrder
validateOrder → used by → POST /orders, POST /order-preview
</code></pre>
<p>Not one of those names contains "checkout" past the first line.</p>
<p>The context you want isn't <em>files with a matching name</em>. It's the <strong>dependency neighbourhood around the behaviour you're changing</strong>, and those two sets overlap far less than feels reasonable.</p>
<p>This is the part I underestimated for a long time. I kept treating bad agent output as a model problem, because that's the framing everyone reaches for: better prompt, better model, more context. Meanwhile the agent was doing competent work on the wrong five files, over and over, and I was rewriting instructions at it.</p>
<p>This is what people have started calling context engineering, and it's where most of the leverage in agentic coding currently sits. Cursor, Claude Code, Aider's repo map and Sourcegraph all attack a version of it. A graph is just the version you can build yourself, tuned to conventions no generic tool knows about.</p>
<h2>Retrieve a neighbourhood, not a directory</h2>
<p>Start from a symbol and walk outward. One hop:</p>
<pre><code class="language-text">validateOrder
├── called by → createOrder
├── called by → previewOrder
├── calls → validateLineItems
└── calls → validateShippingRegion
</code></pre>
<p>Two hops:</p>
<pre><code class="language-text">createOrder  → used by → POST /orders
             → writes-state → checkout
previewOrder → used by → CheckoutSummary
</code></pre>
<p>Now assemble a packet: the target symbol, its callers, its dependencies, the routes affected, the state it touches, the nearby tests, and the architecture rules that apply.</p>
<p>Eight to fifteen files. Which is considerably more useful than 150 files chosen because they share a word, however impressive the token count looks.</p>
<img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/e9a3936f-c915-4319-92fc-0c867915f01e.svg" alt="04-retrieval-comparison" style="display:block;margin:0 auto" />

<p>The traversal itself is unglamorous:</p>
<pre><code class="language-ts">function expand(graph: Graph, start: string, maxDepth = 2) {
  const visited = new Set([start]);
  let frontier = [start];

  for (let depth = 0; depth &lt; maxDepth; depth++) {
    const next: string[] = [];
    for (const current of frontier) {
      for (const edge of neighbors(graph, current)) {
        const candidate = edge.from === current ? edge.to : edge.from;
        if (!visited.has(candidate)) {
          visited.add(candidate);
          next.push(candidate);
        }
      }
    }
    frontier = next;
  }

  return [...visited];
}
</code></pre>
<p>The next improvement isn't going deeper. It's being pickier about which edges you follow.</p>
<h2>Weight your edges</h2>
<p>For business logic, <code>calls</code> and <code>writes-state</code> matter enormously. Importing a CSS file or a shared <code>&lt;Button&gt;</code> matters approximately not at all. And yet an unweighted traversal treats them identically, which is how you end up with your design system in the context window.</p>
<pre><code class="language-ts">const edgeWeights = {
  calls: 10,
  "writes-state": 10,
  "publishes-event": 9,
  "handles-route": 9,
  "reads-state": 8,
  renders: 5,
  imports: 2,
};
</code></pre>
<p>Obvious when written down. Retrieval systems fail to encode obvious things with impressive regularity.</p>
<h2>Tell the agent what <em>not</em> to touch</h2>
<p>Good retrieval isn't only about surfacing code. It's about surfacing boundaries.</p>
<p>Say your layering is UI → service → adapter → vendor SDK, and the agent proposes this:</p>
<pre><code class="language-ts">// CheckoutPage.tsx
import paymentSdk from "payment-sdk";
</code></pre>
<p>A graph-aware check catches the new <code>component → vendor SDK</code> edge and rejects it before merge.</p>
<p>You could instead write "never import the SDK directly" in your instruction file and hope.</p>
<p>I've tried hoping. It works most of the time, which is somehow worse than failing outright. You stop checking, and then one Tuesday it doesn't, and the violation is already three commits deep. Prompts help. But an executable constraint has the notable advantage of not forgetting on a Tuesday.</p>
<pre><code class="language-js">// UI components cannot import repositories
const violations = graph.edges.filter(
  e =&gt; e.kind === "imports" &amp;&amp; isComponent(e.from) &amp;&amp; isRepository(e.to)
);
</code></pre>
<p>The cheapest rule to implement first: <strong>deprecated modules cannot gain new callers.</strong> Store a baseline count, fail if it grows. You may not get to delete the old module this quarter (you probably won't) but you can stop it spreading, and unlike most architecture rules it needs no classification logic whatsoever.</p>
<h2>Blast radius, before the edit</h2>
<p>An agent wants to change <code>normalizeCustomer</code>. The graph knows it has five direct callers, and that those callers hang off an HTTP route, a nightly import job, and two event consumers.</p>
<pre><code class="language-text">Target: normalizeCustomer

Direct callers:           5
Affected HTTP routes:     1
Affected background jobs: 2
Affected event consumers: 2
Nearby tests:            11

Risk indicators:
- high fan-in
- used by async worker
- crosses into the billing boundary
</code></pre>
<p>A crude score turns that into a ranking signal:</p>
<pre><code class="language-ts">risk =
  directCallers * 2 +
  affectedRoutes * 4 +
  backgroundJobs * 4 +
  externalApis * 5 +
  stateWrites * 3;
</code></pre>
<p>Please don't turn this into a sacred number that gates your CI. The question it answers is <em>which changes deserve extra care</em>, not <em>can I mathematically prove this line is dangerous</em>. Software has never once agreed to be that cooperative.</p>
<h2>Documentation is the other half</h2>
<p>Some things the compiler simply cannot know.</p>
<p>If <code>OrderPreviewService</code> deliberately uses a cached price snapshot, because recalculating would make previews change after the customer approved them, no amount of static analysis recovers that reasoning. But the graph knows <code>OrderPreviewService → calls → getPriceSnapshot</code>, so when a task touches either symbol, that decision record can be pulled into context automatically.</p>
<p>Clean division of labour: <strong>the graph knows what exists and what connects; the docs explain why the weird parts are deliberate.</strong></p>
<h3>Keep the root doc a router</h3>
<p>Your agent instruction file (<code>AGENTS.md</code>, <code>CLAUDE.md</code>, whatever your tool reads) should hold only what <em>isn't derivable from the code</em>, with a hard size limit. Mine is capped around 300 lines, which is about 6,200 tokens paid on every single session. When a section outgrows that, it's become a decision record.</p>
<p>Four things earn their place:</p>
<p><strong>What does NOT belong where.</strong> A two-column table per folder: what belongs, and what doesn't. The negative column is the one that does the work. Every architecture doc tells you where things go; almost none tell you where things must not go, and a helper in the wrong folder is one the next person will never find, which is where duplication comes from in the first place.</p>
<p><strong>A domain glossary.</strong> Business term → code term → API name. Without it, neither a new hire nor an agent can map a ticket onto a folder.</p>
<p><strong>Confusing pairs, written from bugs that actually happened.</strong> In my codebase three different things are called some variant of "event," and two similarly-named entities are genuinely distinct objects that must never be merged. That section exists because both have already cost someone an afternoon.</p>
<p><strong>Off-limits without discussion.</strong> Generated files, vendored code, anything external config might reference by name.</p>
<p>Don't start from a template. Start from your last five <em>"why is it like that?"</em> Slack threads and your last five review comments saying <em>"we already have this."</em> That's the content. It's already written; it's just scattered across conversations nobody can search.</p>
<h3>Decision records that end in "Do not"</h3>
<p>Not every decision deserves a record. The ones that do are the decisions a reasonable engineer will eventually try to <em>simplify</em>. Usually on a Friday, usually with good intentions.</p>
<p>So every ADR I write ends with a <strong>Do not</strong> section, phrased as the sentence that engineer would say to themselves:</p>
<pre><code class="language-md"># ADR: External API access stays behind adapters

## Context
The vendor SDK has unstable response shapes and inconsistent errors.

## Decision
Feature code calls typed adapter functions.

## Do not
Do not import the SDK directly inside a feature module,
even if your new feature only needs one endpoint.
</code></pre>
<p>That last section is the difference between a decision log and a guardrail. A normal ADR explains a choice to someone who reads it. A "Do not" line intercepts someone who was never going to read it, because it's the phrase they'll grep, or the phrase retrieval surfaces at the moment it matters.</p>
<p>Two rules keep this honest. <strong>ADRs are append-only.</strong> Supersede, never edit, so a record is either current or explicitly historical with no third state where it quietly disagrees with the code.</p>
<h3>And now the embarrassing part</h3>
<p>The second rule is that these documents rot, and a confidently wrong router is worse than none at all.</p>
<p>I can be specific about this, because when I re-ran my measurements I audited the docs against the code at the same time. Here's my own paperwork:</p>
<table>
<thead>
<tr>
<th>Document</th>
<th>Claimed</th>
<th>Actually</th>
</tr>
</thead>
<tbody><tr>
<td>Tooling reference</td>
<td>1,149 source files, 106 state slices</td>
<td>771 files, 45 slice folders</td>
</tr>
<tr>
<td>Readiness checklist</td>
<td>Thunks "excluded from the index", filed under <em>not done yet</em></td>
<td>145 thunks and 73 selectors indexed</td>
</tr>
<tr>
<td>Rebuild time, in two places</td>
<td>15–20 seconds</td>
<td>13.1 seconds</td>
</tr>
<tr>
<td>A decision record</td>
<td>Slice count off by roughly 5x</td>
<td>n/a</td>
</tr>
</tbody></table>
<p>Every one of those was written by someone careful. I know, because it was me. I'd written the negative-space table and the append-only rule in the same sitting, feeling quite good about myself.</p>
<p>Nothing in my process caught any of it. There was no moment where the docs announced they'd gone wrong. They just sat there, confident and slightly false, for months.</p>
<p>The second row is the one that stings. A "not done yet" list advertising a gap that was closed months ago will send the next person off to rebuild something that already works. That isn't documentation sitting there being harmlessly stale. That's documentation actively wasting someone's afternoon.</p>
<p>Tie doc review to convention changes rather than the calendar, and audit the docs whenever you regenerate the graph. The graph is the only thing in your repo positioned to catch your prose lying.</p>
<h3>Correct for the model's priors, too</h3>
<p>One more failure mode, running in the opposite direction.</p>
<p>The first review my instruction file got flagged that the model kept adding memoization everywhere. The reviewer's diagnosis: its training data skews toward older React, where you had to. Newer versions handle much of it automatically.</p>
<p>That isn't the model lacking knowledge of my codebase. It's the model having <em>too much</em> knowledge, of the wrong vintage, applied with total confidence.</p>
<p>So an instruction file has two jobs. It encodes what's true about your repository, and it corrects what the model assumes about your framework. The second kind is easy to skip because it doesn't feel like documentation. It feels like arguing with a very self-assured junior. Write it down anyway:</p>
<pre><code class="language-md">## Version-specific: override your priors

- React 19: do not add useMemo/useCallback defensively.
  The compiler handles most of this. Memoize only with
  a measured reason.
</code></pre>
<p>Both kinds go stale, in opposite directions. Your code drifts from your docs. The model's assumptions drift from your framework. The router file sits between them and is the only thing watching either.</p>
<h2>Diff the graph after the patch</h2>
<p>Before: <code>Feature → Service → Adapter → External API</code>. After: same chain, plus a shiny new <code>Feature → External API</code>.</p>
<p>It compiles. The tests pass. Nothing is red. And an architectural boundary just moved.</p>
<p>The graph delta catches it:</p>
<pre><code class="language-text">Graph delta

+ CheckoutPage → calls → validateMinimumOrder
+ validateMinimumOrder → reads-state → pricingRules
- CheckoutPage → imports → legacyValidation

No new cross-layer imports.
No new dependency cycles.
</code></pre>
<p>Easier to review than a 600-line diff you're scrolling through at 5pm hoping the architecture reveals itself.</p>
<p>The general principle: <strong>check effects, not just generated text.</strong></p>
<h2>The whole loop, assembled</h2>
<p>Put the retrieval half and the verification half together and you get something that looks less like "an AI writes code" and more like a pipeline with the model as one stage in it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/3c8e9c22-2bbe-4213-839a-84e193cd49ff.svg" alt="06-agent-loop" style="display:block;margin:0 auto" />

<p>Steps one to four decide what the model is allowed to see. Steps six to eight check what it did with that. The agent itself only ever occupies step five, which is a considerably smaller share of the system than the marketing around agents would have you believe.</p>
<p>That framing is useful when something goes wrong, because it gives you somewhere specific to look. Bad output means either the packet was wrong or the model was wrong, and those live in different stages with different fixes.</p>
<h2>So what does it actually save?</h2>
<p>Time to stop asserting and measure.</p>
<p>I took six real discovery questions from my own codebase and ran each two ways. Through the symbol index, and through the exploration you do without one. Orient in the tree, grep a guess, grep again because the first guess missed, open files to confirm.</p>
<p>Real commands, real output, three repetitions, median reported.</p>
<table>
<thead>
<tr>
<th>Question</th>
<th>Tool calls</th>
<th>Tool output (tokens)</th>
</tr>
</thead>
<tbody><tr>
<td>Is there a helper that runs a paginated API query?</td>
<td>1 / 4</td>
<td>1,000 / 3,488</td>
</tr>
<tr>
<td>Is there an existing loading spinner?</td>
<td>1 / 3</td>
<td>267 / 4,380</td>
</tr>
<tr>
<td>Where is the role flag derived, and is it authoritative?</td>
<td>2 / 3</td>
<td>603 / 4,690</td>
</tr>
<tr>
<td>Is there a date formatting helper already?</td>
<td>1 / 3</td>
<td>759 / 5,108</td>
</tr>
<tr>
<td>Is there something that chunks oversized query batches?</td>
<td>1 / 3</td>
<td>643 / 2,103</td>
</tr>
<tr>
<td>What shape does a new feature slice follow?</td>
<td>2 / 5</td>
<td>997 / 2,434</td>
</tr>
<tr>
<td><strong>Total</strong></td>
<td><strong>8 / 21</strong></td>
<td><strong>4,269 / 22,203</strong></td>
</tr>
</tbody></table>
<p>Cells read <em>with index / without</em>.</p>
<p><strong>81% less output for the model to read. 13 fewer tool calls.</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/fb9330df-aeb8-4207-8be5-e35bdd75ff55.svg" alt="05-benchmark" style="display:block;margin:0 auto" />

<p>The call count is what drives cost, because every call is a round trip that re-sends the whole accumulated conversation as input. Counting the final answer turn: 14 round trips against 27. Model those at current large-model pricing and the cost difference lands near 49%.</p>
<p>I swept the assumptions. Harness context from 4k to 80k tokens, output per turn from 200 to 4,000, latency from 3 to 20 seconds. It stays in a 48-51% band, because the result is driven by measured call counts rather than my guesses.</p>
<p><strong>Now the caveats, which matter more than the percentage.</strong></p>
<p>The without-index path is a <em>modelled</em> sequence, not an observed agent run. I wrote those commands based on what unaided search looks like here. A sharper agent might do the first task in two calls. A flailing one might take eight. The output volumes are real measurements of what those commands return. The baseline's shape is my judgement.</p>
<p>Token counts come from an estimator, not a token-counting endpoint. Call it ±10–15%. Applied identically to both sides, so the ratio holds even if absolutes drift.</p>
<p>And this prices <em>discovery only</em>. It doesn't price the thing the index mainly exists to prevent, which is an agent writing a second <code>formatDate</code> because it never found the first. That cost lands in review, or next sprint, or in a bug six months out. No single-session benchmark catches it.</p>
<p>Read 49% as a floor.</p>
<h2>And when it makes things worse</h2>
<p>Here's the number I suspect most posts like this quietly skip.</p>
<p>The instruction file loads every session whether anyone searches or not. 6,179 tokens, paid up front, every time. Against an average saving of about $0.076 per discovery task, it pays for itself <strong>within the first task of a session</strong>.</p>
<p>But the worst realistic case, with the instruction file loaded and the index never queried and the agent grepping anyway, comes out <strong>9.1% more expensive</strong> than having no toolchain at all.</p>
<p>That's the downside bound. One avoided duplicate helper repays it many times over, so I'll take that trade all day. But if your own benchmark doesn't contain a number like this, you haven't finished measuring. You've finished marketing.</p>
<p>You may also find plain lexical search handles most of your tasks fine. Good. Use the graph where structure genuinely helps. The goal isn't to justify the elaborate thing you built.</p>
<h2>Separate the retriever from the agent</h2>
<p>This distinction does more work than anything else here.</p>
<p>When an agent makes a bad change: was the model weak, or did retrieval never surface the critical dependency? Different failures, different fixes. Track them together and every failure becomes "improve the prompt," including the ones caused by the agent never seeing the file.</p>
<table>
<thead>
<tr>
<th>Task</th>
<th>Retrieval</th>
<th>Agent</th>
<th>Tests</th>
</tr>
</thead>
<tbody><tr>
<td>Tax rounding</td>
<td>Pass</td>
<td>Pass</td>
<td>Pass</td>
</tr>
<tr>
<td>Retry handling</td>
<td>Pass</td>
<td>Fail</td>
<td>Fail</td>
</tr>
<tr>
<td>Eligibility rule</td>
<td><strong>Fail</strong></td>
<td>Fail</td>
<td>Fail</td>
</tr>
</tbody></table>
<p>On row three the model failed because the retriever never surfaced the shared rule. No amount of prompt engineering fixes that, though I'm sure someone has tried for a week.</p>
<h2>Start with retrieval, not autonomy</h2>
<p>If I were introducing this somewhere new I wouldn't begin with an agent editing production code.</p>
<p>Start here: developer asks a question → system finds relevant symbols → system shows the neighbourhood → developer picks what to read. Then: agent proposes context → developer reviews → agent proposes a patch. Automate further only after you've measured retrieval quality.</p>
<p>You get useful tooling immediately, and it survives the model layer changing underneath you, which it will, roughly every four months. The graph describes your repository, not somebody's API.</p>
<h2>Quick answers</h2>
<p><strong>Is this just RAG for code?</strong> It's the retrieval half, with structure instead of embeddings. Chunk-and-embed finds text that <em>reads</em> similar. A graph finds code that's actually connected. Good systems use both.</p>
<p><strong>How is this different from a repo map?</strong> A repo map is usually a flat summary handed over up front. A graph is queried per task, so context scopes to the change instead of the codebase.</p>
<p><strong>Do I need this with Cursor or Claude Code?</strong> On a small codebase, probably not. Their retrieval is good. It starts paying off when your repo has conventions no generic tool knows, which is exactly what those framework-specific edges encode.</p>
<p><strong>Does this work outside TypeScript?</strong> The concepts do. The implementation leans on the TypeScript type checker for cross-file resolution; you'd need an equivalent.</p>
<h2>Building the graph itself</h2>
<p>This article assumed the graph exists. For the implementation, covering <code>Program</code>, <code>TypeChecker</code>, symbol resolution, framework-specific edges and intent search, start with Part 1:</p>
<p><a href="https://blog.ashishkrjha.dev/build-a-typescript-code-graph-with-the-compiler-api"><strong>Build a TypeScript Code Graph with the Compiler API</strong></a></p>
<h2>The takeaway</h2>
<p>The best use of a code graph in AI-assisted development isn't a prettier architecture diagram. It's <strong>controlling context</strong>.</p>
<p>What should the agent read. What should it not touch. What else might this change break. Which tests matter. Did this patch just move a boundary.</p>
<p>That's a retrieval and verification layer around the agent, and a far better foundation than "AI that can read the repo," which is not a strategy so much as a hope with a large context window.</p>
<p>The part I didn't expect: almost none of this work was about AI. Naming things findably, writing down which decisions are load-bearing, admitting where the docs had drifted. That's the same work that makes a codebase survivable for the humans in it. The agent just made the cost of skipping it visible, and put a number on it.</p>
<p>Which, honestly, is more than any of my previous attempts to care about documentation ever managed.</p>
<hr />
<p><em>I'm Ashish Kr Jha, a software engineer. I build things in production and then have to live with them, which is the part that actually teaches you something. More at</em> <a href="https://ashishkrjha.dev"><em>ashishkrjha.dev</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[Build a TypeScript Code Graph with the Compiler API]]></title><description><![CDATA[Have you ever written a helper function, opened a pull request, and had someone comment "we already have this"?
I have. More than once, in the same codebase. And once, on a helper I had written myself]]></description><link>https://blog.ashishkrjha.dev/build-a-typescript-code-graph-with-the-compiler-api</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/build-a-typescript-code-graph-with-the-compiler-api</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Developer Tools]]></category><category><![CDATA[#ai-tools]]></category><category><![CDATA[ai agents]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Wed, 19 Aug 2026 07:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/8dadc59f-7b48-422f-b4e7-2f40d3ec1845.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever written a helper function, opened a pull request, and had someone comment <em>"we already have this"</em>?</p>
<p>I have. More than once, in the same codebase. And once, on a helper I had written myself eight months earlier, under a name I no longer remembered choosing. That's the one that stayed with me.</p>
<p>There's a very particular flavour of embarrassment in that. Not "I didn't know the codebase," which is forgivable. More like finding out you've been introduced to yourself at a party.</p>
<p>And the genuinely infuriating part is that searching wouldn't have saved me. The function was there. It was called something I'd never have guessed in a hundred tries.</p>
<p>That's the problem this article is about. Not "how do I search my code" but something harder: <strong>how do I ask my codebase a question and get a real answer?</strong></p>
<p>Three questions in particular:</p>
<ol>
<li><p>Does this already exist?</p>
</li>
<li><p>Where does this code belong?</p>
</li>
<li><p>What will I break if I change it?</p>
</li>
</ol>
<p>Grep can't answer any of them properly. But the TypeScript compiler can, and it's already sitting in your <code>node_modules</code>.</p>
<h2>First, why grep runs out of road</h2>
<p>Say you've got this import:</p>
<pre><code class="language-ts">import { calculateOrderTotal as getCartValue } from "@/pricing";

const total = getCartValue(cart);
</code></pre>
<p>Now search for <code>calculateOrderTotal</code>. This file won't come up. The function is here, it's being called right now, but it's wearing a different name.</p>
<p>And even without the alias, <code>@/pricing</code> is almost certainly a barrel file re-exporting from somewhere else. Barrel files are wonderful for writing imports and actively hostile to everything that happens afterwards. The real declaration is two hops away from anything you typed.</p>
<img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/8ce7938a-2116-42fa-9ef1-2a7ab05e8836.svg" alt="alias-resolution.svg" style="display:block;margin:0 auto" />

<p>Grep works on text. The TypeScript type checker works on <em>meaning</em>. Ask it what <code>getCartValue</code> refers to and it walks back through the alias, through the barrel, and hands you the actual declaration.</p>
<p>That difference is the whole article. Text search tells you a string appears in twelve files. The compiler tells you which symbols call which function. Only the second one is something you can safely refactor.</p>
<h2>Why I actually built this</h2>
<p>For a while I treated this as a personal failing. Learn the codebase better. Read more of it. Keep a list.</p>
<p>Then I watched a new engineer join and spend most of their first fortnight asking questions I couldn't answer cleanly either. <em>Where does this belong, does something like this exist, what happens if I change this.</em> I'd been there two years and I was guessing. Confidently, and often correctly, but guessing.</p>
<p>That's when it stopped feeling like a memory problem.</p>
<p>There's a threshold a codebase crosses where nobody holds it in their head anymore. Not the tech lead, not the person who wrote the first commit. Past that line you start making changes with a quiet undertone of <em>I think this is fine</em>, and you ship it, and mostly it is fine, and the times it isn't you find out from someone else's bug report.</p>
<p>I didn't want a better memory. I wanted to stop guessing.</p>
<h2>What this looks like when it works</h2>
<p>Before we build anything, here's the payoff:</p>
<pre><code class="language-bash">$ node find-symbol.mjs "convert date to utc"

1. parseIsoTimestamp        dates/parseIsoTimestamp.ts
2. normalizeServerDate      dates/normalizeServerDate.ts
3. formatUtcDate            display/formatUtcDate.ts
</code></pre>
<p>I typed what I wanted. It found things named nothing like it, in about a third of a second, and I have never once had to remember what any of them were called.</p>
<p>Some numbers from the codebase I built it on, so you know the scale we're talking about:</p>
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>Source files</td>
<td>771</td>
</tr>
<tr>
<td>Graph nodes</td>
<td>2,795</td>
</tr>
<tr>
<td>Graph edges</td>
<td>17,985</td>
</tr>
<tr>
<td>Searchable symbols</td>
<td>873</td>
</tr>
<tr>
<td>Rebuild time</td>
<td>13.1 s</td>
</tr>
<tr>
<td>New dependencies</td>
<td>0</td>
</tr>
</tbody></table>
<p>The domain is anonymized and the examples below are generic, but every number is real.</p>
<h2>Step 1: Ask TypeScript for a Program</h2>
<p>A <code>Program</code> is TypeScript's view of your whole project: every file, resolved with the same config your app builds with.</p>
<pre><code class="language-ts">import ts from "typescript";

const configPath = ts.findConfigFile("./", ts.sys.fileExists, "tsconfig.json");
if (!configPath) throw new Error("No tsconfig.json found");

const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, "./");

const program = ts.createProgram({
  rootNames: parsed.fileNames,
  options: parsed.options,
});

const checker = program.getTypeChecker();
</code></pre>
<p>Using the project's own <code>tsconfig.json</code> matters here. Your path aliases and <code>allowJs</code> settings need to match what actually compiles, or half your imports won't resolve.</p>
<p>Then walk the files:</p>
<pre><code class="language-ts">for (const sourceFile of program.getSourceFiles()) {
  if (sourceFile.isDeclarationFile) continue;
  if (sourceFile.fileName.includes("node_modules")) continue;
  visit(sourceFile);
}

function visit(node: ts.Node) {
  if (ts.isFunctionDeclaration(node) &amp;&amp; node.name) {
    addNode({
      id: `function:${node.name.text}`,
      kind: "function",
      name: node.name.text,
      file: node.getSourceFile().fileName,
    });
  }
  ts.forEachChild(node, visit);
}
</code></pre>
<p>You now have a list of every function in your project. Useful, but it's still just a list.</p>
<p><strong>Tip:</strong> keep <a href="https://ts-ast-viewer.com/">TypeScript AST Viewer</a> open in a tab while you write this. Paste in a snippet, see exactly what node types come back. It'll save you an hour of guessing.</p>
<h2>Step 2: Resolve symbols, not strings</h2>
<p>Here's where it gets interesting. When you hit a call expression, ask the checker what's being called:</p>
<pre><code class="language-ts">if (ts.isCallExpression(node)) {
  const symbol = checker.getSymbolAtLocation(node.expression);
}
</code></pre>
<p>But if that call came through an import, you've got an <em>alias</em>. A pointer, not the thing itself. So unwrap it:</p>
<pre><code class="language-ts">function resolveSymbol(symbol: ts.Symbol | undefined) {
  if (!symbol) return undefined;
  if (symbol.flags &amp; ts.SymbolFlags.Alias) {
    return checker.getAliasedSymbol(symbol);
  }
  return symbol;
}
</code></pre>
<p>That flag check isn't optional, and I found that out the way everyone does. <code>getAliasedSymbol</code> <strong>throws</strong> if you hand it something that isn't an alias. Not returns null, not returns the original. Throws. In a codebase with barrel files you'll hit both cases inside the same file, so guard it, or spend twenty minutes wondering why your build script dies on file three every single time.</p>
<p>Now record the relationship:</p>
<pre><code class="language-ts">const resolved = resolveSymbol(symbol);
const declaration = resolved?.declarations?.[0];

if (declaration) {
  addEdge({
    from: currentSymbolId,
    to: symbolId(resolved, declaration),
    kind: "calls",
  });
}
</code></pre>
<p>You're now storing a link between two real declarations instead of two strings that happen to match. Everything else builds on this.</p>
<h2>Step 3: Keep the data model boring</h2>
<pre><code class="language-ts">type NodeKind = "file" | "function" | "component" | "hook" | "state" | "package";

type EdgeKind =
  | "imports" | "calls" | "renders"
  | "uses-hook" | "reads-state" | "writes-state";

interface GraphNode {
  id: string;
  kind: NodeKind;
  name: string;
  file?: string;
}

interface GraphEdge {
  from: string;
  to: string;
  kind: EdgeKind;
}
</code></pre>
<p>Write it out as <code>{ "nodes": [], "edges": [] }</code> and stop. I know "knowledge graph" sounds like it deserves something fancier, but plain JSON has one enormous advantage: it exists today, and you can query it with <code>Array.prototype.filter</code>.</p>
<p>Mine comes out at 5.5 MB. Gitignore it. We'll commit something much smaller in a bit.</p>
<h2>Step 4: Teach it about <em>your</em> codebase</h2>
<p>Everything so far is generic. If you stop here you've built a dependency graph, which <a href="https://github.com/sverweij/dependency-cruiser">dependency-cruiser</a> and <a href="https://github.com/pahen/madge">Madge</a> already give you for free, and which you've just spent a weekend reinventing. Don't stop here.</p>
<p>The value comes from two functions you write yourself.</p>
<p><code>classifyFile(path)</code> maps your folder conventions onto node kinds. <code>src/hooks/</code> means hook, <code>src/redux/slices/api/</code> means API client. Get this wrong and every query afterwards returns noise, because "show me the components that read this state" depends on the graph knowing what a component is.</p>
<p><code>detectFactoryKind(initializer)</code> catches the things your framework creates through function calls. The AST just sees a <code>const</code>, so without help your graph is full of opaque constants where the interesting nodes should be. I detect <code>createAsyncThunk</code>, <code>createSelector</code> and <code>createSlice</code>. Yours might be <code>defineStore</code>, <code>createMachine</code>, or a DI registration.</p>
<p>Both are short, forty lines or so. They're also the difference between a generic import graph and a map of your system.</p>
<p>Now you can add edges nobody else could give you. When the walker sees this:</p>
<pre><code class="language-ts">const cart = useAppSelector(state =&gt; state.cart);
</code></pre>
<p>it emits <code>CheckoutPage → reads-state → cart</code>. And when it sees a thunk:</p>
<pre><code class="language-ts">export const refreshCart = createAsyncThunk("cart/refresh", async () =&gt; { ... });
</code></pre>
<p>it emits <code>refreshCart → writes-state → cart</code>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/f0692146-d90c-4478-80b5-6dd3c310bd05.svg" alt="graph-model.svg" style="display:block;margin:0 auto" />

<p>Something I didn't expect. Those two state detectors produced 320 edges out of nearly 18,000, under 2% of the graph. They're also the ones people query. The compiler gives you thousands of edges for free; the handful you write yourself carry most of the weight.</p>
<h2>The bug it found in its first week</h2>
<p>I want to tell you about this one, because it's the moment the tool proved itself and it wasn't a feature.</p>
<p>My <code>reads-state</code> detector keys off the state shape, <code>state.invoiceTemplates</code>, plural. My <code>writes-state</code> detector keys off the name passed to <code>createSlice({ name })</code>, which turned out to be <code>invoiceTemplate</code>, singular.</p>
<p>Same slice. Two different names depending on which direction you asked.</p>
<p>My first reaction was that my detector was broken. My second, after ten minutes of checking, was the slightly cold realisation that it wasn't. The codebase had been carrying that inconsistency for years, and every one of us had walked past it.</p>
<p>Nobody had spotted it because no single file shows you both sides. You'd have to open the slice definition and a component that consumes it, at the same time, while specifically hunting for a mismatch that you have no reason to suspect exists. Nobody does that. Nobody has ever done that.</p>
<p>Expect a few of these. <strong>A graph that surfaces your naming inconsistencies is working correctly, even when the first thing it tells you is embarrassing.</strong></p>
<h2>Step 5: Make symbols searchable</h2>
<p>A node gets far more useful once it carries more than a name:</p>
<pre><code class="language-json">{
  "id": "function:parseIsoTimestamp",
  "name": "parseIsoTimestamp",
  "kind": "function",
  "module": "dates",
  "summary": "Convert an ISO timestamp into UTC epoch milliseconds",
  "signature": "(value: string) =&gt; number"
}
</code></pre>
<p>The checker infers most of that for free, which is the nice part. You get a decent search index without asking anyone to maintain a catalog by hand.</p>
<p>One honest number before you get excited: in my index, 91% of symbols have a type signature and <strong>24% have a written summary</strong>.</p>
<p>Signatures come from the compiler. Prose comes from humans. You can guess which one shows up reliably.</p>
<p>So if you want better search results cheaply, don't set out to document everything. Add doc comments to the shared helpers only, the forty things people keep re-implementing. That's where the return is.</p>
<h2>Step 6: Search by intent</h2>
<p>Now the search itself. The key idea is tokenization: <code>toEpochMs</code> and <code>to_epoch_ms</code> both break down into <code>["to", "epoch", "ms"]</code>. That's what lets someone search for a <em>thing they want</em> and find a function named nothing like it.</p>
<p>This is the case grep structurally cannot handle. <code>normalize_date</code> and <code>clean_timestamp</code> share zero characters, so no regex will ever connect them, but both might be exactly what you meant.</p>
<p>The scorer is a weighted sum, and I'd encourage you to keep yours equally dull:</p>
<pre><code class="language-ts">function scoreSymbol(symbol: SearchableSymbol, query: string) {
  const q = normalize(query);
  const name = normalize(symbol.name);
  const summary = normalize(symbol.summary ?? "");

  let score = 0;

  if (name === q) score += 1000;        // exact name
  if (name.includes(q)) score += 60;    // name substring
  if (summary.includes(q)) score += 25; // summary substring

  const queryTokens = tokenize(q);
  const nameTokens = new Set(tokenize(name));
  const summaryTokens = new Set(tokenize(summary));

  for (const token of queryTokens) {
    if (nameTokens.has(token)) score += 20;
    if (summaryTokens.has(token)) score += 6;
  }

  return score;
}
</code></pre>
<p>Module match adds 15, path match 10. The exact numbers barely matter. You'll tune them against your own repo within a day of using it.</p>
<p>Wrap it in a CLI with no dependencies:</p>
<pre><code class="language-bash">node find-symbol.mjs "convert date to utc"
node find-symbol.mjs --kind component "loading spinner"
node find-symbol.mjs --module src/redux "thunk"
</code></pre>
<h2>The part that makes it cheap</h2>
<p>Here's the bit I like.</p>
<p>That 5.5 MB graph reduces down to a 717 KB index of 873 symbols. Run a token counter over it and it's roughly <strong>248,000 tokens</strong> of structural information about the codebase. The full graph is closer to 1.9 million.</p>
<p>None of it is ever loaded into a context window. Not once.</p>
<p>A search reads it from disk, ranks it in about 300 milliseconds, and prints ten lines.</p>
<img src="https://cdn.hashnode.com/uploads/covers/62db053c38759e6b49828665/75968dc4-65d6-46e1-975b-6141ef2710ad.svg" alt="index-compression.svg" style="display:block;margin:0 auto" />

<p>That ratio, two million tokens on disk and ten lines in the answer, is the entire argument for building structure instead of stuffing more files into a prompt. It's also why this works fine for humans who don't have a context window at all.</p>
<p>Commit the index, gitignore the graph. And pretty-print it rather than minifying. It changes on every edit and turns up in most diffs, so a reviewer is going to see it. A readable diff is the difference between "fine, whatever" and "can we please delete this thing." If merge conflicts get annoying, a <code>merge=union</code> gitattribute helps.</p>
<h2>Do you need embeddings for this?</h2>
<p>Not to start. Embedding search does help when the query and the symbol share no vocabulary at all, and that case is real.</p>
<p>But a lexical scorer is fast, local, explainable, free to run, and tunable in an afternoon. No vector database, no model dependency, no API key, no monthly bill for a service that indexes 873 functions.</p>
<p>Add embeddings later, once you've collected actual searches where the ranking failed. Otherwise you're solving a problem you haven't met yet, which is a considerably more expensive hobby than it sounds.</p>
<p>Same answer for graph databases. My entire query surface is <code>graph.edges.filter(...)</code> run through <code>node -e</code>. Reach for Neo4j when you need multi-repo traversal or interactive exploration, not because a diagram had arrows in it.</p>
<h2>Keeping it honest</h2>
<p>An index that was accurate three months ago is a historical document. Regenerate it in one of these places, best first:</p>
<ol>
<li><p><strong>Editor or agent post-edit hook.</strong> Freshest, zero ceremony, but only covers people using that tool</p>
</li>
<li><p><strong>Pre-commit.</strong> This is the one that keeps it correct for the whole team</p>
</li>
<li><p><strong>Manual, before searching.</strong> Costs 13 seconds</p>
</li>
<li><p><strong>CI on merge.</strong> Fail if regenerating produces a diff</p>
</li>
</ol>
<p>Whatever you do, don't put regeneration on a sprint cadence. It goes stale <em>during</em> the sprint, which is precisely when the duplicates get written. You'd be building a tool that is reliably most wrong at the exact moment anyone needs it.</p>
<p>My post-edit hook is 25 lines, and the most important line in it is this:</p>
<pre><code class="language-js">} catch {
  // Never disrupt the workflow. Swallow errors silently.
}
</code></pre>
<p>A background hook that can fail loudly will be switched off within a week, by you, irritably, mid-task, the third time it interrupts something. It either works invisibly or does nothing at all. Both outcomes are survivable. Popping up in someone's edit loop is not.</p>
<h2>Where this doesn't help</h2>
<p>Worth being upfront. The graph misses runtime dependency injection, string-based event names, dynamic imports, reflection, database relationships and external config.</p>
<p>The biggest gap is simpler: <strong>it only sees TypeScript.</strong> SQL, Python, templates, config files: all invisible, along with any coupling that runs through them. If a chunk of your logic lives in stored procedures, the graph is describing half your system while looking complete.</p>
<p>Treat it as a useful model, not an oracle.</p>
<h2>Start smaller than this</h2>
<p>You don't need everything above to get value. Here's the version that fits in a day:</p>
<ol>
<li><p>Build a <code>Program</code></p>
</li>
<li><p>Index files and exported symbols</p>
</li>
<li><p>Resolve <code>imports</code> and <code>calls</code></p>
</li>
<li><p>Write <code>classifyFile</code> for your folders</p>
</li>
<li><p>Add <strong>one</strong> framework-specific edge, whichever coupling your team keeps asking about</p>
</li>
<li><p>Save as JSON, gitignore it, commit a reduced index</p>
</li>
<li><p>Add one command people run before writing shared code</p>
</li>
</ol>
<p>Steps 1–4 are an afternoon. The rest is another one. On a 771-file tree the whole rebuild takes 13 seconds, so the loop while you're tuning detectors is quick.</p>
<p>Then watch what happens. Do people find existing helpers? Are fewer near-duplicate utilities landing? Which searches return junk?</p>
<p>The graph is only infrastructure. Its value comes entirely from the questions people actually ask it.</p>
<p>What I got out of it wasn't really the search command, in the end. It was that the codebase stopped feeling like something I was negotiating with. Changes I'd have approached carefully, I could now approach quickly, because I could see what was on the other side of them.</p>
<p>That's a small thing to say and a large thing to have.</p>
<h2>Quick answers</h2>
<p><strong>Do I need a graph database?</strong> No. JSON and array filters go a long way.</p>
<p><strong>How long does the build take?</strong> 13.1 seconds on 771 files. Fine on a save hook, too slow per keystroke.</p>
<p><strong>Does this work for plain JavaScript?</strong> Partly. <code>allowJs</code> pulls <code>.js</code> files in, but without annotations the symbol resolution is much weaker.</p>
<p><strong>Is this just an AST?</strong> No. An AST gives you syntax inside one file. The type checker resolves meaning <em>across</em> files, working out which declaration an identifier points at. That's the part that matters.</p>
<p><strong>Should I use</strong> <a href="https://ts-morph.com/"><strong>ts-morph</strong></a> <strong>instead?</strong> If you're writing codemods, yes, it's a much nicer API. I went with the raw Compiler API because the only import is <code>typescript</code>, which the project already had, so the script copies into another repo with no install step. That's the whole trade: a few hours of extra plumbing for zero new dependencies.</p>
<h2>Next: handing this to an AI agent</h2>
<p>Once your codebase is nodes and edges, search is only the first thing you can do with it. The same graph can decide what an agent should read before editing a function, which routes a refactor might touch, and whether a change just crossed an architecture boundary.</p>
<p>I measured that, including the case where it costs <em>more</em> than doing nothing:</p>
<p><a href="https://blog.ashishkrjha.dev/code-graphs-for-ai-coding-agents-better-repository-context-and-safer-refactoring"><strong>Code Graphs for AI Coding Agents: Better Repository Context and Safer Refactoring</strong></a></p>
<p><em>I'm Ashish Kr Jha, a software engineer. I build things in production and then have to live with them, which is the part that actually teaches you something. More at</em> <a href="https://ashishkrjha.dev"><em>ashishkrjha.dev</em></a><em>.</em></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Functions: A detailed Guide]]></title><description><![CDATA[Javascript is a programming language and it is highly dependent on functions like many other languages to make code more modular and concise. In functional Programming functions are pure Functions, which means if the input is not changed the output o...]]></description><link>https://blog.ashishkrjha.dev/javascript-functions-a-detailed-guide</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/javascript-functions-a-detailed-guide</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[js functions]]></category><category><![CDATA[IIFE]]></category><category><![CDATA[HOF]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Fri, 20 Jan 2023 16:36:02 GMT</pubDate><content:encoded><![CDATA[<p>Javascript is a programming language and it is highly dependent on functions like many other languages to make code more modular and concise. In functional Programming functions are pure Functions, which means if the input is not changed the output of a function will remain the same.</p>
<h3 id="heading-simple-types-of-function">Simple Types of Function</h3>
<p>Some basic types of functions are :</p>
<ul>
<li>Function Declaration: This is the most common type of function in JavaScript. It is defined using the "function" keyword, followed by the function name, a set of parentheses, and a block of code within curly braces. Function declarations are hoisted, which means they are available for use throughout the entire script, before or after they are defined.</li>
</ul>
<pre><code class="lang-javascript">Copy codefunction greet() {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
}
greet(); <span class="hljs-comment">// "Hello World!"</span>
</code></pre>
<ul>
<li>Function Expression: A function expression is a function that is assigned to a variable. It is defined using the "var" keyword, followed by the variable name, the "=" operator, the "function" keyword, and the function definition. Function expressions are not hoisted, which means they can only be called after they are defined.</li>
</ul>
<pre><code class="lang-javascript">Copy codevar greet = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
};
greet(); <span class="hljs-comment">// "Hello World!"</span>
</code></pre>
<ul>
<li>Arrow Function: Arrow functions, also known as "fat arrow" functions, are a more concise way of defining functions in JavaScript. They are defined using the "=&gt;" operator, and do not have their own "this" keyword.</li>
</ul>
<pre><code class="lang-javascript">Copy codelet greet = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
};
greet(); <span class="hljs-comment">// "Hello World!"</span>
</code></pre>
<ul>
<li>Constructor Functions: These are special functions that are used to create and initialize new objects. They are defined using the "function" keyword, followed by a capitalized function name. They are called using the "new" keyword.</li>
</ul>
<pre><code class="lang-javascript">Copy codefunction Person(name) {
  <span class="hljs-built_in">this</span>.name = name;
}
<span class="hljs-keyword">let</span> john = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"John"</span>);
<span class="hljs-built_in">console</span>.log(john.name); <span class="hljs-comment">// "John"</span>
</code></pre>
<ul>
<li>Closure Function: Closures are functions that have access to the scope of their parent function, even after the parent function has returned. Closures are created by returning a function from within another function.</li>
</ul>
<pre><code class="lang-javascript">Copy codefunction outerFunction() {
  <span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>;
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(x);
  }
}
<span class="hljs-keyword">let</span> closureFunction = outerFunction();
closureFunction(); <span class="hljs-comment">// 10</span>
</code></pre>
<h3 id="heading-higher-order-function">Higher Order Function</h3>
<p>A higher-order function is a function that takes one or more functions as arguments or returns a function as its result.</p>
<p>In JavaScript, a higher-order function is a function that:</p>
<ol>
<li>Accepts one or more functions as arguments: A higher-order function can take one or more functions as arguments and use them within its own function body. For example, a higher-order function that takes two functions and returns the result of one of them based on a condition:</li>
</ol>
<pre><code class="lang-javascript">Copy codefunction conditionallyApply(func1, func2, condition) {
  <span class="hljs-keyword">if</span> (condition) {
    <span class="hljs-keyword">return</span> func1();
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> func2();
  }
}

<span class="hljs-keyword">let</span> func1 = <span class="hljs-function">() =&gt;</span> { <span class="hljs-keyword">return</span> <span class="hljs-string">'first function'</span> };
<span class="hljs-keyword">let</span> func2 = <span class="hljs-function">() =&gt;</span> { <span class="hljs-keyword">return</span> <span class="hljs-string">'second function'</span>};
<span class="hljs-built_in">console</span>.log(conditionallyApply(func1, func2, <span class="hljs-literal">true</span>)) <span class="hljs-comment">// 'first function'</span>
</code></pre>
<p>Higher-order functions can be used to create more abstract and reusable code. They are particularly useful in functional programming, where they are used to create functional primitives that can be combined to form more complex operations.</p>
<p>In summary, a higher-order function is a function that takes one or more functions as arguments or returns a function as its result. This allows for more abstract and reusable code to be written, making it a powerful tool in functional programming.</p>
<h3 id="heading-immediately-invoked-function-expression">Immediately Invoked Function Expression</h3>
<p>An Immediately Invoked Function Expression (IIFE) is a function that is defined and immediately executed as soon as it is defined. It is also known as a Self-Executing Anonymous Function (SEAF).</p>
<p>An IIFE is defined using a function expression and is immediately invoked by adding parentheses after the function expression. The function expression is typically anonymous and does not have a function name.</p>
<p>The general syntax for an IIFE is:</p>
<pre><code class="lang-javascript">Copy code(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// function code here</span>
})();
</code></pre>
<p>IIFEs are commonly used in JavaScript to create a new scope so that variables and functions defined within the IIFE are not visible outside of it. This can be useful for isolating variables and functions that are only needed within a specific part of the code.</p>
<p>IIFEs can also be used to pass in variables from the parent scope as arguments, which can then be used within the IIFE:</p>
<pre><code class="lang-javascript">Copy codelet message = <span class="hljs-string">"Hello"</span>;
(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">msg</span>) </span>{
  <span class="hljs-built_in">console</span>.log(msg); <span class="hljs-comment">// "Hello"</span>
})(message);
</code></pre>
<p>In summary, an IIFE (Immediately Invoked Function Expression) is a function that is defined and immediately executed as soon as it is defined. It is typically anonymous and does not have a function name. IIFEs are commonly used in JavaScript to create a new scope and to isolate variables and functions that are only needed within a specific part of the code.</p>
]]></content:encoded></item><item><title><![CDATA[The flow of Code Execution in Javascript]]></title><description><![CDATA[Javascript is a language designed for the Web, Everything that happens in it, happens in an Execution Context. If a program runs in javascript an execution context is created. Everytime an execution context is created it is created in two phases.
Cre...]]></description><link>https://blog.ashishkrjha.dev/the-flow-of-code-execution-in-javascript</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/the-flow-of-code-execution-in-javascript</guid><category><![CDATA[call stack]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Execution Context]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Fri, 20 Jan 2023 16:21:11 GMT</pubDate><content:encoded><![CDATA[<p>Javascript is a language designed for the Web, Everything that happens in it, happens in an <strong>Execution Context.</strong> If a program runs in javascript an execution context is created. Everytime an execution context is created it is created in two phases.</p>
<h3 id="heading-creation-phase-or-memory-creation">Creation Phase or Memory Creation</h3>
<p>When Memory creation occurs, javascript allocates the memory to all variables and functions present in the program. The function calls and references are stored for later use and the variables are stored with a value of undefined at the start.</p>
<p>So when this phase ends, all variables have been scanned and made undefined for and functions are kept.</p>
<h3 id="heading-code-execution-phase">Code Execution Phase</h3>
<p>In this phase the main execution takes place and the javascript runs the code line by line. When a new function is invoked a new execution context is created within the Global Execution context</p>
<p>These two phases are repeated until the call stack is empty.</p>
<h3 id="heading-what-is-a-call-stack">What is a Call Stack?</h3>
<p>Imagine a pile of books, a very tall pile of heavy books. If you try to get something at the bottom it will be very difficult and you might end up crashing the tower of those heavy books. So what do you do? You take the book on top and remove it and keep doing this until you reach your desired book. The same thing is happening in the call stack. The term <code>LIFO</code> stands for <code>Last In First Out</code>, which simply means the book <em>you kept last</em> on the top of the pile needs to <em>go out first</em></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">A</span>(<span class="hljs-params"></span>)</span>{
    B()
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am Function A`</span>)
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">B</span>(<span class="hljs-params"></span>)</span>{
    C()
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am Function B`</span>)
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">C</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am function C`</span>)
}
A()
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662890602204/o9C7XvhM1.png?auto=compress,format&amp;format=webp" alt="image.png" /></p>
<p>Now in the above example you can see the <code>function C</code> ran first then <code>function B</code> and then finally <code>function A</code>. Image below explains this further.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662889875083/isJxfxyew.png?auto=compress,format&amp;format=webp" alt="2.png" /></p>
<p>The blocks in the above image are functions that were pushed into the call stack.</p>
<ul>
<li><p>First the program was scanned and it saw only <code>function A</code> is being called so it went to <code>Function A</code></p>
</li>
<li><p>In <code>Function A</code> it saw the call for <code>Function B</code> before the <code>console.log</code> could execute so it went to <code>Function B</code> and added it in the call stack, and from there to <code>Function C</code> and added it to the call stack.</p>
</li>
<li><p>Entire functions are loaded and stacked on top on one another and so we execute the one at the top, In this case its <code>Function C</code>.</p>
</li>
<li><p>After the execution of <code>Function C</code>, the next function in the call stack was <code>Function B</code> so it went ahead and executed the <code>console.log</code> there.</p>
</li>
<li><p>And finally, it executed the last function remaining in the call stack which emptied the call stack.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Javascript And its Object]]></title><description><![CDATA[JavaScript objects are a fundamental concept in the language and are used to store and organize data. They are similar to real-world objects in that they have properties and methods that can be used to manipulate and access their data. In this articl...]]></description><link>https://blog.ashishkrjha.dev/javascript-and-its-object</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/javascript-and-its-object</guid><category><![CDATA[js]]></category><category><![CDATA[javascript objects]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Fri, 20 Jan 2023 16:02:37 GMT</pubDate><content:encoded><![CDATA[<p>JavaScript objects are a fundamental concept in the language and are used to store and organize data. They are similar to real-world objects in that they have properties and methods that can be used to manipulate and access their data. In this article, we will discuss the basics of JavaScript objects, how to create and access them, and the different methods available for working with objects.</p>
<p>Apart from that Javascript Objects are very important as most API fetch calls return something similar and if we don't know how to work with Javascript Objects. Our life as developers will become very hard very soon.</p>
<h3 id="heading-creating-objects">Creating Objects</h3>
<p>JavaScript objects can be created using object literals, which are enclosed in curly braces {}. Properties and methods are defined using key-value pairs, with the key being a string and the value being any valid JavaScript data type. Here's an example of an object literal that represents a car:</p>
<pre><code class="lang-javascript">Copy codelet car = {
  <span class="hljs-attr">make</span>: <span class="hljs-string">"Toyota"</span>,
  <span class="hljs-attr">model</span>: <span class="hljs-string">"Camry"</span>,
  <span class="hljs-attr">year</span>: <span class="hljs-number">2020</span>,
  <span class="hljs-attr">getInfo</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.year}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.make}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span>`</span>;
  }
};
</code></pre>
<p>This object has properties <code>make</code>, <code>model</code>, and <code>year</code> and a method <code>getInfo</code> which returns a string representation of the car.</p>
<p>Object literals are a great way to create small, one-off objects, but they can become unwieldy when you need to create multiple objects with the same structure. In such cases, you can use constructors to create objects. A constructor is a function that is used to create new objects. It is defined using the <code>function</code> keyword, and it can take any number of arguments. Here's an example of a constructor that creates car objects:</p>
<pre><code class="lang-javascript">Copy codefunction Car(make, model, year) {
  <span class="hljs-built_in">this</span>.make = make;
  <span class="hljs-built_in">this</span>.model = model;
  <span class="hljs-built_in">this</span>.year = year;
  <span class="hljs-built_in">this</span>.getInfo = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.year}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.make}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span>`</span>;
  }
}
<span class="hljs-keyword">let</span> car1 = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">"Toyota"</span>, <span class="hljs-string">"Camry"</span>, <span class="hljs-number">2020</span>);
<span class="hljs-keyword">let</span> car2 = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">"Honda"</span>, <span class="hljs-string">"Civic"</span>, <span class="hljs-number">2021</span>);
</code></pre>
<p>In this example, the <code>Car</code> the constructor creates new car objects and assigns properties to them based on the arguments passed to the constructor.</p>
<h3 id="heading-accessing-properties-and-methods">Accessing Properties and Methods</h3>
<p>Properties and methods of an object can be accessed using the dot notation or the bracket notation. The dot notation is used to access properties and methods directly, while the bracket notation can be used to access properties using a variable or an expression. Here's an example of how to access the properties and method of the car object:</p>
<pre><code class="lang-javascript">Copy codeconsole.log(car1.make);  <span class="hljs-comment">// Output: Toyota</span>
<span class="hljs-built_in">console</span>.log(car1.getInfo()); <span class="hljs-comment">// Output: 2020 Toyota Camry</span>
<span class="hljs-keyword">let</span> prop = <span class="hljs-string">"model"</span>;
<span class="hljs-built_in">console</span>.log(car1[prop]); <span class="hljs-comment">// Output: Camry</span>
</code></pre>
<h3 id="heading-modifying-properties">Modifying Properties</h3>
<p>The properties of an object can be modified by directly assigning a new value to them. For example, to change the value of the <code>year</code> property of the car object, you can do:</p>
<pre><code class="lang-javascript">Copy codecar1.year = <span class="hljs-number">2022</span>;
<span class="hljs-built_in">console</span>.log(car1.year); <span class="hljs-comment">// Output: 2022</span>
</code></pre>
<h3 id="heading-object-methods">Object Methods</h3>
<p>JavaScript objects are collections of key-value pairs, and each key-value pair is called a property. In addition to properties, objects can also have methods, which are functions that are associated with an object.</p>
<p>There are several built-in methods in JavaScript that can be used with objects, including:</p>
<ul>
<li><p><code>Object.assign()</code> : This method copies the values of all enumerable own properties from one or more source objects to a target object and returns the target object.</p>
</li>
<li><p><code>Object.create()</code> : This method creates a new object with the specified prototype object and properties.</p>
</li>
<li><p><code>Object.defineProperties()</code> : This method defines new or modifies existing properties directly on an object, and returns the object.</p>
</li>
<li><p><code>Object.defineProperty()</code> : This method defines a new property directly on an object, or modifies an existing property, and returns the object.</p>
</li>
<li><p><code>Object.entries()</code> : This method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in the loop.</p>
</li>
<li><p><code>Object.freeze()</code> : This method prevents new properties from being added to an object and prevents existing properties from being removed or modified.</p>
</li>
<li><p><code>Object.getOwnPropertyDescriptor()</code> : This method returns a property descriptor for the own property of an object.</p>
</li>
<li><p><code>Object.getOwnPropertyNames()</code> : This method returns an array of all properties (enumerable or not) found directly upon a given object.</p>
</li>
<li><p><code>Object.getPrototypeOf()</code> : This method returns the prototype of the specified object.</p>
</li>
<li><p><code>Object.isExtensible()</code> : This method determines if an object is extensible (whether it can have new properties added to it).</p>
</li>
<li><p><code>Object.keys()</code> : This method returns an array of a given object's own enumerable properties.</p>
</li>
<li><p><code>Object.preventExtensions()</code> : This method prevents new properties from ever being added to an object.</p>
</li>
<li><p><code>Object.seal()</code> : This method prevents new properties from being added to an object and marks all existing properties as non-configurable.</p>
</li>
<li><p><code>Object.values()</code> : This method returns an array of a given object's own enumerable property values.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Website Responsiveness and Application of Media Queries]]></title><description><![CDATA[What is responsive design and why do we need it?
Responsive Design refers to the ability of the web design/UI to not break on different types of devices. In simple words, a web page should look good on 4k screens and on the small mobile device screen...]]></description><link>https://blog.ashishkrjha.dev/website-responsiveness-and-application-of-media-queries</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/website-responsiveness-and-application-of-media-queries</guid><category><![CDATA[media queries]]></category><category><![CDATA[Responsive Web Design]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Fri, 20 Jan 2023 15:33:51 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-what-is-responsive-design-and-why-do-we-need-it">What is responsive design and why do we need it?</h3>
<p>Responsive Design refers to the ability of the web design/UI to not break on different types of devices. In simple words, a web page should look good on 4k screens and on the small mobile device screens. As the size of the screen changes the UI should also change with it instead of breaking.</p>
<p>We need responsiveness because it makes our devices available to more users. We have many tools at our disposal to make a website responsive, some of them are media queries, using scalable units such as <code>rem</code> ,<code>em</code>, and <code>%</code>.</p>
<h3 id="heading-introduction-to-media-queries">Introduction to media queries</h3>
<p>Media queries are a powerful tool that allows us to make our website responsive and adapt to different devices with different screen sizes. It gives us to change the layout depending on the width, height, orientation, and resolution of the device.</p>
<p>The general syntax of media queries is like this:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (screen size){

<span class="hljs-selector-tag">body</span>{
<span class="hljs-comment">/*somecode*/</span>
}

<span class="hljs-selector-class">.someClass</span>{
<span class="hljs-comment">/*somecode*/</span>
}

}
</code></pre>
<p>In the above example, we can see that we are changing the layout or style of the website depending on the screen size of the viewport. We can have multiple media queries for different screen sizes. These screen size breakpoints appear in the dev tools of chrome. If you <strong>inspect</strong> any page and press <code>ctrl+shift+m</code> you will see the breakpoint at the top right below the website URL</p>
<p>This is an example of the Youtube breakpoint</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674227246245/dde1a54e-1cd4-4e72-9ad3-abc0ab362724.png" alt class="image--center mx-auto" /></p>
<p>You can see all the vertical thin lines of the color green, yellow and blue are the breakpoints that youtube has. Now don't get all worried as most websites don't even have half of the breakpoints as youtube.</p>
<p>Most websites have 4-6 breakpoints or less or more depending on the targeted visitors of their website.</p>
<h3 id="heading-we-can-use-media-queries-in-combination-with-other-methods">We can use media queries in combination with other methods.</h3>
<p>Yes, there are many ways to make a website responsive and media queries are one of the popular ones but it alone is not enough to get the job done <strong>efficiently</strong>. We can use things like flexbox and grid container to make the website more fluid along with units like <code>em</code>, <code>rem</code> and <code>%</code>.</p>
<p>CSS Grid is an incredibly powerful tool for creating intricate and organized web page layouts. It allows for a much more flexible layout system than traditional HTML and CSS, allowing elements to be placed in specific rows and columns, and have specific sizes and positions. This makes it perfect for creating complex and responsive designs that adapt to different screen sizes and devices.</p>
<p>Flexbox is one of the most widely used and efficient ways to design our layout in HTML. When we have a lot of elements we can use <code>flex-wrap</code> to make it adjust according to the screen size.</p>
<h3 id="heading-optimizing-according-to-the-devices">Optimizing according to the devices</h3>
<p>Most website companies have data about what devices access their website and they can target those devices by defining a range of values. The general syntax for such media queries is something like</p>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">500px</span>) <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">800px</span>) <span class="hljs-keyword">and</span> (<span class="hljs-attribute">orientation:</span> landscape){
<span class="hljs-comment">/*Style*/</span>
}
</code></pre>
<p>By using more strict conditions we can improve the UX and Ui for a targeted device.</p>
<h3 id="heading-some-tips-to-increase-the-flexibility-of-the-website">Some Tips to increase the Flexibility of the website</h3>
<ul>
<li><p>Utilize a mobile-first approach: Start with the most basic styles for a mobile experience and layer on additional styles as the viewport gets larger.</p>
</li>
<li><p>Leverage a combination of min-width and max-width media queries: This allows you to create breakpoints that target specific devices or ranges of devices.</p>
</li>
<li><p>Make use of em-based media queries: This allows you to create breakpoints that are relative to the font size of the user’s device.</p>
</li>
<li><p>Take advantage of orientation media queries: This is important for ensuring your website looks great on both landscape and portrait orientations.</p>
</li>
<li><p>Consider using media query combinations: This allows you to define multiple breakpoints in one media query and target a specific range of viewports.</p>
</li>
<li><p>Incorporate media query testing into your workflow: Use tools like Chrome DevTools to test and debug your media queries.</p>
</li>
</ul>
<h3 id="heading-testing-and-debugging-responsiveness">Testing and Debugging Responsiveness</h3>
<p>Test and debugging responsiveness is a vital part of web development. Responsive design is the concept of having a website look and function optimally regardless of the device or screen size of the user. To ensure that a website is responsive, it must be tested and debugged across multiple devices and browsers.</p>
<p>Testing and debugging are essential for verifying that the website is optimized for all device sizes and that all features are working properly. This process can be done manually or with automated tools.</p>
<p>Manual testing involves checking the website on a variety of devices and browsers. This can be time-consuming and tedious, but it is the most reliable way to ensure that the website looks and functions as intended.</p>
<p>Automated testing can be done with tools such as Selenium and PhantomJS. These tools can quickly simulate user interactions on a website, and generate reports that can be used to debug any issues. In addition, they can be used to run automated tests across multiple browsers and devices.</p>
<p>The process of testing and debugging a website for responsiveness requires a thorough understanding of HTML, CSS, and JavaScript. It’s important to make sure that all elements of the website are optimized for a range of devices and browsers, and that any issues are quickly identified and</p>
]]></content:encoded></item><item><title><![CDATA[CSS Grid: An Overview]]></title><description><![CDATA[CSS Grid is an incredibly powerful tool for creating intricate and organized web page layouts. It allows for a much more flexible layout system than traditional HTML and CSS, allowing elements to be placed in specific rows and columns, and have speci...]]></description><link>https://blog.ashishkrjha.dev/css-grid-an-overview</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/css-grid-an-overview</guid><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Fri, 20 Jan 2023 14:41:46 GMT</pubDate><content:encoded><![CDATA[<p>CSS Grid is an incredibly powerful tool for creating intricate and organized web page layouts. It allows for a much more flexible layout system than traditional HTML and CSS, allowing elements to be placed in specific rows and columns, and have specific sizes and positions. This makes it perfect for creating complex and responsive designs that adapt to different screen sizes and devices.</p>
<p>At its core, CSS Grid is a two-dimensional grid-based layout system. It allows elements to be placed in rows and columns and has a number of powerful features that allow for more control over how elements look and interact on the page. It also provides support for auto-placement, meaning elements can be placed in specific positions without having to manually code every element's position.</p>
<p>CSS Grid makes it easy to create complex web page designs. It provides a wide range of features such as grid-template-columns, grid-template-rows, grid-gap, and grid-area, which allow developers to easily create layouts with precise control over element positioning, sizing, and spacing.</p>
<p>For example, the following code uses grid-template-columns and grid-template-rows to define the layout for a page with four columns and three rows:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid</span> { 
<span class="hljs-attribute">display</span>: grid; 
<span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr; 
<span class="hljs-attribute">grid-template-rows</span>: <span class="hljs-number">100px</span> <span class="hljs-number">100px</span> <span class="hljs-number">100px</span>; 
}
</code></pre>
<p>In this example, the grid is split into four columns, each with a width of 1fr (which stands for fraction), and three rows with a height of 100px. This will create a four-column, three-row grid.</p>
<p>CSS Grid also supports a number of other features, such as, <code>grid-gap</code> which allows for spacing between elements, and, <code>grid-area</code> which allows elements to be placed in specific areas of the grid. These features allow developers to create complex and responsive layouts that can adapt to different screen sizes and devices.</p>
<p>CSS Grid is an incredibly powerful tool for creating complex and responsive</p>
<h3 id="heading-placing-the-grid-items-in-a-container-and-assigning-their-position">Placing the grid Items in a container and assigning their position</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>fr);
  <span class="hljs-attribute">grid-gap</span>: <span class="hljs-number">10px</span> <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-class">.item1</span> {
  <span class="hljs-attribute">grid-column</span>: <span class="hljs-number">1</span> / <span class="hljs-number">2</span>;
  <span class="hljs-attribute">grid-row</span>:  <span class="hljs-number">1</span> / <span class="hljs-number">2</span>;
}

<span class="hljs-selector-class">.item2</span> {
  <span class="hljs-attribute">grid-column</span>: <span class="hljs-number">2</span> / <span class="hljs-number">3</span>;
  <span class="hljs-attribute">grid-row</span>: <span class="hljs-number">1</span> / <span class="hljs-number">3</span>;
}

<span class="hljs-selector-class">.item3</span> {
  <span class="hljs-attribute">grid-column</span>: <span class="hljs-number">3</span> / <span class="hljs-number">4</span>;
  <span class="hljs-attribute">grid-row</span>: <span class="hljs-number">1</span> / <span class="hljs-number">2</span>;
}
</code></pre>
<p>The code sets up a 3-column grid with 10px of gap between each column and row. The items are then placed within the container using the grid-column and grid-row properties. The .item1 class is placed in the first column, first row, .item2 is placed in the second column, first and second rows, and .item3 is placed in the third column, first row.</p>
<h3 id="heading-best-practices-for-working-with-css-grid-and-tips-for-debugging-and-troubleshooting">Best practices for working with CSS Grid and tips for debugging and troubleshooting</h3>
<ul>
<li><p>Start Simple: Begin with a basic grid structure and then build from there.</p>
</li>
<li><p>Use Source Order: Pay attention to the order of your HTML elements and adjust the grid accordingly.</p>
</li>
<li><p>Nest Grids: Nesting grids can help you create complex layouts.</p>
</li>
<li><p>Utilize Template Areas: Template areas make it easier to visualize and create complex layouts.</p>
</li>
<li><p>Use Flexible Units: Use flexible units such as fr and ch for setting up grid rows and columns.</p>
</li>
<li><p>Plan Ahead: Take the time to plan out your grids and think ahead to future needs.</p>
</li>
<li><p>Utilize Fallbacks: Try to incorporate fallbacks and alternative approaches for browsers that don’t support CSS Grid.</p>
</li>
<li><p>Leverage DevTools: Use Chrome’s DevTools to visualize and debug your grid layouts.</p>
</li>
<li><p>Test Across Browsers: Always test your grid layouts across multiple browsers and devices.</p>
</li>
<li><p>Use a Grid System: If you’re not comfortable creating grids from scratch, consider using a grid system such as Bootstrap.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Intro to HTML Input Fields]]></title><description><![CDATA[What are input Fields in HTML?
Anything that allows us to give data, or enter any form of data in to web page can be considered as input field. They can be range sliders, input boxes, number fields, date and time selector etc.
In this article we will...]]></description><link>https://blog.ashishkrjha.dev/intro-to-html-input-fields</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/intro-to-html-input-fields</guid><category><![CDATA[html forms]]></category><category><![CDATA[HTML5]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Fri, 20 Jan 2023 13:55:25 GMT</pubDate><content:encoded><![CDATA[<h4 id="heading-what-are-input-fields-in-html">What are input Fields in HTML?</h4>
<p>Anything that allows us to give data, or enter any form of data in to web page can be considered as input field. They can be range sliders, input boxes, number fields, date and time selector etc.</p>
<p>In this article we will briefly look over these input fields and learn what purpose they serve.</p>
<h3 id="heading-importance-of-input-field-in-html-forms-and-ui">Importance of Input field in HTML forms and UI</h3>
<p>As mentioned above the input fields are elements which takes user input in a form. They help improve the interactions with the web page.</p>
<p>Some of the Input fields are:</p>
<ul>
<li><p><code>&lt;input&gt;</code> : This is the most commonly used input field and it has various attributes.</p>
<ul>
<li><p><code>&lt;input type="text"&gt;</code> : This is a basic text input field that allows user to enter text.</p>
</li>
<li><p><code>&lt;input type="password"&gt;</code> : This is a password field that allows user to enter password or any sensitive information which the user might not want to show to everyone</p>
</li>
<li><p><code>&lt;input type="checkbox"&gt;</code>: This is a checkbox that allows the user to select one or more options from a list.</p>
</li>
<li><p><code>&lt;input type="radio"&gt;</code> : This is a radio button that allows user to select one option out of many other</p>
</li>
<li><p><code>&lt;input type="submit"&gt;</code> : This is used to submit a block of information from the page to server</p>
</li>
<li><p><code>&lt;input type="reset"&gt;</code> : This is used to reset all the input fields</p>
</li>
</ul>
</li>
<li><p><code>&lt;textarea&gt;</code> : This is an input field which is used incase we want to enter a large chunk to information</p>
</li>
</ul>
<h3 id="heading-best-practices-for-input-fields">Best Practices for Input fields</h3>
<p>The best practices fall under the proper HTML semantics</p>
<ul>
<li><p>Choosing correct type of input field for the requirement is very important. We wouldn't want a password field with <code>type=text</code>.</p>
</li>
<li><p>Whenever we choose the input fields we must choose the fields while keeping the user experience in mind. If we want to select states we need a drop-down field.</p>
</li>
<li><p>Using a proper labels to correctly identify the elements of input field helps the crawler as well as the people who use screen readers. This adds to the accessibility of the web page.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[What are HTML elements???]]></title><description><![CDATA[An HTML element is a piece of text wrapped by <>, It is referred to as HTML tags to be specific. HTML offers a wide variety of such tags and this increases with every version of HTML.
Why are the tags so important?
The tags give us a structure in the...]]></description><link>https://blog.ashishkrjha.dev/what-are-html-elements</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/what-are-html-elements</guid><category><![CDATA[semantichtml]]></category><category><![CDATA[HTML5]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Fri, 20 Jan 2023 12:40:11 GMT</pubDate><content:encoded><![CDATA[<p>An HTML element is a piece of text wrapped by <code>&lt;&gt;</code>, It is referred to as HTML tags to be specific. HTML offers a wide variety of such tags and this increases with every version of HTML.</p>
<h4 id="heading-why-are-the-tags-so-important">Why are the tags so important?</h4>
<p>The tags give us a structure in the website and allow the browsers to know which is what. It also helps web crawlers to scrap the web for better visibility or data scraping.</p>
<p>Each set of tags has its own unique purpose and behavior. For example <code>&lt;img&gt;</code> tag holds the source link to an image and it is used to display images.</p>
<p>HTML tags can be divided into different categories, Some of the important ones are</p>
<ul>
<li><p>Structural Tags: These tags are used to create the overall structure of web pages and it also helps the crawler look for the things it needs. Some of these tags are <code>&lt;html&gt;</code> ,<code>&lt;body&gt;</code> and <code>&lt;head&gt;</code></p>
</li>
<li><p>Headings and paragraphs: These tags are used to organize the title and paragraphs in the webpage. The crawler uses these tags to check the heading/title and content of the page. Tags are <code>&lt;h1&gt;</code> which ranges from <code>h1</code> to <code>h6</code> and there is <code>&lt;p&gt;</code> tag for the paragraphs.</p>
</li>
<li><p>Lists: These tags are used to create lists in a webpage. This can be an ordered list or an unordered list. The tag for the ordered list is <code>&lt;ol&gt;</code> and the tag for the unordered list is <code>&lt;ul&gt;</code> and the <code>&lt;li&gt;</code> tag is used to specify the list item inside the ordered or unordered list.</p>
</li>
<li><p>Links: The tag for creating a hyperlink is <code>&lt;a&gt;</code> tag and we can use it to create hyperlinks and add the link to <code>href</code> attribute and we can also have a <code>target</code> which can be assigned to <code>_blank</code> , if we do this the hyperlink will open in a new tab</p>
</li>
<li><p>Images: The tag <code>&lt;img&gt;</code> used to show images in a page. It has attributes for <code>src</code> which points to the source of the image and an <code>alt</code> tag which shows up in case the image doesn't load up. <code>alt</code> tag helps the crawler and adds to the accessibility of the web page</p>
</li>
<li><p>Tables: The tags which help us to create a table falls under this category. The tags are <code>&lt;table&gt;</code>, <code>&lt;tr&gt;</code> and <code>&lt;td&gt;</code>. Where <code>&lt;table&gt;</code> is the parent tag and <code>&lt;tr&gt;</code> represents the table row and <code>&lt;td&gt;</code> represents the table data?</p>
</li>
<li><p>Forms: The tags which help us to create forms fall under this section. <code>&lt;form&gt;</code>, <code>&lt;input&gt;</code> and <code>&lt;button&gt;</code> are some examples of form tags.</p>
</li>
</ul>
<h3 id="heading-how-does-html-semantics-affect-seo">How does HTML semantics affect SEO?</h3>
<p>What is SEO you might ask?</p>
<p>Well, SEO stands for Search Engine Optimization. Whenever we search google for something the google crawler crawls the websites to look for relevant information and returns the results.</p>
<p>Suppose your website has the exact information someone is looking for but your web pages are poorly optimized for SEO, In that case, that person will no see your web page in the first few pages of the search maybe not even later. So proper SEO is desired in websites.</p>
<p>HTML semantics come to the rescue for this. <code>&lt;h1&gt;</code> should only be used for the main heading of the website, if there are two <code>&lt;h1&gt;</code> tags the crawler will get confused as to which is the main heading. Similarly the <code>&lt;h2&gt;</code> and <code>&lt;h3&gt;</code> Tags are used for the subheadings and should be used in that manner.</p>
<p>Another useful thing is the <code>&lt;meta&gt;</code> tag which can be used to provide additional information about the web page. Using HTML tags correctly and consistently can help search engines to understand the content of a page and return to the web page when a user searches for the information.</p>
<p>HTML semantics are often overlooked by beginners but it is one of the most important overlooked topics because using correct semantics makes the website more readable to machines and machines are the ones who show your website to everyone.</p>
]]></content:encoded></item><item><title><![CDATA[Brief Intro to CSS Box Model]]></title><description><![CDATA[What is a Box Model in CSS?
The CSS Box model is a box that wraps around every HTML element. The term "Box Model" is used when talking about design and Layout. It consists of few things: Margin, Padding, Borders, and the Actual content.

All the thin...]]></description><link>https://blog.ashishkrjha.dev/brief-intro-to-css-box-model</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/brief-intro-to-css-box-model</guid><category><![CDATA[CSS]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[Css padding property ]]></category><category><![CDATA[Css margin property ]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Fri, 20 Jan 2023 07:39:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674200243472/d8931347-a43a-4b91-af10-bfe00959d1ef.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-is-a-box-model-in-css">What is a Box Model in CSS?</h1>
<p>The CSS Box model is a box that wraps around every HTML element. The term "Box Model" is used when talking about design and Layout. It consists of few things: <strong>Margin</strong>, <strong>Padding, Borders,</strong> and the <strong>Actual content.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674198653328/103ebc41-8208-4e37-87ab-6645bcb026ed.png" alt class="image--center mx-auto" /></p>
<p>All the things in a box model give HTML a structure. We will discuss some of the options given to us for this model</p>
<h3 id="heading-borders">Borders</h3>
<p>Borders can be applied to most boxes in HTML. Borders have parameters such as</p>
<ul>
<li><p><code>border-width</code> : This decidess what the width of the border will be</p>
</li>
<li><p><code>border-style</code>: This parameter helps us to determine the style of the border</p>
</li>
<li><p><code>border-color</code>: We can change the color of the border using this parameter</p>
</li>
<li><p><code>border-radius</code>: This is use to curve the edges and can help us to make the UI look more elegant or make rounded shapes.</p>
<p>  We can use the various options these parameters provide us. We can use these parameter on all four sides of the container. For more in-depth knowledge refer <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/border">here</a></p>
</li>
</ul>
<h3 id="heading-margin">Margin</h3>
<p>Margins are like their name suggests, consider the margins of your notebook. We try to keep things within the margins of the notebook. Similarly in CSS when we use margin it is applied on the outer side of the container. It can be use as</p>
<ul>
<li><p><code>margin</code>: This applies the margin evenly on all four sides of the container</p>
</li>
<li><p><code>margin-left</code> : This applies the margin at the left side of the container</p>
</li>
<li><p><code>margin-top</code> : This applies the margin at the top side of the container</p>
</li>
<li><p><code>margin-right</code> This applies margin at the right side of the container</p>
</li>
<li><p><code>margin-bottom</code>: This applies the margin at the bottom side of the container</p>
</li>
</ul>
<p>Warning: Overuse of Margin may lead to margin-collapse which messes up the entire flow of the layout.</p>
<p>It is best to avoid using margins in all places. Margins can affect the layout of other containers depending on where you use it. For more in-depth knowledge refer <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/margin">here</a></p>
<h3 id="heading-padding">Padding</h3>
<p>Padding is the gap inside, between the border and the content. It's like a cushion that separates the border and the content inside the container. Padding doesn't not impact anything outside of the container. It is essential to the layout.</p>
<p>Just like the margin, we can apply padding on all four sides of the container or just one side depending on the requirements of the UI. It can be applied as</p>
<ul>
<li><code>padding</code>: This applies the padding evenly on all four sides of the container</li>
</ul>
<ul>
<li><p><code>padding-left</code> : This applies the padding at the left inner side of the container</p>
</li>
<li><p><code>padding-top</code> : This applies the margin at the top inner side of the container</p>
</li>
<li><p><code>padding-right</code> This applies margin at the right inner-side of the container</p>
</li>
<li><p><code>padding-bottom</code>: This applies the margin at the bottom inner-side of the container</p>
</li>
</ul>
<p>For more in-depth knowledge refer <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/padding">here</a></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript  Interview Quick Overview]]></title><description><![CDATA[Javascript is the soul of web development and trying to understand some concepts might leave you confused. In this article, we tried to clear some of the core concepts that are asked in the interviews. So let's dive straight into it.
Scope
The scope ...]]></description><link>https://blog.ashishkrjha.dev/javascript-interview-quick-overview</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/javascript-interview-quick-overview</guid><category><![CDATA[iwritecode]]></category><category><![CDATA[Hoisting]]></category><category><![CDATA[callstack]]></category><category><![CDATA[Scope]]></category><category><![CDATA[#js-interview]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Sun, 11 Sep 2022 12:57:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1662900985922/iJyvw5Vdn.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Javascript is the soul of web development and trying to understand some concepts might leave you confused. In this article, we tried to clear some of the core concepts that are asked in the interviews. So let's dive straight into it.</p>
<h1 id="heading-scope">Scope</h1>
<p>The scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.
Scopes are layered in a hierarchy, so the child has access to the parent's scope but not the other way around. </p>
<p><strong><em>Think of it as the relationship between child and parent, the child can ask or take an ice cream or chocolate from the parents but not the other way around (I mean you can but...)</em></strong></p>
<p>This example should give you a better understanding. Let's dive into the different types of scope in Js</p>
<h3 id="heading-what-is-a-global-scope">What is a Global Scope?</h3>
<p>Global scope is the default scope for running all the code in js and everything runs in this scope.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> globalVariable = <span class="hljs-string">'test1'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">//some code</span>
}
</code></pre>
<p>In the above example the <code>globalVariable</code> with the value of <code>test1</code> is in global scope. In HTML the global scope refers to the <code>window</code> Object</p>
<ul>
<li>Module Scope: This is the scope of the modules in the code. You must have imported some modules if you have worked with any frameworks of Js</li>
</ul>
<h3 id="heading-what-is-a-function-scope">What is a Function Scope?</h3>
<p>Function Scope is the scope created using a function</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">let</span> number = <span class="hljs-number">45</span>
<span class="hljs-built_in">console</span>.log(number)<span class="hljs-comment">// this will print the number 45 when the function is called</span>
}
test()
<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">//this will throw an error of the number is not defined</span>
</code></pre>
<p>In the above example, you can see we cannot access the variables from outside the function if they are declared inside the function. But <code>functions</code> inside the <code>function test()</code> can access the variables of the parent function. Sometimes it is also referred to as Lexical scope.</p>
<h3 id="heading-how-do-let-and-const-act-in-terms-of-scope">How do let and const act in terms of scope?</h3>
<p>There are <code>let</code> and <code>const</code> which work in <code>block scope</code>. </p>
<p>Block Scope It is a scope created by opening <code>{</code> and  closing with <code>}</code></p>
<pre><code class="lang-js">{
    <span class="hljs-keyword">let</span> num = <span class="hljs-number">25</span>
    <span class="hljs-keyword">const</span> tea = <span class="hljs-string">'tasty'</span>
    <span class="hljs-built_in">console</span>.log(num) <span class="hljs-comment">// 25</span>
    <span class="hljs-built_in">console</span>.log(tea) <span class="hljs-comment">// tasty</span>
}
<span class="hljs-built_in">console</span>.log(num) <span class="hljs-comment">// num is not defined</span>
<span class="hljs-built_in">console</span>.log(tea) <span class="hljs-comment">// tea is not defined</span>
</code></pre>
<p>There is another keyword called <code>var</code> which has a function or global scope but it is not advisable to use this <code>var</code> keyword for declarations.</p>
<h3 id="heading-what-is-a-scope-chain">What is a scope chain?</h3>
<p>Js engine uses a scope to find the exact location or accessibility of the variables and that particular process is called Scope chain. It means that one variable has a scope used by another variable or function having another scope.</p>
<h1 id="heading-single-thread">Single Thread</h1>
<p>Those of you who have been working with Js for a while would have come across the term called Single Thread. 
This term is just used to refer to a way javascript reads code which is one or single line at a time. Javascript is a language that runs one line of code at a time and waits until that line is complete and is ok and moves to the next line. </p>
<p>If the line needs time to execute it moves to the next line by default but to stop if from moving we can use <code>async/await</code> and wait until the current line is executed completely. We might have to do this because the results of the current line might be required for future lines of code.
This happens because Javascript uses something called call stack which we will discuss in the next section</p>
<h1 id="heading-call-stack">Call Stack</h1>
<p>If you know the Data Structure of stack which follows LIFO, call stack is works just like that. However if you don't know the Data Structure Stack worry not, we got you covered.</p>
<h3 id="heading-explain-call-stack">Explain call stack.</h3>
<p>Imagine a pile of books, a very tall pile of heavy books. If you try to get something at the bottom it will be very difficult and you might end up crashing the tower of those heavy books. So what do you do? You take the book on top and remove it and keep doing this until you reach your desired book. Same thing is happening in call stack. The term <code>LIFO</code> stands for <code>Last In First Out</code>, which simply means the book <em>you kept last</em> on the top of the pile needs to <em>go out first</em></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">A</span>(<span class="hljs-params"></span>)</span>{
    B()
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am Function A`</span>)
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">B</span>(<span class="hljs-params"></span>)</span>{
    C()
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am Function B`</span>)
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">C</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am function C`</span>)
}
A()
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662890602204/o9C7XvhM1.png" alt="image.png" /></p>
<p>Now in the above example you can see the <code>function C</code> ran first then <code>function B</code> and then finally <code>function A</code>. Image below explains this further.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662889875083/isJxfxyew.png" alt="2.png" /></p>
<p>The blocks in the above image are functions that were pushed into the call stack. </p>
<ul>
<li>First the program was scanned and it saw only <code>function A</code> is being called so it went to <code>Function A</code></li>
<li>In <code>Function A</code> it saw the call for <code>Function B</code> before the <code>console.log</code> could execute so it went to <code>Function B</code> and added it in the call stack, and from there to <code>Function C</code> and added it to the call stack. </li>
<li>Entire functions are loaded and stacked  on top on one another and so we execute the one at the top, In this case its <code>Function C</code>.</li>
<li>After the execution of <code>Function C</code>, the next function in the call stack was <code>Function B</code> so it went ahead and executed the <code>console.log</code> there.</li>
<li>And finally, it executed the last function remaining in the call stack which emptied the call stack.</li>
</ul>
<h1 id="heading-hoisting">Hoisting</h1>
<p>JavaScript Hoisitng refers to the process by which the interpreter moves the declaration of functions, variables to the top of their scope before the code execute.</p>
<p>This allows Functions to be safely used before they are declared but variables and classes are hosted differently.</p>
<p>A general rule which helps me to track hoisting process is :</p>
<ul>
<li><code>Functions are scanned and stored in memory or made available  for future use</code></li>
<li><code>Variables are scanned and made undefined</code></li>
</ul>
<h3 id="heading-function-hoisting">Function Hoisting</h3>
<pre><code class="lang-js">A(<span class="hljs-number">5</span>)
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">A</span>(<span class="hljs-params">num</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'\n'</span>)
    <span class="hljs-built_in">console</span>.log(num*num)
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'\n'</span>)
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662899335903/bAP6ZXrIU.png" alt="image.png" /></p>
<p>As you can see in the example that the function <code>A()</code> is being called before the declaration. When the Javascript interpreter scanned the program it saw a function <code>A()</code> and it knew there is a function called <code>A()</code>.
Without hoisting we would have to call the function after it is declared.</p>
<h3 id="heading-variable-hoisting">Variable Hoisting</h3>
<p>According to the rule mentioned above Variables used before declaration will return <code>undefined</code> value</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(num)
<span class="hljs-keyword">var</span> num  = <span class="hljs-number">9</span>
num = <span class="hljs-number">8</span>*<span class="hljs-number">8</span>
<span class="hljs-built_in">console</span>.log(num)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1662899681443/mcabRBaAS.png" alt="image.png" /></p>
<p>In the above example you can see the when we use variable before declaration it returns <code>undefined</code>. After which we declare it and give it a value of <code>9</code> and then change that value to <code>8*8</code> and <code>console.log</code> the value which returns 64 which is the result of <code>8*8</code>.</p>
<p>This is example case but if we use <code>let</code> instead of <code>var</code>, it would throw an error on the first line saying <code>num is not defined</code></p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Inbuilt Arrays Methods]]></title><description><![CDATA[What is an array?
Well, In programming it is just a collection of some similar or non-similar data. In Javascript, there is no restriction on array type. For example
int arr[] = { 10, 20, 30, 40};

the above array contains only numbers and is in the ...]]></description><link>https://blog.ashishkrjha.dev/javascript-inbuilt-arrays-methods</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/javascript-inbuilt-arrays-methods</guid><category><![CDATA[iwritecode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[array methods]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Sat, 27 Aug 2022 13:19:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1661606241897/AlFNCXNPh.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-is-an-array">What is an array?</h1>
<p>Well, In programming it is just a collection of some similar or non-similar data. In Javascript, there is no restriction on array type. For example</p>
<pre><code class="lang-c++"><span class="hljs-keyword">int</span> arr[] = { <span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>};
</code></pre>
<p>the above array contains only numbers and is in the syntax of C++ language, as you can see the type <code>int</code> has been mentioned. </p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arr = [ <span class="hljs-string">'Cars'</span>, <span class="hljs-number">4</span>, <span class="hljs-literal">true</span>, [<span class="hljs-string">'this'</span> ,<span class="hljs-string">'is'</span> ,<span class="hljs-string">'subarray'</span>]]
</code></pre>
<p>However, In Javascript, we don't need the type declaration, which is a good or bad thing depending on the situation. The above example demonstrates the declaration of an array.
In Programming <strong>arrays</strong> play a vital role. Javascript has provided us with multiple functions to make our life easier in development. In this Article we will be discussing the various aspects of the array functions in Javascript.</p>
<h2 id="heading-declaration-using-constructor">Declaration Using Constructor</h2>
<p>We can declare array via above method called literal notation or constructor</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]
</code></pre>
<p>Another method to declare the array using the constructor </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span>  numbers = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>)
</code></pre>
<p>We can also declare array length like</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">5</span>)
</code></pre>
<h2 id="heading-static-array-methods">Static Array Methods</h2>
<h3 id="heading-arrayfrom">Array.from()</h3>
<p>We can use static array methods to create a new arrays from some data we have. The syntax is <code>Array.from()</code></p>
<p>Array from a String:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> name = <span class="hljs-string">'mango'</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>.from(name))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661598992383/nPmhEQlNO.png" alt="image.png" /></p>
<p>Array after performing some operation:
The Syntax is <code>Array.from(array, function)</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>.from(arr, <span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> x*x))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661598947705/zlincw5zY.png" alt="image.png" /></p>
<h3 id="heading-arrayisarray">Array.isArray()</h3>
<p>This Array function checks if the given parameter is an array or not. It returns <code>true</code> if it is an array otherwise it returns <code>false</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> name = <span class="hljs-string">'mango'</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>.isArray(arr));
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>.isArray(name));
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661598899814/emH2kYJq-.png" alt="image.png" /></p>
<h3 id="heading-arrayof">Array.of()</h3>
<p>The <code>Array.of()</code> method creates a new Array from the arguments given regardless of type.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>.of(<span class="hljs-string">'travel'</span>));
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>.of(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>));
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661598870207/BKHqU1tz5.png" alt="image.png" /></p>
<h2 id="heading-instance-properties">Instance properties</h2>
<h3 id="heading-arraylength">Array.length</h3>
<p>This is a widely used property that gives us the length of the array, <code>array.length</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-string">'q'</span>,<span class="hljs-string">'w'</span>,<span class="hljs-string">'4'</span>,<span class="hljs-number">3</span>]
<span class="hljs-built_in">console</span>.log(numbers.length);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661593023429/K3id2licE.png" alt="image.png" /></p>
<h2 id="heading-instance-methods">Instance Methods</h2>
<h3 id="heading-arrayat">Array.at()</h3>
<p>This method returns array item <code>at</code> a given <code>index</code>, It also accepts negative integers as arguments and counts back from the last element.
<code>Array.at()</code>, This is a fairly new method so it might not be available for you in your environment.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-string">'q'</span>,<span class="hljs-string">'w'</span>,<span class="hljs-string">'4'</span>,<span class="hljs-number">3</span>]
<span class="hljs-built_in">console</span>.log(numbers.at(<span class="hljs-number">5</span>));
<span class="hljs-built_in">console</span>.log(numbers.at(<span class="hljs-number">-8</span>));
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661593689565/F4OIRyJN_.png" alt="image.png" /></p>
<h3 id="heading-arrayconcat">Array.concat</h3>
<p>This is a method which concatenates two different arrays into one array.
<code>array1.concat(array2)</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>]
<span class="hljs-keyword">const</span> numbers2 = [<span class="hljs-string">'q'</span>,<span class="hljs-string">'w'</span>,<span class="hljs-string">'4'</span>,<span class="hljs-number">3</span>]
<span class="hljs-built_in">console</span>.log(numbers.concat(numbers2))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661598816507/_mVmNzZWz.png" alt="image.png" /></p>
<h3 id="heading-arraycopywithin">Array.copyWithin()</h3>
<p>The <code>copyWithin()</code> method copies part of an array to another location in the same array and returns it without modifying its length. It can take 3 arguments but atleast one argument must be present</p>
<p><code>array.copyWithin(target,start,end)</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-string">'q'</span>,<span class="hljs-string">'w'</span>,<span class="hljs-string">'4'</span>,<span class="hljs-number">3</span>]
<span class="hljs-built_in">console</span>.log(numbers.copyWithin(<span class="hljs-number">0</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>))
<span class="hljs-built_in">console</span>.log(numbers.copyWithin(<span class="hljs-number">0</span>,<span class="hljs-number">3</span>,<span class="hljs-number">7</span>))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661598771593/r-c3GEauw.png" alt="image.png" /></p>
<h3 id="heading-arrayentries">Array.entries()</h3>
<p>This method gives us the index/value of the array elements. We can </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> num = [<span class="hljs-string">'a'</span>,<span class="hljs-string">'b'</span>,<span class="hljs-string">'c'</span>,<span class="hljs-string">'d'</span>]
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">const</span> [index,element] <span class="hljs-keyword">of</span> num.entries()){
    <span class="hljs-built_in">console</span>.log(index,element)
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661598713481/qH6wDz86W.png" alt="image.png" /></p>
<h3 id="heading-arrayevery">Array.every()</h3>
<p>This method checks if all the elements of the given array satisfies the condition. It returns true if all elements meet the condition otherwise false.
We have taken a simple even number example</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isEven = <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> value%<span class="hljs-number">2</span>===<span class="hljs-number">0</span>
<span class="hljs-keyword">const</span> arr1 = [<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">6</span>,<span class="hljs-number">8</span>]
<span class="hljs-keyword">const</span> arr2 = [<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>]
<span class="hljs-built_in">console</span>.log(arr1.every(isEven))
<span class="hljs-built_in">console</span>.log(arr2.every(isEven))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661599244895/SWm56-pc2.png" alt="image.png" /></p>
<h3 id="heading-arrayfill">Array.fill()</h3>
<p>This is a method used to change array elements to a static value, it modifies the original array. General syntax</p>
<p><code>fill(value,startIndex,endIndex)</code></p>
<p>Here start Index and end index are optional, without these all elements will be replaced by the value. Also just like the <code>.at()</code> method we can use negative integers to start from the end of Array</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log([<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>].fill(<span class="hljs-number">4</span>));
<span class="hljs-built_in">console</span>.log([<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>].fill(<span class="hljs-number">4</span>,<span class="hljs-number">1</span>))
<span class="hljs-built_in">console</span>.log([<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>].fill(<span class="hljs-number">4</span>,<span class="hljs-number">1</span>,<span class="hljs-number">2</span>))
<span class="hljs-built_in">console</span>.log([<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>].fill(<span class="hljs-number">4</span>,<span class="hljs-number">-3</span>,<span class="hljs-number">-2</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>(<span class="hljs-number">4</span>).fill(<span class="hljs-number">4</span>))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661599793881/TWLASTNh_.png" alt="image.png" /></p>
<h3 id="heading-arrayfilter">Array.filter()</h3>
<p>This returns new array containing all the elements of the calling array for which the filter condition is <code>true</code>. It takes a callback function to check the condition.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> num = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
<span class="hljs-built_in">console</span>.log(num.filter(<span class="hljs-function"><span class="hljs-params">ele</span> =&gt;</span> ele%<span class="hljs-number">2</span>!==<span class="hljs-number">0</span>))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661600069523/Q2hhLVhya.png" alt="image.png" /></p>
<h3 id="heading-arrayfind-and-arrayfindlast">Array.find() and Array.findLast()</h3>
<p>The <code>find()</code> method returns the first element in array which satisfies the given condition. If no values found it returns <code>undefined</code></p>
<p>The <code>findLast()</code>  method returns the last element in array which satisfies the given condition instead of the first like in <code>find(). If no values found it also returns</code>undefined`</p>
<pre><code class="lang-js"><span class="hljs-comment">//example contains only find() </span>
<span class="hljs-comment">// findLast() also works same but returns last element.</span>
<span class="hljs-keyword">const</span> num = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
<span class="hljs-built_in">console</span>.log(num.find(<span class="hljs-function"><span class="hljs-params">ele</span> =&gt;</span> ele&gt;<span class="hljs-number">7</span>))<span class="hljs-comment">// check for number greater than 7</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661600219237/TmW9LX_wm.png" alt="image.png" /></p>
<h3 id="heading-arrayfindindex-and-arrayfindlastindex">Array.findIndex() and Array.findLastIndex()</h3>
<p>The <code>findIndex()</code> method returns the index of the first element in the array which satisfies the given condition. If no elements are found, it returns -1.</p>
<p>The <code>findLastIndex()</code> method returns the index of the last element in the array which satisfies the given condition. If no elements are found, it returns -1.</p>
<pre><code class="lang-js"><span class="hljs-comment">// example only contains of findIndex()</span>
<span class="hljs-comment">// findLastIndex() works the same but will return last element index.</span>
<span class="hljs-keyword">const</span> num = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">8</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">9</span>]
<span class="hljs-built_in">console</span>.log(num.findIndex(<span class="hljs-function"><span class="hljs-params">ele</span> =&gt;</span> ele&gt;<span class="hljs-number">7</span>))<span class="hljs-comment">//8 is at index 5</span>
<span class="hljs-built_in">console</span>.log(num.findIndex(<span class="hljs-function"><span class="hljs-params">ele</span> =&gt;</span> ele&gt;<span class="hljs-number">10</span>))<span class="hljs-comment">// no element greater than 10</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661600398480/8fQzuxHvZ.png" alt="image.png" /></p>
<h3 id="heading-arrayflat">Array.flat()</h3>
<p>This method creates a new array with all the sub-array elements added in order into it recursively up to the specified depth</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> num = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,[<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>],<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
<span class="hljs-built_in">console</span>.log(num.flat())
<span class="hljs-keyword">const</span> num2 = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,[<span class="hljs-number">5</span>,[[<span class="hljs-number">6</span>]],<span class="hljs-number">7</span>],<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
<span class="hljs-built_in">console</span>.log(num2.flat(<span class="hljs-number">2</span>))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661601395058/4pPyuQl41.png" alt="image.png" /></p>
<h3 id="heading-arrayflatmap">Array.flatMap()</h3>
<p>This method returns a new array which is formed according to the condition given in the callback function to each element of the array, and then flattens the result by one level. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> num = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,[<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>],<span class="hljs-number">8</span>,<span class="hljs-number">9</span>]
<span class="hljs-built_in">console</span>.log(num.flatMap(<span class="hljs-function">(<span class="hljs-params">ele</span>) =&gt;</span> ele*<span class="hljs-number">2</span>))
<span class="hljs-built_in">console</span>.log(num.flatMap(<span class="hljs-function">(<span class="hljs-params">ele</span>) =&gt;</span> ele))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661601751045/_91LEW9Hu.png" alt="image.png" /></p>
<h3 id="heading-arrayforeach">Array.forEach()</h3>
<p>This is a method for the array which works with each element and applies the function to each element.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> num = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>]
num.forEach(<span class="hljs-function"><span class="hljs-params">ele</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(ele*ele))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661601984188/Sdch6OG_I.png" alt="image.png" /></p>
<h3 id="heading-arrayincludes">Array.includes()</h3>
<p>This method checks for a certain value among the entries of the array and returns <code>true</code> if value is found else <code>false</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> num = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>]
<span class="hljs-built_in">console</span>.log(num.includes(<span class="hljs-number">4</span>))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661602082756/oglLglnX6.png" alt="image.png" /></p>
<h3 id="heading-arrayindexof-and-arraylastindexof">Array.indexOf() and Array.lastIndexOf()</h3>
<p>These two method returns the  first and last index of the given element much like <code>Array.findIndex()</code> and <code>Array.findLastIndex()</code> method we saw earlier but unlike previous method, <code>indexOf()</code> allows us to decide which index to start the search from.</p>
<p><code>array.indexOf(searchElement)</code></p>
<p><code>array.indexOf(searchElement, fromIndex)</code></p>
<p><code>array.lastIndexOf(searchElement)</code></p>
<p><code>array.lastIndexOf(searchElement, fromIndex)</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> num = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">4</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">4</span>]
<span class="hljs-built_in">console</span>.log(num.indexOf(<span class="hljs-number">4</span>,<span class="hljs-number">5</span>))
<span class="hljs-built_in">console</span>.log(num.lastIndexOf(<span class="hljs-number">4</span>,num.length<span class="hljs-number">-2</span>))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661603191193/ej7KUkaY0.png" alt="image.png" /></p>
<p>As you can see we started from the <code>index 5</code> which holds the value <code>6</code> so we got the first <code>4</code> after <code>6</code> which was at the last index of <code>11</code>. And for the <code>lastIndexOf()</code> we got <code>num.length</code> which is <code>15</code> and we started with <code>13th</code> index and going reverse we got <code>4</code> at 12th index</p>
<h3 id="heading-arrayjoin">Array.join()</h3>
<p>This is a method used to join elements of array with a specific separated which is optional. The <code>join()</code> method creates and returns a new String by concatenating all the elements in an array. By default the separator is commas. If array has only one item it will remain unaffected.</p>
<p><code>arr.join()</code>
`arr.join('-')</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> name = [<span class="hljs-string">'m'</span>,<span class="hljs-string">'a'</span>,<span class="hljs-string">'n'</span>,<span class="hljs-string">'g'</span>,<span class="hljs-string">'o'</span>]
<span class="hljs-built_in">console</span>.log(name.join())
<span class="hljs-built_in">console</span>.log(name.join(<span class="hljs-string">'-'</span>))
<span class="hljs-built_in">console</span>.log(name.join(<span class="hljs-string">'_'</span>))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661603694766/A4Iof9qdD.png" alt="image.png" /></p>
<h3 id="heading-arraymap">Array.map()</h3>
<p>The <code>map()</code> method is another of the popular method people use. It creates new array and populates it with the results of calling the function on every element in the array</p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>]
<span class="hljs-keyword">const</span> squaredNum = numbers.map(<span class="hljs-function"><span class="hljs-params">ele</span> =&gt;</span> ele*ele)
<span class="hljs-built_in">console</span>.log(squaredNum)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661603955911/aG1yTD6gK.png" alt="image.png" /></p>
<h3 id="heading-arraypop">Array.pop()</h3>
<p>The <code>pop()</code> method removes the last element from an array and returns that element. This changes the original array's length</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>]
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Length before pop() is : <span class="hljs-subst">${numbers.length}</span>`</span>)
<span class="hljs-keyword">const</span> popped = numbers.pop()
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The removed element : <span class="hljs-subst">${popped}</span>`</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Array after Change <span class="hljs-subst">${numbers}</span>`</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Length after pop() is : <span class="hljs-subst">${numbers.length}</span>`</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661604167134/r2aOcKWDw.png" alt="image.png" /></p>
<h3 id="heading-arraypush">Array.push()</h3>
<p>The <code>push()</code> method adds one or more elements to end the array and returns the new length of the array</p>
<p><code>array.push(element1, element2,...,elementN)</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Length before push() is : <span class="hljs-subst">${numbers.length}</span>`</span>)
numbers.push(<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Array after Change <span class="hljs-subst">${numbers}</span>`</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Length after push() is : <span class="hljs-subst">${numbers.length}</span>`</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661604365232/clnf6QG-c.png" alt="image.png" /></p>
<h3 id="heading-arrayreduce">Array.reduce()</h3>
<p>The <code>reduce()</code> method executes a user-supplied "reducer" callback function on every element of the array. It works on each element step by step and in order. It does not change the original array</p>
<p><code>reduce((previousValue, currentValue, currentIndex, array) =&gt; { /* … */ } )</code></p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]
<span class="hljs-built_in">console</span>.log(numbers.reduce(<span class="hljs-function">(<span class="hljs-params">ele, sum</span>) =&gt;</span> sum + ele))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661604721145/pmteBlPO8.png" alt="image.png" /></p>
<h3 id="heading-arrayreverse">Array.reverse()</h3>
<p>The reverse() method reverse an array and returns the reference to same array, i.e it modifies the original array.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]
<span class="hljs-built_in">console</span>.log(numbers)
numbers.reverse()
<span class="hljs-built_in">console</span>.log(numbers)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661604837683/HF-8Rw1Bj.png" alt="image.png" /></p>
<h3 id="heading-arrayshift">Array.shift()</h3>
<p>This method removes the first element from the array and returns that element.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>]
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Length before shift() is : <span class="hljs-subst">${numbers.length}</span>`</span>)
<span class="hljs-keyword">const</span> shifted = numbers.shift()
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The removed element : <span class="hljs-subst">${shifted}</span>`</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Array after Change <span class="hljs-subst">${numbers}</span>`</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Length after shift() is : <span class="hljs-subst">${numbers.length}</span>`</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661604957811/9YjprU67F.png" alt="image.png" /></p>
<h3 id="heading-arrayunshift">Array.unshift()</h3>
<p>The <code>unshift()</code> method adds one or more elements to the beginning the array instead at the last like <code>push()</code> and like <code>push()</code> it also changes the length.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Length before unshift() is : <span class="hljs-subst">${numbers.length}</span>`</span>)
numbers.unshift(<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Array after Change: <span class="hljs-subst">${numbers}</span>`</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Length after unshift() is : <span class="hljs-subst">${numbers.length}</span>`</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661605155963/Qf3_0S_bg.png" alt="image.png" /></p>
<h3 id="heading-arrayslice">Array.slice()</h3>
<p>The <code>slice()</code> method returns a copy of the portion of an array into new array object selected from <code>start</code> to <code>end</code>, where <code>start</code> and <code>end</code> are index of the items of the array. This method does not modified the original array</p>
<p><code>slice()</code>
<code>slice(start)</code>
<code>slcie(start,end)</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>]
<span class="hljs-keyword">const</span> sliced = numbers.slice(<span class="hljs-number">2</span>,<span class="hljs-number">4</span>)
<span class="hljs-built_in">console</span>.log(numbers)
<span class="hljs-built_in">console</span>.log(sliced)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661605473691/Jo2Er9VTA.png" alt="image.png" /></p>
<h3 id="heading-arraysome">Array.some()</h3>
<p>The <code>some()</code> method tests a condition just like <code>every()</code> method but instead of matching the condition to all elements like it did in <code>every()</code>, in <code>some()</code> we just check if some elements match the condition, if some elements match then we return <code>true</code> If no element matches we return <code>false</code></p>
<pre><code class="lang-js">
<span class="hljs-keyword">const</span> isEven = <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> value%<span class="hljs-number">2</span>===<span class="hljs-number">0</span>
<span class="hljs-keyword">const</span> arr1 = [<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">6</span>,<span class="hljs-number">8</span>]
<span class="hljs-keyword">const</span> arr2 = [<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>]
<span class="hljs-keyword">const</span> arr3 = [<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>,<span class="hljs-number">7</span>]
<span class="hljs-built_in">console</span>.log(arr1.some(isEven))
<span class="hljs-built_in">console</span>.log(arr2.some(isEven))
<span class="hljs-built_in">console</span>.log(arr3.some(isEven))
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661605713380/rHOqbI1Cz.png" alt="image.png" /></p>
<h3 id="heading-arraysort">Array.sort()</h3>
<p>This method sorts the array like the name suggests, it can sort both numbers and alphabets. We can also given a sorting condition. The default sorting condition is ascending.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">34</span>,<span class="hljs-number">5</span>,<span class="hljs-number">21</span>,<span class="hljs-number">5</span>,<span class="hljs-number">2</span>,<span class="hljs-number">1</span>,<span class="hljs-number">0</span>,<span class="hljs-number">12</span>,<span class="hljs-number">45</span>]
<span class="hljs-keyword">const</span> alpha = [<span class="hljs-string">'r'</span>,<span class="hljs-string">'t'</span>,<span class="hljs-string">'v'</span>,<span class="hljs-string">'f'</span>,<span class="hljs-string">'a'</span>,<span class="hljs-string">'b'</span>]
<span class="hljs-built_in">console</span>.log(numbers.sort(<span class="hljs-function">(<span class="hljs-params">a,b</span>) =&gt;</span> a-b))
<span class="hljs-built_in">console</span>.log(alpha.sort())
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661605935054/ZzX5nnbOm.png" alt="image.png" /></p>
<h3 id="heading-arraysplice">Array.splice()</h3>
<p>This method is used to change chunks of array and resize the array while changing the original array completely. We can delete the items or change their value using splice. </p>
<p>General Syntax</p>
<p><code>splice(start, deleteCount, item1, item2, itemN)</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>]
<span class="hljs-keyword">const</span> numbers1 = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>]
numbers.splice(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>)
numbers1.splice(<span class="hljs-number">2</span>,<span class="hljs-number">2</span>,<span class="hljs-string">'a'</span>,<span class="hljs-string">'4'</span>)
<span class="hljs-built_in">console</span>.log(numbers)
<span class="hljs-built_in">console</span>.log(numbers1)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1661606156477/Xy8JmgxdF.png" alt="image.png" /></p>
]]></content:encoded></item><item><title><![CDATA[Easy Positioning with CSS Flexbox..!!!]]></title><description><![CDATA[CSS Flexbox, What is it?
Flexbox is a 1-D layout method for arranging items in rows or columns. Items expand to fill additional space or shrink to fit into smaller containers. Here we are going to discuss most of the things flexbox offers. 
Flexbox o...]]></description><link>https://blog.ashishkrjha.dev/easy-positioning-with-css-flexbox</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/easy-positioning-with-css-flexbox</guid><category><![CDATA[Learn Code Online]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Mon, 01 Aug 2022 11:26:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1659353587507/d3f2Ers8k.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-css-flexbox-what-is-it">CSS Flexbox, What is it?</h2>
<p>Flexbox is a 1-D layout method for arranging items in rows or columns. Items expand to fill additional space or shrink to fit into smaller containers. Here we are going to discuss most of the things flexbox offers. </p>
<p>Flexbox offers the same set of things provided by CSS positioning but in a much more straightforward, flexible way. The main thing we keep in mind when using the flexbox is the container and its children.</p>
<p>Let's dive in</p>
<h3 id="heading-flexbox-properties">FlexBox Properties</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659347251494/2-Kt0cI_W.png" alt="image.png" /></p>
<p>This is without the flex property. </p>
<pre><code class="lang-css"> <span class="hljs-selector-class">.container</span>{
    <span class="hljs-attribute">gap</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">display</span>: flex;
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659347362815/_nnyyHf6i.png" alt="image.png" /></p>
<p>By default, the flex-direction is row so all the elements inside the container are aligned in a row.</p>
<p>We can also add values to the <code>flex-direction</code> property</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span>{
    <span class="hljs-attribute">gap</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">flex-direction</span>: column-reverse;
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659347548976/c0QjcWCpV.png" alt="image.png" /></p>
<p><code>flex-direction</code> has 4 property values we can use. What <code>flex-direction</code> does is, it changes the axis according to the property value we assign.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659347695160/Kzzgh1Z47.png" alt="image.png" /></p>
<p>This is an image from MDN docs that gives us a better understanding of the axis.  When we used <code>flex-direction: column-reverse</code> the main axis became from <code>bottom-to-top</code> and the direction matters for the upcoming property we will be exploring. The 4 values for <code>flex-direction</code> are given below:</p>
<ul>
<li><code>column</code>:  This value places the flex items vertically, from top to bottom.</li>
<li><code>column-reverse</code>:  This value places the flex items vertically but from bottom to top.</li>
<li><code>row</code>:  This value places the flex items horizontally,  from left to right.</li>
<li><code>row-reverse</code>:  This value places the flex items horizontally but from right to left</li>
</ul>
<h3 id="heading-flex-wrap">Flex-wrap</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659349066127/2okpmjexN.png" alt="image.png" /></p>
<p>This happens when we have too many items clumped up together, to solve this issue we have <code>flex-wrap</code> because by default the flex items try to shrink and stay in the row/column so we need to add additional property to remove that skewed look.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span>{
    <span class="hljs-attribute">gap</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">flex-wrap</span>: wrap;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid red;
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659349173102/h_V-r8HCh.png" alt="image.png" /></p>
<p><code>flex-wrap</code> has 3 property value</p>
<ul>
<li><code>wrap</code> :  This will be wrap flex items in multiple lines from top to bottom</li>
<li><code>no-wrap</code> :  This property doe not affect the row in any manner</li>
<li><code>wrap-reverse</code>: This property is similar to <code>row-reverse</code> where it wraps the items but in reverse order that is bottom to top</li>
</ul>
<h3 id="heading-flex-flow">flex-flow</h3>
<p>Now that you have learned about the two properties, lets combine them with <code>flex-flow</code>
This property is combination of <code>flex-direction</code> and <code>flex-wrap</code> and the generic syntax would be <code>flex-flow: flex-direction flex-wrap</code></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span>{
  <span class="hljs-attribute">flex-flow</span>: row-reverse wrap
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659349920805/0zkAQcXQL.png" alt="image.png" /></p>
<h3 id="heading-justify-content">justify-content</h3>
<p>This is one of the property which is affected by the <code>flex-direction</code>. This property aligns the items along the main axis which is decided by the <code>flex-direction</code>. For simplicity we will be using <code>flex-direction: row</code>.</p>
<p><code>justify-content: flex-start</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659351137210/G7diGbjXp.png" alt="image.png" /></p>
<p><code>justify-content: flex-end</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659351115265/juR6vOQu5.png" alt="image.png" /></p>
<p><code>justify-content: space-between</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659351176015/FFq4k0Ull.png" alt="image.png" /></p>
<p><code>justify-content: space-around</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659351254522/U3K1h005d.png" alt="image.png" /></p>
<p><code>justify-content: space-evenly</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659351310156/U-wTIXDGp.png" alt="image.png" /></p>
<h3 id="heading-align-content">align-content</h3>
<p>This property displaces the items according to <code>cross-axis</code>. We have taken a <code>flex-direction: row</code> so in the upcoming examples the displacement will occur in y-axis.</p>
<p><code>align-content: flex-start</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659351778267/PPI8jgugK.png" alt="image.png" /></p>
<p><code>align-content: flex-end</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659351805161/HBc9lDSSJ.png" alt="image.png" /></p>
<p><code>align-content: center</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659351957612/uCOTby27L.png" alt="image.png" /></p>
<p><code>align-content: stretch</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659351987233/YIgStPWNg.png" alt="image.png" /></p>
<h3 id="heading-align-items">align-items</h3>
<p>This property aligns the flex lines. It defines how the flex items should distribute vertically on the current line.  It is for items in a single row. Major difference between <code>align-items</code> and <code>align-content</code> is that `align-content doesn't interfere with items in a row but with rows itself.  </p>
<ul>
<li><code>stretch</code>:  Flex items are stretched to take up the leftover space.</li>
<li><code>flex-start/start/self-start</code>:  Flex items are placed at the start of the vertical or cross axis.  </li>
<li><code>flex-end/end/self-end</code>:  Flex items are placed at the end of the vertical or cross axis.  </li>
<li><code>center</code>:  Flex items are placed in the center along with the cross or vertical axis.</li>
<li><code>baselines</code>:  Flex items are aligned such as their baselines align.</li>
</ul>
<h3 id="heading-other-propeties">Other Propeties</h3>
<p><code>Order</code>: This property decides the order in which elements are positioned. by default the elements have a order of 0. So, if we want to bring something to front we can assign it a lower value like <code>order:-1</code> or if we want to push something to the end we can assign it a higher value.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.blacklogo</span>{
<span class="hljs-attribute">order</span>:-<span class="hljs-number">1</span>
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659352975853/3dtwto1fAy.png" alt="image.png" /></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.redlogo</span>{
<span class="hljs-attribute">order</span>: <span class="hljs-number">6</span>
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1659353068947/61-LOPAqa.png" alt="image.png" />
In the above examples we pushed the red logo at the last by give it a higher enough value. And brought the black logo in the front by applying it an lower enough value</p>
<p><code>align-self</code>: It can be used to override the align-items by applying it to an individual element.</p>
]]></content:encoded></item><item><title><![CDATA[Git commands: A quick overview]]></title><description><![CDATA[This is a short introductory article for git commands.
Setup and Initialization
This command is used to initialize an existing folder as a git repo
git init

This is used to copy a git repo
git clone [URL]


Stage and Snapshot
Show modified files in ...]]></description><link>https://blog.ashishkrjha.dev/git-commands-a-quick-overview</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/git-commands-a-quick-overview</guid><category><![CDATA[Git Commands]]></category><category><![CDATA[cheatsheet]]></category><category><![CDATA[Learn Code Online]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Sun, 24 Jul 2022 20:01:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1659269102193/Ihv7l2wL4.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is a short introductory article for git commands.</p>
<h2 id="heading-setup-and-initialization">Setup and Initialization</h2>
<p>This command is used to initialize an existing folder as a git repo</p>
<p><code>git init</code></p>
<hr />
<p>This is used to copy a git repo</p>
<p><code>git clone [URL]</code></p>
<hr />
<hr />
<h2 id="heading-stage-and-snapshot">Stage and Snapshot</h2>
<p>Show modified files in the working directory that are staged for your next commit
<code>git status</code></p>
<p>Add a file for your next commit</p>
<p><code>git add [fileName]</code></p>
<p>to add all files</p>
<p><code>git add .</code></p>
<hr />
<p>unstaged a file while retaining the changes in the working directory</p>
<p><code>git reset [fileName]</code></p>
<hr />
<p>check the difference between what is changed but not staged</p>
<p><code>git diff</code></p>
<p>check the difference between what is staged but not yet committed</p>
<p><code>git diff --staged</code></p>
<hr />
<p>Commit staged content as a new commit snapshot</p>
<p><code>git commit -m "message"</code></p>
<hr />
<hr />
<h2 id="heading-branch-and-merge">Branch and Merge</h2>
<p>List your branches. A <code>*</code> will appear next to the currently active branch</p>
<p><code>git branch</code></p>
<hr />
<p>Create a new branch at the current commit</p>
<p><code>git branch [branch-name]</code></p>
<hr />
<p>Switch to another branch and check it into your working directory</p>
<p><code>git checkout</code></p>
<hr />
<p>merge the specified branch's history into the current one</p>
<p><code>git merge [branch]</code></p>
<hr />
<p>show all the commits in the current branch's history</p>
<p><code>git log</code></p>
<hr />
<hr />
<h2 id="heading-inspect-and-compare">Inspect and Compare</h2>
<p>show the commits on BranchA that are not in BranchB</p>
<p><code>git log branchB..branchA</code></p>
<hr />
<p>show the commit that changed file, even across renames</p>
<p><code>git log --follow [file]</code></p>
<hr />
<p>show the diff of what is in BranchA that is not in BranchB</p>
<p><code>git diff branchB..branchA</code></p>
<p>show any object in Git in human readable format</p>
<p><code>git show [SHA]</code></p>
<hr />
<hr />
<h2 id="heading-tracking-path-changes">Tracking Path Changes</h2>
<p>Delete the files from project and stage the removal for commit</p>
<p><code>git rm [file]</code></p>
<hr />
<p>change an existing file path and stage the move</p>
<p><code>git mv[existing-path][new-path]</code></p>
<hr />
<p>show all commit logs with indication of any paths that moved</p>
<p><code>git log --state  -M</code></p>
<hr />
<hr />
<h2 id="heading-share-and-update">Share and Update</h2>
<p>add a git URL as an alias</p>
<p><code>git remote add [alias][URL]</code></p>
<hr />
<p>fetch down all the branches from that git remote</p>
<p><code>git fetch [alias]</code></p>
<hr />
<p>Merge a remote branch into your current branch to bring it up to date</p>
<p><code>git merge [alias]/[branch]</code></p>
<hr />
<p>Transmit local branch commits to the remove repo branch</p>
<p><code>git push [alias][branch]</code></p>
<hr />
<p>fetch and merge any commits from the tracking remote branch</p>
<p><code>git pull</code></p>
<hr />
<hr />
<h2 id="heading-rewrite-history">Rewrite History</h2>
<p>apply any commits of current branch ahead of specified one</p>
<p><code>git rebase [branch]</code></p>
<hr />
<p>clear staging area, rewrite working tree from specified commit</p>
<p><code>git reset --hard[commit]</code></p>
<hr />
<hr />
<h2 id="heading-temporary-commits">Temporary Commits</h2>
<p>Save modified and staged changes</p>
<p><code>git stash</code></p>
<hr />
<p>list the stack-order of stashed file changes</p>
<p><code>git stash list</code></p>
<hr />
<p>write working from top of stash stack</p>
<p><code>git stash stop</code></p>
<hr />
<p>discard the changes from the top of stash stack</p>
<p><code>git stash drop</code></p>
<hr />
<p>This is pretty much all important git commands. I hope it helped. Thanks and Keep Learning!</p>
]]></content:encoded></item><item><title><![CDATA[A Quick Guide to MarkDown Syntax]]></title><description><![CDATA[What is MarkDown?
Markdown is a plain text formatting syntax that is focused on making writing on the internet easier. It can also be considered as an alternative to WYSIWYG editors. WYSIWYG is What You See Is What You Get... MarkDown files have an e...]]></description><link>https://blog.ashishkrjha.dev/a-quick-guide-to-markdown-syntax</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/a-quick-guide-to-markdown-syntax</guid><category><![CDATA[markdown]]></category><category><![CDATA[Learn Code Online]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Sun, 24 Jul 2022 17:53:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1658681320154/gxYWZh5qd.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-is-markdown">What is MarkDown?</h3>
<p>Markdown is a plain text formatting syntax that is focused on making writing on the internet easier. It can also be considered as an alternative to WYSIWYG editors. WYSIWYG is What You See Is What You Get... MarkDown files have an extension of .md. If you have worked with Github you must be familiar with it. </p>
<p>It is much easier to learn and fast to use without too many tags mussing everything up. </p>
<h1 id="heading-basic-syntax">Basic Syntax</h1>
<h2 id="heading-heading">Heading</h2>
<p>Just like in HTML heading here ranges from 1-6 with size decreasing. 
<code>#</code> followed by <code>space</code> and then <code>Heading</code>.
<code># Heading 1</code></p>
<h1 id="heading-heading-1">Heading 1</h1>
<p><code>## Heading 2</code></p>
<h2 id="heading-heading-2">Heading 2</h2>
<p><code>### Heading 3</code></p>
<h3 id="heading-heading-3">Heading 3</h3>
<h2 id="heading-bold">Bold</h2>
<p>For Bold we use <code>**</code> or <code>__</code> on both sides of the text 
<code>**Bold**</code> <code>__Bold__</code></p>
<p><strong>Bold</strong> <strong>Bold</strong></p>
<h2 id="heading-italic">Italic</h2>
<p>For Italics, we use <code>*</code> or <code>_</code> </p>
<p><em>Italic</em> <em>Italic</em></p>
<h2 id="heading-blockquote">Blockquote</h2>
<p>For blockquote, we use <code>&gt;</code> followed by <code>space</code></p>
<blockquote>
<p>BlockQuote</p>
</blockquote>
<h2 id="heading-ordered-list">Ordered List</h2>
<p>For Ordered List </p>
<pre><code class="lang-md"><span class="hljs-bullet">1.</span> First item
<span class="hljs-bullet">2.</span> Second item
<span class="hljs-bullet">3.</span> Extra
</code></pre>
<ol>
<li>First item</li>
<li>Second item</li>
<li>Extra</li>
</ol>
<p>the point here to note is that any <code>number</code> followed by <code>.</code> and <code>space</code> will get ordered serially.  Even if we write <code>9. nth item</code> the list will begin from <code>1</code></p>
<h2 id="heading-unordered-list">Unordered List</h2>
<p>Unordered List we can use <code>-</code> followed by <code>space</code></p>
<pre><code class="lang-md"><span class="hljs-bullet">-</span> First item
<span class="hljs-bullet">-</span> Second item
<span class="hljs-bullet">-</span> Third item
</code></pre>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
<h2 id="heading-code">Code</h2>
<p>Code can be written between the backticks</p>
<pre><code class="lang-md"><span class="hljs-code">`code`</span>
</code></pre>
<p>if we want a block of code we can have 3 such backticks /backquotes, and to highlight the code inside we can mention the language/format it's in right after the first 3 backquotes.</p>
<h2 id="heading-horizontal-line">Horizontal Line</h2>
<p>A horizontal line can be drawn using <code>---</code> but must have an empty line above it</p>
<hr />
<h2 id="heading-link">Link</h2>
<p>Link can be added  using </p>
<pre><code class="lang-md">[<span class="hljs-string">Youtube</span>](<span class="hljs-link">www.Youtube.com</span>)
</code></pre>
<p><a target="_blank" href="https://www.youtube.com">Youtube</a></p>
<h2 id="heading-image">Image</h2>
<p>Image Addition can also be done in the same manner but we have to add <code>!</code> before the entire line. </p>
<pre><code class="lang-md">![<span class="hljs-string">SomeName</span>](<span class="hljs-link">LinkToImage</span>)
</code></pre>
<h1 id="heading-extended-syntax">Extended Syntax</h1>
<h2 id="heading-table">Table</h2>
<p>To add a table, use three or more <code>---</code> to create each column's header, and use <code>|</code> to separate each column. </p>
<pre><code class="lang-md">| Syntax      | Description |
| ----------- | ----------- |
| Header      | Title       |
| Paragraph   | Text        |
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Syntax</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>Header</td><td>Title</td></tr>
<tr>
<td>Paragraph</td><td>Text</td></tr>
</tbody>
</table>
</div><h2 id="heading-strikethrough">StrikeThrough</h2>
<p>You can strikethrough words by putting a horizontal line using <code>~~</code> before and after the words you want to strike.</p>
<h2 id="heading-tasklists">TaskLists</h2>
<p>Task lists allow you to create a list of items with checkboxes.</p>
<pre><code class="lang-md"><span class="hljs-bullet">-</span> [x] Step one
<span class="hljs-bullet">-</span> [x] Step two
<span class="hljs-bullet">-</span> [ ] Step Three
</code></pre>
<ul>
<li>[x] Step one</li>
<li>[x] Step two</li>
<li>[ ] Step Three</li>
</ul>
<h2 id="heading-emoji">Emoji</h2>
<p>Some Markdown supports emoji as well</p>
<pre><code class="lang-md">Gone camping! :tent: Be back soon.

That is so funny! :joy:
</code></pre>
<h2 id="heading-highlighting">Highlighting</h2>
<p>Highlighting can be done using <code>==</code> on both sides of important words.</p>
<pre><code class="lang-md">I need to highlight these ==very important words==.
</code></pre>
<h2 id="heading-subscript-and-superscript">Subscript and SuperScript</h2>
<p>For Subscript we use <code>~</code> and For Superscript we use <code>^</code></p>
<pre><code class="lang-md">H~2~O
X^3^
</code></pre>
<p>This is pretty much all the features of Markdown at the time of publishing this article. The features which don't have examples using the md code are not supported by the platform as of now. 
Thanks for Reading, Keep Learning!</p>
]]></content:encoded></item><item><title><![CDATA[Positioning in CSS Positions...]]></title><description><![CDATA[CSS Positions
The most annoying part of styling is to position that one div which refuses to obey css commands. It's frustrating and mentally draining BUT why does this happen in the first place? This Article will help you understand the nature of va...]]></description><link>https://blog.ashishkrjha.dev/positioning-in-css-positions</link><guid isPermaLink="true">https://blog.ashishkrjha.dev/positioning-in-css-positions</guid><category><![CDATA[CSS]]></category><category><![CDATA[cssPositions]]></category><category><![CDATA[Learn Code Online]]></category><dc:creator><![CDATA[Ashish Kr Jha]]></dc:creator><pubDate>Sun, 24 Jul 2022 14:17:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1658671983879/ZLmziicK9.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-css-positions">CSS Positions</h2>
<p>The most annoying part of styling is to position that one <code>div</code> which refuses to obey css commands. It's frustrating and mentally draining <strong><em>BUT</em></strong> why does this happen in the first place? This Article will help you understand the nature of various positions in CSS to prevent such things from happening. 
There are various types of CSS Positions. We will cover them here. </p>
<h3 id="heading-position-static">Position Static</h3>
<p>Now this is a very common position, the default position of HTML is <code>static</code>, This position allows a normal flow of the document and displays things as they are ordered in HTML. The <code>top</code>,<code>right</code>,<code>left</code>,<code>bottom</code>, and <code>z-index</code> properties do not affect <code>position: static</code>.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"parent"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child1"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child2"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child3"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>CSS</p>
<pre><code class="lang-css">  <span class="hljs-selector-class">.parent</span>{
}
<span class="hljs-selector-class">.child1</span>{
}
<span class="hljs-selector-class">.child2</span>{
}
<span class="hljs-selector-class">.child3</span>{
}
</code></pre>
<p>OUTPUT</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1658669338290/OzufJn7nm.png" alt="image.png" /></p>
<h3 id="heading-position-relative">Position relative</h3>
<p>This position stacks on top of the position static as if it contained a <code>z-index</code> and stacks on top of the normal flow of the document. The Offset values of <code>top</code>,<code>right</code>,<code>left</code> and 
 <code>bottom</code> shows it. For example</p>
<p>HTML</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"parent"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child1"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child2"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child3"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>CSS</p>
<pre><code class="lang-css">  <span class="hljs-selector-class">.parent</span>{
}
<span class="hljs-selector-class">.child1</span>{
    <span class="hljs-attribute">position</span>: relative;
    <span class="hljs-attribute">left</span>: <span class="hljs-number">50px</span>;

}
<span class="hljs-selector-class">.child2</span>{
}
<span class="hljs-selector-class">.child3</span>{
}
</code></pre>
<p>OUTPUT</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1658669130375/XqCTzwN-u.png" alt="image.png" /></p>
<p>When we add more offset parameters</p>
<p>CSS</p>
<pre><code class="lang-css">  <span class="hljs-selector-class">.parent</span>{
}
<span class="hljs-selector-class">.child1</span>{
    <span class="hljs-attribute">position</span>: relative;
    <span class="hljs-attribute">left</span>: <span class="hljs-number">50px</span>;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">20px</span>
}
<span class="hljs-selector-class">.child2</span>{
}
<span class="hljs-selector-class">.child3</span>{
}
</code></pre>
<p>OUTPUT</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1658669100562/fKTZVrjnS.png" alt="image.png" /></p>
<p>Effect of <code>position: relative</code> on <code>table-row</code>,<code>table-column</code>,<code>table-cell</code> elements is undefined. Also, the <code>relative position</code> of the element does not affect the other elements positioned in the HTML Document</p>
<h3 id="heading-position-absolute">Position Absolute</h3>
<p>The <code>absolute</code> position removes the element from the normal flow of the document and is positioned to the closest positioned ancestor, if there is no closest ancestor it will be placed<code>relative</code> to the page. After which we can assign it the offset values of <code>top</code>,<code>right</code>,<code>bottom</code>,<code>left</code> which will decide its final position</p>
<p>HTML</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"parent"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child1"</span>&gt;</span>There is<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child2"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child3"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>CSS</p>
<pre><code class="lang-css">  <span class="hljs-selector-class">.parent</span>{
}
<span class="hljs-selector-class">.child1</span>{
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">left</span>: <span class="hljs-number">100px</span>;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">30px</span>;
}
<span class="hljs-selector-class">.child2</span>{
}
<span class="hljs-selector-class">.child3</span>{
}
</code></pre>
<p>OUTPUT</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1658670558330/YTCihuOK6.png" alt="image.png" />
As you can see the <code>child1</code> has been aligned according to the page and not according to its parent div. And the behavior of other elements is as if the <code>child1</code> didn't exist.</p>
<h3 id="heading-position-fixed">Position Fixed</h3>
<p>This is very similar to the <code>absolute</code> position as it will also be removed from the flow of the document/page. But <code>fixed</code> will always be relative to the document and is unaffected by scrolling. For example in the above HTML</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.parent</span>{
}
<span class="hljs-selector-class">.child1</span>{
    <span class="hljs-attribute">position</span>: fixed;
    <span class="hljs-attribute">left</span>: <span class="hljs-number">100px</span>;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">30px</span>;
}
<span class="hljs-selector-class">.child2</span>{

}

<span class="hljs-selector-class">.child3</span>{

}
</code></pre>
<p>OUTPUT</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1658671030432/BHSPrGAyM.png" alt="image.png" /></p>
<p> In the sample, you can see that even when scrolling the child1 has maintained its position according to the offset value as it is sticking to the document. It can be used to create floating elements that are always in the viewport</p>
<h3 id="heading-position-sticky">Position Sticky</h3>
<p>This is a very unique position, <code>sticky</code> can be considered as a hybrid of the <code>relative</code> and <code>fixed</code> position. Until we reach the end of the viewport it acts as if it were relative and as soon as we cross the threshold of the viewport when scrolling, it starts behaving like a <code>fixed</code>. It requires at least one of the offset values to stick to.</p>
<p>This brings us to the end of our learning journey with CSS Position. Hope the article helped you. Thanks and Keep Learning</p>
]]></content:encoded></item></channel></rss>