How Google Bot Crawls JavaScript [2025]

Ever wondered how Google turns your lovingly handcrafted website into a ranking somewhere below a Reddit thread from 2013? It’s not magic, it’s just a long queue of tiny robot librarians fetching HTML, executing JavaScript, and occasionally having nervous breakdowns when they hit your React app.

This is the life cycle of a webpage inside Google’s digestive system: crawl, render, index, panic. Let’s go step by step before your sitemap starts crying.

1. Crawling: getting the raw HTML

1.1 URL discovery & crawl queue

Googlebot first has to discover your URLs. That can happen via:

  • Links from other pages
  • XML sitemaps
  • Manual submit / “Inspect URL → Request indexing” in Search Console
  • Other Google systems (e.g. feeds, previous crawls)

Discovered URLs go into a crawl queue with priority based on things like page importance and your site’s crawl budget.

1.2 robots.txt and basic checks

Before requesting the URL, Googlebot:

  1. Fetches robots.txt
  2. Checks if the URL (and key resources like JS/CSS) are allowed
  3. Applies host load limits and crawl budget rules

If the page or important JS/CSS files are blocked in robots.txt, Google:

  • Won’t crawl them
  • Won’t be able to fully render your JS content later

Practical implication: Never block /js/, /static/, /assets/, etc. in robots.txt.

1.3 Fetching the HTML (“first wave”)

Googlebot makes a normal HTTP request (like a browser without UI):

  • Gets the initial HTML (without having run JS yet)
  • Parses head tags (title, meta description, canonical, meta robots, hreflang, etc.)
  • Extracts links from the HTML and adds them to the crawl queue
  • Notes references to resources (JS, CSS, images)

At this stage, only what’s in the raw HTML is visible. If your content is 100% client-side rendered (React, Vue, etc.), Google might see almost nothing yet.

Google can sometimes do basic indexing directly from the HTML (e.g. if content is already there), but JS-heavy pages need the next phase.


2. Rendering: running your JavaScript

Google describes the JS pipeline as: Crawling → Rendering → Indexing. Rendering happens in a separate system using an evergreen version of Chromium (a headless Chrome kept relatively up-to-date) called the Web Rendering Service.

2.1 The render queue (“second wave”)

After the initial crawl:

  1. Google adds the page to a render queue.
  2. When resources allow, that queue feeds URLs into the rendering system.
  3. Until rendering happens, Google only “knows” what was in the raw HTML.

This is why people talk about “two waves of indexing” for JavaScript:

  • Wave 1: Index from HTML (if possible)
  • Wave 2: Index updated content after JS has run

Modern research suggests the process is smoother and faster than years ago, but there is still a render queue and potential delay for JS content.

2.2 How Google’s renderer behaves

When a page reaches the renderer:

  1. Google loads it in an evergreen Chromium environment (no UI).
  2. It fetches JS, CSS, and other resources (subject to robots.txt, CORS, etc.).
  3. It executes JavaScript for a limited amount of time (shorter than a user session).
  4. JS can:
    • Modify the DOM
    • Inject content
    • Fetch JSON/XHR/data and add it to the page
    • Add structured data (application/ld+json) dynamically

Important constraints (from Google’s docs & tests):

  • No user interactions: Google doesn’t click, type, or scroll like a user.
  • Time limits: Long chains of async calls may never complete before the renderer stops.
  • Resource limits: Heavily blocking scripts or endless network calls can break rendering.
  • “Noindex = no render” effect: If a page is noindex, Google generally won’t bother rendering it.

2.3 Post-render snapshot

Once JS finishes (or time runs out), Google:

  1. Takes the final DOM snapshot (what a user would see after JS).
  2. Extracts:
    • Visible text content
    • Links added by JS (e.g. SPA navigation)
    • Structured data present in the DOM
    • Meta tags if they are changed or added by JS

This rendered snapshot is what feeds into the real indexing stage.


3. Indexing: storing & scoring the rendered content

With the rendered HTML/DOM in hand, Google moves to indexing.

3.1 Understanding the content

From the rendered DOM, Google:

  • Tokenizes and stores text (words, phrases, headings).
  • Maps entities, topics, and relationships.
  • Reads links (anchor text + target URL) added by your JS navigation.
  • Parses structured data (schema.org, etc.) that JS may have injected.

This is the version of the page that can now rank for queries matching that content.

3.2 Canonicals, duplicates & signals

Indexing also handles:

  • Canonical selection (HTML tags, redirects, link signals).
  • Duplicate / near-duplicate detection, especially if JS rewrites similar pages.
  • Applying meta robots and HTTP headers from the final state after JS (for most cases).

If Google decides another URL is the canonical, your rendered JS content might be stored but not shown as the main result.

3.3 Final result: searchable document

After indexing, the document is:

  • Stored in Google’s index with:
    • Content (from rendered DOM)
    • Links
    • Structured data
    • Various quality & relevance signals
  • Ready to be retrieved and ranked when a user searches for related queries.

4. Where JavaScript sites usually break this flow

Because JS adds extra moving parts, a bunch of things can go wrong between crawl → render → index:

  1. Blocked JS/CSS in robots.txt
    Google can’t render layout or content if the files are disallowed.
  2. Content only after interaction
    If key text appears only after a click/scroll or in a modal that never opens, Google won’t see it.
  3. Too slow or broken rendering
    Heavy JS, long waterfalls, or failing XHR calls mean the DOM never contains the content when Google takes the snapshot.
  4. Infinite scroll / SPA routing without proper URLs
    If content is loaded endlessly on one URL without crawlable links or pagination (e.g. no ?page=2, no anchor links), Googlebot may only see the initial “page”.
  5. Client-side only structured data that doesn’t materialise in time
    If JS injects JSON-LD but too slowly (or fails), rich results won’t trigger.

5. How to see what Google sees (JS-specific)

To understand how your JS is being processed:

  • Use URL Inspection“View crawled page” & “Screenshot” in Search Console to see the rendered DOM.
  • Compare “HTML” vs “Rendered HTML” to spot what content only appears post-JS.
  • Use “Test live URL” if you suspect render-queue delay.
  • Check Coverage / Pages report for “Crawled – currently not indexed” patterns that often show render/index issues.

So there you have it — from lazy bots fetching half your HTML to a headless Chrome pretending to be a real user for 0.3 seconds. Somewhere in that chaos, your content might actually get indexed.

If your JavaScript site isn’t showing up, don’t blame Google just yet — try unblocking your own files and giving the crawler half a chance. Think of it as SEO mindfulness: eliminate obstacles, breathe deeply, and let the bots eat your content in peace.


Explained in simpler terms – How Googlebot Crawls Javascript –

Stage 1 – Discovery & Crawling: “Finding your page and grabbing the first copy”

1. Google finds your URL

Google finds pages from things you already know:

  • Links on other sites
  • Your internal links
  • Your XML sitemap
  • Stuff you submit in Search Console

It puts those URLs in a big to-do list (crawl queue).


2. robots.txt check

Before visiting a URL, Google checks your robots.txt file:

  • If the page or important files (JS/CSS) are blocked, Google is basically told: “Don’t look here.”
  • If they’re allowed, it moves on.

Simple rule for you:
Never block your JS/CSS folders in robots.txt.


3. Google downloads the HTML (Wave 1)

Google now requests the page, just like a browser:

  • It gets the basic HTML (before any JavaScript runs).
  • From that HTML it grabs:
    • Title, meta description, canonical, meta robots, etc.
    • Any plain text that’s already there
    • Links to other pages
    • Links to JS/CSS/images

At this point, Google has not run your JavaScript yet.

If your important content is already in the HTML (e.g. server-side rendered), Google can often index it right away from this “first wave”.


Stage 2 – Rendering: “Actually running your JavaScript”

Now Google needs to know what your page looks like after JS runs – like a real user would see it.

Because this is heavy work, Google doesn’t do it instantly for every URL.

4. Render queue (waiting line)

After the first crawl, JavaScript pages go into a render queue:

  • Think of it like: “We’ve saved the HTML. When we have time, we’ll come back and run the JS.”

So for a while, Google might only know the bare HTML version of your page.


5. Headless Chrome renders the page

When your page reaches the front of the queue, Google loads it in something like Chrome without a screen (headless browser).

This browser:

  • Downloads JS/CSS (if not blocked)
  • Executes the JS for a short amount of time
  • Lets JS:
    • Change the DOM (the page structure)
    • Insert more text
    • Add more links
    • Inject structured data (JSON-LD)

Then it takes a snapshot of the final page – the “after JS” version.

This is basically:

“What a user would see if they opened your page and waited a bit.”


6. Things that can go wrong here

This is where JS sites often break:

  • Blocked JS/CSS → Google can’t see the layout or content properly.
  • Very slow JS → content appears after Google stops waiting.
  • Content only after a click/scroll → Google doesn’t usually click buttons or scroll like a human.
  • Broken scripts / errors → content never appears at all.

Result: Google’s snapshot may miss your main content.


Stage 3 – Indexing: “Filing your page in the library”

Now Google has:

  • Version 1: HTML-only (first wave)
  • Version 2: Rendered DOM (after JS runs)

7. Understanding the rendered page

From the rendered snapshot Google:

  • Reads all the visible text
  • Sees headings and structure
  • Follows any extra links added by JS
  • Reads structured data (schema)
  • Applies canonical tags / meta robots, etc.

This updated information is used to update your page in the index (second wave).


8. Search results

When someone searches:

  1. Google looks through its index of pages (which contains that rendered version).
  2. It decides which pages are most relevant.
  3. It shows your URL in the results.
  4. When the user clicks it, they go to your live site, not to Google’s stored copy.

Quick “JS SEO” checklist for you

If you remember nothing else, remember these:

  1. Can I see my main content in the raw HTML?
    • If yes → you’re mostly safe (e.g. SSR or hybrid).
    • If no → you’re relying heavily on rendering; be extra careful.
  2. Are JS & CSS allowed in robots.txt?
    • They should be.
  3. Does important content require a click/scroll?
    • Try to have key text and links visible without interaction, or use proper URLs for loaded content.
  4. Is the page reasonably fast?
    • If it takes ages for content to appear, Google may bail before seeing it.
  5. Use Search Console’s URL Inspection → “View crawled page”
    • Compare:
      • HTML Google saw
      • Rendered HTML
    • If you don’t see your text in the rendered version → that’s a problem.

eCommerce Structured Data

E-commerce Example for Structured Data Carousels

Below are step by step instructions

You will need:

  • A “summary” or “Product Listings Page” with structured data
  • Structured data on the product pages themselves

At the time of writing, this feature is only available in EU countries.

Step 1: Choose and Implement a Summary Page

Create a summary page that lists multiple products, each linking to a detailed product page.

For example, a category page that lists “Top 5 Winter Coats.”

Step 2: Add Required Properties to the Summary Page

Add the ItemList structured data to your summary page. Here’s an example in JSON-LD format:

<html>
  <head>
    <title>Top 5 Winter Coats</title>
    <script type="application/ld+json">
      {
        "@context": "https://schema.org",
        "@type": "ItemList",
        "itemListElement": [
          {
            "@type": "ListItem",
            "position": 1,
            "item": {
              "@type": "Product",
              "name": "Puffy Coat Series by Goat Coat",
              "image": [
                "https://example.com/photos/1x1/photo.jpg",
                "https://example.com/photos/4x3/photo.jpg",
                "https://example.com/photos/16x9/photo.jpg"
              ],
              "offers": {
                "@type": "AggregateOffer",
                "lowPrice": 45.00,
                "highPrice": 60.00,
                "priceCurrency": "USD"
              },
              "aggregateRating": {
                "@type": "AggregateRating",
                "ratingValue": 4.9,
                "reviewCount": 50
              },
              "url": "https://www.example.com/puffy-coats"
            }
          },
          {
            "@type": "ListItem",
            "position": 2,
            "item": {
              "@type": "Product",
              "name": "Wool Coat Series by Best Coats Around",
              "image": [
                "https://example.com/photos/1x1/photo.jpg",
                "https://example.com/photos/4x3/photo.jpg",
                "https://example.com/photos/16x9/photo.jpg"
              ],
              "offers": {
                "@type": "AggregateOffer",
                "lowPrice": 189.00,
                "highPrice": 200.00,
                "priceCurrency": "USD"
              },
              "aggregateRating": {
                "@type": "AggregateRating",
                "ratingValue": 4.7,
                "reviewCount": 827
              },
              "url": "https://www.example.com/wool-coats"
            }
          },
          {
            "@type": "ListItem",
            "position": 3,
            "item": {
              "@type": "Product",
              "name": "Antarctic Coat by Cold Coats",
              "image": [
                "https://example.com/photos/1x1/photo.jpg",
                "https://example.com/photos/4x3/photo.jpg",
                "https://example.com/photos/16x9/photo.jpg"
              ],
              "offers": {
                "@type": "Offer",
                "price": 45.00,
                "priceCurrency": "USD"
              },
              "aggregateRating": {
                "@type": "AggregateRating",
                "ratingValue": 4.9,
                "reviewCount": 1290
              },
              "url": "https://www.example.com/antarctic-coat"
            }
          }
        ]
      }
    </script>
  </head>
  <body>
  </body>
</html>

Step 3: Validate Your Code

  1. Rich Results Test: Validate your structured data using the Rich Results Test.
  2. URL Inspection Tool: Use the URL Inspection tool in Google Search Console to ensure your page is accessible and not blocked by robots.txt or noindex tags.

Step 4: Deploy Your Page

  1. Deploy your summary page and a few detail pages.
  2. Use the URL Inspection tool to request indexing of your new pages.

Step 5: Submit a Sitemap

  1. Create a sitemap including your summary and detail pages.
  2. Submit the sitemap through Google Search Console to ensure Google knows about all your pages.

Step 6: Follow Guidelines

  1. Ensure compliance with Search Essentials.
  2. Adhere to general structured data guidelines and specific requirements for carousel rich results.

Example Detail Pages

Each product linked from the summary page should have its own detail page with structured data. For example:

<html>
  <head>
    <title>Puffy Coat Series by Goat Coat</title>
    <script type="application/ld+json">
      {
        "@context": "https://schema.org",
        "@type": "Product",
        "name": "Puffy Coat Series by Goat Coat",
        "image": [
          "https://example.com/photos/1x1/photo.jpg",
          "https://example.com/photos/4x3/photo.jpg",
          "https://example.com/photos/16x9/photo.jpg"
        ],
        "description": "A stylish and warm puffy coat perfect for winter.",
        "offers": {
          "@type": "Offer",
          "price": 45.00,
          "priceCurrency": "USD",
          "url": "https://www.example.com/puffy-coats"
        },
        "aggregateRating": {
          "@type": "AggregateRating",
          "ratingValue": 4.9,
          "reviewCount": 50
        }
      }
    </script>
  </head>
  <body>
  </body>
</html>

That should be it!



What is Optional Chaining in JavaScript? (2023)

I asked Chat GPT to explain optional chaining in JavaScript to me like I’m 5:

Alright kiddo, imagine you have a big toy box. Inside this toy box, there are smaller boxes, and inside those, even smaller boxes. Some boxes might be empty, and others might have a toy or another smaller box inside.

Let’s say you want to find a tiny toy car, but you’re not sure which box it’s in. You start with the big toy box, then you open a smaller box inside, and then another one, and so on, until you either find the toy car or reach an empty box.

But there’s a problem. What if you try to open a box and there’s no box inside? You can’t keep looking, right? You’d stop there and say, “Oops! There’s no box here to open.”

In JavaScript, when you want to access something deep inside an object (like our big toy box), you might run into a similar problem. The thing you’re looking for might not be there, and if you try to access it, you’ll get an error.

JavaScript’s optional chaining is like a magic tool that helps with this. Instead of going box by box, and risking an error if something isn’t there, optional chaining lets you say, “Hey, if there’s a box here, open it. If not, that’s okay, just tell me there’s nothing there.”

In code, it looks like this:

let toy = bigToyBox?.smallBox?.tinyBox?.toyCar;

If any of the boxes don’t exist, JavaScript won’t get mad. It’ll just say undefined, meaning “I didn’t find it.” And that’s how optional chaining keeps our toy search safe and error-free!

Optional chaining is an operation in JS that let’s us access values, inside of an object.

Being able to use ?. – allows you to optionally chain things.

It will only try to access the nested value, if the first value existed.

if something doesnt’ exist – it will just return “undefined”

The optional chaining is helpful when working with a database and lots of data, so that you don’t have to manage a load of “if statements”

Optional chaining is a convenient way to access values inside of objects, when working with dynamic data its important that you avoid errors and crashing. Optional chaining can help with this!

Rest Pattern & Parameters JavaScript [2023] Explained like I’m 10

Rest paramaters are represented by 3 dots and then an array name

rest parameter

It is very similar to the spread operator – using the same symbol – 3 dots.

However, the rest pattern is used within a function’s parameters

Say you have a function called sum, with 2 parameters – a + b

But we add a third argument – the third argument will normally be ignored.

Using the rest parameter, as shown below, you can now store all the arguments, into an array, named “args”

Now rewrite the funcition, with a loop and you can write any amount of arguments and they will be added:

I asked Chat GPT to explain the rest parameter to me like I’m 10:

Imagine you and your friends are at an ice cream shop. There are lots of flavors to choose from.

Now, think of a JavaScript function as the ice cream shop owner. When you order your ice cream, you might say “I want chocolate, vanilla, and strawberry.” But your friends might order different flavors or a different number of scoops.

To handle this, the shop owner (our JavaScript function) uses a special bucket, called the “rest” parameter. No matter how many flavors you and your friends order, they all go into this same bucket.

In JavaScript, this is like when a function uses “…args” as a parameter. For example:

function orderIceCream(...flavors) { console.log(flavors); }

Here, ‘flavors’ is our special bucket. If you call orderIceCream("chocolate", "vanilla", "strawberry"), the function will print ["chocolate", "vanilla", "strawberry"]. And if your friend calls orderIceCream("mint", "rocky road"), the function will print ["mint", "rocky road"]. No matter how many flavors (or arguments) you give the function, they all get collected into the ‘flavors’ array. That’s the magic of the rest parameter!

One important thing to remember is that the rest parameter (...flavors in our example) should always be the last parameter in your function, because it’s like the shop owner’s “catch-all” bucket for all remaining ice cream flavors you order.

I hope that makes sense! Let me know if you have any other questions about JavaScript.

New Logical Assignment Operators (2023)

Well, these were introduced in 2021, according to the Udemy course I am doing.

the “=” sign, assigns values to things

When there’s additional stuff, before the “=”, like “&&”; then some kind of logic has to be fulfilled before anything is assigned.

Two vertical lines, or pipes – “||” are the “OR” operators

Logical AND Assignment (&&=)

This logical assignment operator only assigns the value if the left-hand side is truthy.

In JavaScript, two ampersands (&&) in an assignment operator form a Logical AND assignment operator (&&=). This is a newer addition to JavaScript, introduced in ES2021.

Here’s how it works:

Let’s say we have two variables, a and b.

If we write a &&= b;, it is a shorter way of saying:

If a is truthy, let’s assign the value of b to a.

If a is falsy, keep a as it is.”

A “truthy” value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy—i.e., except for false, 0, -0, 0n, "", null, undefined, and NaN.

So, &&= is checking if the first value is truthy and if so, it assigns the second value to the first one. If the first value is falsy, it remains unchanged.

Screenshot from Geeksforgeeks

Logical OR Assignment (||=)

This logical assignment operator only assigns the value if the left-hand expression is falsy.

This can be useful in cases where we want to keep the existing value if it does not exist, otherwise we want to assign a default to it. 

The Logical OR Assignment (||=) is a shorthand way of performing a logical OR operation and an assignment in one step. This operator was introduced in JavaScript with the ES2021 specification.

Here’s a simple way to understand it:

Let’s say we have two variables, a and b. If we write a ||= b;, it’s a shorter way of saying: “If a is not truthy (meaning it’s false, null, undefined, 0, NaN, or an empty string ”), then assign the value of b to a. If a is truthy (meaning it has any value other than those falsy values), then keep a as it is.”

So, a ||= b; is essentially a shortcut for a = a || b;.

The Logical OR Assignment (||=) operator is a handy tool when you want to assign a default or fallback value to a variable if the initial value of the variable is not truthy.

screenshot source

Logical Nullish Assignment (??=)





I asked Chat GPT to explain the operator to me like I’m 10:

Alright kiddo, let’s have a little chat about this nifty tool in JavaScript called the Nullish Coalescing Assignment Operator, which is represented by ??=. Sounds pretty fancy, huh? Don’t worry, we’ll make it fun!

Imagine you’re playing a game of football with your mates. Now, you always need a ball to play, right? But sometimes, you might forget to bring your own ball to the game. In comes the Nullish Coalescing Assignment operator to save the day.

So, let’s say myBall is the ball you bring, and spareBall is a ball that’s always kept at the ground just in case. Now, you want to check if you’ve brought your ball. If you have, great, we use your ball (myBall) for the game. But, if you forgot your ball (meaning myBall is null or undefined), we then use the spareBall.

In JavaScript, we’d write this check as myBall ??= spareBall;. This means, “If I forgot my ball (myBall), let’s use the spareBall.”

So that’s it, bachgen (that’s ‘boy’ in Welsh)! The Nullish Coalescing Assignment Operator is like your safety net, always making sure you have a ball to kick around!

Screenshot from WisdomGeek

Logical Assignment OperatorsLogical Operators
x ||= yx || (x = y)
x &&= yx && (x = y)
x ??= yx ?? (x = y);

Nullish coalescing operator (??) in JavaScript (2023)

I asked chat GPT to explain the Nullish coalescing operator (??) to me, like I’m 10 years old:

Let’s imagine you have two boxes, one is called ‘boxA’ and the other is ‘boxB’.

Now, you’re told you can take a toy from boxA, but here’s the thing, sometimes boxA can be empty. If boxA is empty, you’re allowed to take a toy from boxB instead.

In JavaScript, this is what the nullish coalescing operator (??) does. If the value on its left side (boxA) is “null” or “undefined” (it’s empty), it’ll give you the value on the right side (boxB).

Let’s look at this in code:

let boxA = null;
let boxB = "Dinosaur Toy";

let myToy = boxA ?? boxB;
console.log(myToy);  // This will print: Dinosaur Toy

In this example, ‘boxA’ is null (it’s empty), so we move to ‘boxB’ and take the “Dinosaur Toy”.

But what if ‘boxA’ does have a toy?

let boxA = "Robot Toy";
let boxB = "Dinosaur Toy";

let myToy = boxA ?? boxB;
console.log(myToy);  // This will print: Robot Toy


Here, ‘boxA’ has a “Robot Toy”, so we take that and ignore what’s in ‘boxB’. It’s just like the rule we set at the start, we only check ‘boxB’ if ‘boxA’ is empty!

I hope that helps explain the nullish coalescing operator!

Notes from this video^

This operator works like the logical “or”, but is more strict

In this scenario, at the start of a game, the user has to provide the level of difficulty they want, and they also have the option of stating/providing at starting cash amount.

In this code, if they don’t provide a starting cash amount, they’ll get “500”

So the default for the “cash” is 500

If the user does provide a cash amount, then that gets used instead of the default.

Short Circuiting in JavaScript (2023)

I asked Chat GPT to explain Short Circuting in JavaScript to me like I was 10.
I also asked for some jokes to be thrown in the mix.

“Hey there kiddo! You know how when you’re playing video games and there’s a super long level, but you discover a secret shortcut and skip straight to the end? Well, that’s kinda what we do in Javascript with something called “Short Circuiting”.

We use two super cool signs, “&&” and “||“.

Okay, first let’s talk about the two “ands” – “&&”. It’s like you and your best friend are on a secret mission. You both need to do your parts for the mission to be successful. If one of you fails, the mission fails. In Javascript, both sides of “&&” must be true for the whole thing to be true.

If the first part is false, Javascript doesn’t even bother to check the second part, because it already knows the mission failed! (this is the short-circuiting – it just quits)

Now, let’s talk about the two “ors” – “||“. This is like saying, you can have an ice cream OR a cake for dessert. If you get ice cream, that’s great! You don’t need the cake anymore (although, cake is always good).

Similarly, in Javascript, if the first part of “||” is true, Javascript takes the shortcut and doesn’t bother checking the second part.

Here’s a geeky joke for you: Why don’t programmers like nature? It has too many bugs! And don’t forget, always be like Javascript’s “&&” and “||”. Take the shortest path and save your energy for more video games! 😉”

Yea, so after reading that, I’m none the wiser, so here’s some notes from a video that I found on YouTube…

If price is more than 500 and less than 2000

Then print “hello”

If both operands are true, then print hello.

The “short circuit” occurs, because if the first parameter is not true, then JavaScript won’t bother running the second one.

So if the price was 400, and wasn’t greater than 500, then the JS would stop running and not bother to evaluate if the price is also less than 2000

It’s the same with the “or” operands, or operators, whatever they are called.

If the first condition is true, then it won’t bother running or looking at the second one, because with the “or” operator, only one of them has to be true.

Rest Pattern and parameters in Javascript

https://www.udemy.com/course/the-complete-javascript-course/learn/lecture/22648543#learning-tools

I asked Chat GPT to explain the rest pattern and parameters in JS to me, like I was 11, and to add some welsh slang:

“Alright, kiddo, let’s chat about Rest Pattern and Parameters in JavaScript, tidy la?

It’s like when you’re at a sweet shop, and they’ve got all these fab sweets – Choc bars, bonbons, chewy toffees, and so on. But you don’t want to pick ’em all up one by one, do you? That’d take ages, innit? Instead, you want to scoop ’em up all at once, don’t you?

Well, in JavaScript, we’ve got this clever trick called the Rest Pattern. It’s like that sweetie scoop. Instead of grabbing arguments one by one, you can grab all of them at once. You can see this Rest Pattern when you see ‘…’ before a variable, like this: function fun(...args) { }. The ‘args’ here is like our sweetie bag, it’s holding all the arguments that were scooped up.

Now, these Rest Parameters, they’re proper tidy! Because all those arguments are now in one bag (or in an array, as we say in JavaScript), you can do things to the whole lot of them at once – like adding, subtracting, or whatever else you fancy.

So, remember, next time you want to scoop up a load of arguments in one go, the Rest Pattern and Parameters are your best mates, alright? Proper job, bach!”

Here’s some notes from medium and geekforgeeks

The rest parameter, introduced in ES2015 or ES6, provides an enhanced method to handle function parameters. This makes it easier to manage a varying number of inputs as parameters in a function. A rest parameter lets us represent an indefinite number of arguments as an array, meaning a function can be called with any number of arguments, regardless of its original definition.

The syntax looks like this:

// '...' represents the rest parameter
function functionname(...parameters) {
  // function statement;
}


Notice when ‘…’ is at the end of the function parameters, it’s recognized as the rest parameter and stores any number of parameters as an array.

For example, let’s say we have a function without a rest parameter:

function fun(a, b){
    return a + b;
}
console.log(fun(1, 2)); // Outputs: 3
console.log(fun(1, 2, 3, 4, 5)); // Outputs: 3 

In this case, we can pass more arguments than defined parameters without causing errors. However, only the first two arguments are evaluated. The rest parameter changes this by allowing us to collect any number of arguments into an array:

// Example using the rest parameter
function fun(...input){
    let sum = 0;
    for(let i of input){
        sum += i;
    }
    return sum;
}
console.log(fun(1,2)); // Outputs: 3
console.log(fun(1,2,3)); // Outputs: 6
console.log(fun(1,2,3,4,5)); // Outputs: 15 

Now, every argument is included when we call the ‘fun()’ function. The sum of all array elements is calculated using the ‘for..of’ loop.

Remember, the rest parameter must always be the last argument in a function, as it collects all remaining arguments into an array.

Here’s an example where the rest parameter is used with other arguments:

function fun(a,b,...c){
    console.log(`${a} ${b}`);
    console.log(c);
    console.log(c[0]);
    console.log(c.length);
    console.log(c.indexOf('Lionel'));
}
fun('Mukul','Latiyan','Lionel','Messi','Barcelona');

Output:





In this example, the rest parameter is passed as the third parameter. The first two arguments are treated normally, while the rest are collected by the rest parameter. Because the rest parameter produces an array, we can apply array methods provided by JavaScript.

The Spread Operator in JavaScript (explained in cockney)

TLDR; – The Spread operator allows you to join strings or arrays together in one longer string or array

Image from Reddit

Good tutorial here

Right, guv’nor! Picture this. You’ve got yourself a box of LEGOs, like? Now in the world of JavaScript, this box is what we’d call an array. It’s a list of things, sorted and lined up all proper like.

Now, suppose you have another bigger box, crammed full of all sorts of knick-knacks. You fancy bunging your LEGOs in there, but not as a separate box. Nah, you want to spread ’em out so each LEGO is jumbled up with the other toys.

This is what the JavaScript spread operator is all about. It’s like taking your box of LEGOs and tipping ’em into the larger toy box.

Here’s a little squiz:

let legos = ['red', 'blue', 'green'];
let otherToys = ['doll', 'car', ...legos, 'ball'];

console.log(otherToys); 
// Output: ['doll', 'car', 'red', 'blue', 'green', 'ball']

In this case, ...legos is using the spread operator. It’s like we’re tipping out all the LEGO pieces (each colour) into the otherToys array. Job’s a good ‘un!

So the spread operator ... in JavaScript is like spilling the beans, it pulls all elements from an array (or all properties from an object), and scatters them into something else.

And remember, this operator doesn’t muck about with the original array (or your LEGO box). It’s like taking the LEGO pieces out for a bit of a lark. The original LEGO box is still there, untouched. Bob’s your uncle, Fanny’s your aunt!

Here are some other notes I’ve robbed from other websites (with references back to um tho)

Programiz.com

Spread Operator

The spread operator ... is used to expand or spread an iterable or an array. For example,

const arrValue = [‘My’, ‘name’, ‘is’, ‘Jack’];

console.log(arrValue); // [“My”, “name”, “is”, “Jack”]
console.log(…arrValue); // My name is Jack

In this case, the code:

console.log(...arrValue)

is equivalent to:

console.log('My', 'name', 'is', 'Jack')

Copy Array Using Spread Operator

You can also use the spread syntax ... to copy the items into a single array. For example,

const arr1 = ['one', 'two'];
const arr2 = [...arr1, 'three', 'four', 'five'];

console.log(arr2); 
//  Output:
//  ["one", "two", "three", "four", "five"]

You can run the code in the programiz code runner thing here

codingsumit

JavaScript Loops – Looping Backwards & Loops in Loops

Notes taken from The Complete JavaScript Course 2023: From Zero to Expert! course on Udemy.

Why would you use a for loop?

I asked Chat GPT this very question, and got this answer:

In JavaScript, a “for” loop is a control flow statement that allows you to execute a block of code a certain number of times. The “for” loop includes initialization, a condition, and incrementation/decrementation.

Here are some reasons and scenarios for using a “for” loop:

  1. Iterating over arrays: You might use a “for” loop when you need to iterate over an array of elements. Each loop iteration corresponds to one element in the array, so you can do something with each individual item.
    Example:
    let arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); // prints each element of the array }
  2. Repetitive tasks: You would use a “for” loop when you need to perform a task a certain number of times. The “for” loop is a straightforward way to repeat a task.

    Example:
    for (let i = 0; i < 10; i++) { console.log(i); // prints numbers 0 to 9 }
  3. Traversing strings: Similar to arrays, you can use a “for” loop to traverse each character in a string.

    Example:
    let str = "Hello, World!"; for (let i = 0; i < str.length; i++) { console.log(str[i]); // prints each character in the string }
  4. Nested loops: You can use “for” loops inside other “for” loops when dealing with multi-dimensional data, such as a matrix or 2D array.
    Example:
    let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { console.log(matrix[i][j]);
    // prints each element in the matrix } }

Please note that while “for” loops are a classic control flow mechanism, there are other methods in JavaScript for similar use-cases, especially for arrays. This includes methods like Array.prototype.forEach, Array.prototype.map, Array.prototype.filter, and others, which might provide cleaner and more readable code in some scenarios. However, understanding the workings of a “for” loop is fundamental for programming in JavaScript and many other languages.

What are for loops?

Loops, by default, start at the beginning of an array, and work forwards, from variable/element 0 to element 10 – if an array has 10 elements.

Loops can also start at the end, say element 10 and work back to the first element.

for (let i = arrayname.length - 1; i>=0; i--)

In the code above.
The counter called “i” will keep running along as the variable/element is greater than or equal to 0 (the variable number, as in it’s order starting from 0)

Every time the loop runs, instead of adding 1 to “i”, subtract 1.

To print the current element to the console.log, the code should be:

for (let i = arrayname.length - 1; i>=0; i--) {
console.log(jonas[i]);
}

This image from kodify.net explains the parts of a standard for loop quite nicely

for loop

Loop inside a Loop

Loops within loops, are sometimes called “nested loops”.

Image Source

With a nested loop, the outer loop executes first, and the inner loop executes each time the outer loop executes.

If condition 1 is true, then condition 2 will execute.

For a much better explanation, please visit the educba.com website here.

Oh, one more thing that might be useful, I asked Chat GPT to explain for loops like I’m 10 years old:

“Imagine you have a big box of Lego blocks, and you want to look at each block one by one. You would start from the first block, then move to the second, then the third, and so on, until you’ve seen all the blocks. A “for” loop in JavaScript is like doing that – it’s a way for your computer to look at or do something with each item in a list, one at a time, from start to finish.

Here’s a real-life example:

Let’s say you’re on a website that shows all the movies currently playing in theaters. When the website wants to show you all the movie names, it might have a list (in programming, we call this an array) of all those movies. But how does it get from a list of movies to showing each one on your screen? It can use a “for” loop!

In the code of the website, it might look something like this:

let movies = ["Toy Story 4", "The Lion King", "Frozen 2", "Star Wars: The Rise of Skywalker"]; // This is the list of movies.

for (let i = 0; i < movies.length; i++) {
  console.log(movies[i]); // This will show each movie name, one after the other.
}

In this example, i is like a pointer that starts at the beginning of the list (0) and moves one step forward each time the loop runs (i++). The loop keeps going as long as i is less than the length of the list (i < movies.length). And in each loop, movies[i] is how we access each movie name.

This “for” loop helps the website to go through every movie in the list and do something with it – like showing it on your screen!”