≡ Menu

Loops are a fundamental concept in programming, allowing you to execute a block of code repeatedly.

Instead of writing the same code over and over, loops help you automate repetitive tasks efficiently.

In JavaScript, there are several types of loops, each suited for different situations.

1. The for Loop: The Go-To Repeater

The for loop is the most common and generally the most structured loop.

It’s perfect when you know exactly how many times you want the loop to run (e.g., iterating through an array or counting to a specific number).

Structure

The for loop has three main expressions inside its parentheses, separated by semicolons:

  1. Initialization: Executed once before the loop starts. This usually initializes a counter variable (e.g., i=0).

  2. Condition: Evaluated before each loop iteration. If it’s true, the loop continues; if false, the loop stops.

  3. Increment/Decrement: Executed after each loop iteration. This usually updates the counter variable (e.g., i++).

Example

Let’s print the numbers from 1 to 5:

for (let i = 1; i <= 5; i++) {
  console.log("Count: " + i);
}
/*
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
*/

2. The while Loop: Condition-Based Running

The while loop runs as long as a specified condition remains true. It’s ideal when you don’t know the exact number of iterations beforehand, but you know the condition that must be met to stop the loop.

Structure

The while loop only requires a condition inside its parentheses. Crucially, you must manage the variable that controls the condition inside the loop’s body to prevent an infinite loop.

Example

Let’s do the same counting exercise with a while loop:

let count = 1;

while (count <= 5) {
  console.log("Count: " + count);
  count++; // Don't forget to update the counter!
}
/*
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
*/

3. The do...while Loop: Guaranteed Execution

The do...while loop is very similar to the while loop, but with one key difference: the code block is executed at least once before the condition is checked.

Structure

The do block executes, and then the while condition is checked.

Example

Even if the condition is initially false, the do block runs once:

let j = 10;

do {
  console.log("This will print once: " + j);
  j++;
} while (j < 5); // The condition is false (10 < 5 is false)
/*
Output:
This will print once: 10
*/

4. Loops for Iterating Collections (Arrays)

JavaScript provides specialized loops for easily working with arrays and other iterable objects.

A. for...of: Iterating Over Values

The for...of loop iterates over the values (elements) of an iterable object (like an array, string, or map).

const fruits = ["apple", "banana", "cherry"];

for (const fruit of fruits) {
  console.log("I like " + fruit);
}
/*
Output:
I like apple
I like banana
I like cherry
*/

B. for...in: Iterating Over Object Properties (Keys)

The for...in loop iterates over the enumerable properties (keys/indexes) of an object. While it can be used for arrays, it’s generally discouraged in favor of for, for...of, or Array.prototype.forEach().

const user = { name: "Alice", age: 30, city: "NY" };

for (const key in user) {
  console.log(key + ": " + user[key]);
}
/*
Output:
name: Alice
age: 30
city: NY
*/

🛑 Loop Control Statements

Sometimes you need to jump out of a loop or skip an iteration. That’s where control statements come in.

  • break: Immediately exits the entire loop. Execution continues with the code following the loop.

  • continue: Skips the rest of the current iteration and jumps to the next iteration of the loop.

Example:

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    continue; // Skip the number 3
  }
  if (i === 5) {
    break; // Stop completely when we hit 5
  }
  console.log(i);
}
/*
Output:
1
2
4
*/

Loops are the backbone of automated tasks in JavaScript.

Understanding when to use a for, while, or for...of loop is key to writing clean, efficient, and powerful code!

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 0 comments }

React Server Components (RSC) have redefined modern web development, offering massive performance gains by shifting rendering and data fetching from the browser to the server. If you’re using the Next.js App Router, you’re already using RSC!

This post walks you through building a simple, highly performant blog using Next.js Server Components for data fetching and rendering, coupled with Client Components only where true interactivity is needed.


The Power Duo: Server Components (Default) and Client Components ('use client')

In Next.js App Router, every component is a Server Component by default. This is the key to performance, as these components:

  1. Can fetch data directly (using async/await).

  2. Have access to server-side resources (like environment variables).

  3. Do not ship their code to the client’s JavaScript bundle.

We use Client Components only for features requiring browser APIs, state, or event handlers (like onClick).

1. 📂 Mocking Server-Side Data (lib/posts.ts)

In a real-world scenario, the function below would contain your database query (e.g., using Prisma or an ORM). Here, we simulate that server-side access and a network delay.

// src/lib/posts.ts

export interface Post {
  id: string;
  title: string;
  content: string;
  author: string;
  date: string;
}

export async function getPosts(): Promise<Post[]> {
  // Simulate network delay and database query
  await new Promise((resolve) => setTimeout(resolve, 1000));

  return [
    /* ... mock data objects ... */
    // { id: '1', title: '...', content: '...', author: '...' },
    // { id: '2', title: '...', content: '...', author: '...' },
  ];
}

By placing this code on the server, we ensure that secrets or connection strings used within getPosts are never exposed to the client.

2. ❤️ The Interactive Client Component (components/LikeButton.tsx)

This component handles user interaction (the button click) and manages local state (the like count). Because it needs browser capabilities, we mark it with the 'use client' directive.

// src/components/LikeButton.tsx
'use client'; 

import { useState } from 'react';

// ... component definition ...

export default function LikeButton({ initialLikes }: LikeButtonProps) {
  const [likes, setLikes] = useState(initialLikes);

  const handleClick = () => {
    setLikes((prevLikes) => prevLikes + 1);
    // Real-world: Send update to a Server Action or API endpoint
  };

  return (
    <button
      onClick={handleClick}
      // ... Tailwind CSS classes ...
    >
      ❤️ Like ({likes})
    </button>
  );
}

Key Takeaway: The Client Component file is the only one whose code is sent to the browser.

3. 📝 The Rendering Server Component (components/BlogPost.tsx)

This component receives the post data (fetched on the server) and structures the UI. It remains a Server Component, even though it renders the LikeButton Client Component inside it.

// src/components/BlogPost.tsx

import { Post } from '@/lib/posts';
import LikeButton from './LikeButton'; // Importing a Client Component

// ... component definition ...

export default function BlogPost({ post }: BlogPostProps) {
  return (
    <article className="bg-white p-6 rounded-lg shadow-md mb-8">
      <h2 className="text-3xl font-bold text-gray-800 mb-2">{post.title}</h2>
      {/* ... other post details ... */}
      <div className="prose prose-lg text-gray-700">
        <p>{post.content}</p>
      </div>
      
      {/* Renders the static HTML of the LikeButton, then hydrates it */}
      <LikeButton initialLikes={Math.floor(Math.random() * 100)} /> 
    </article>
  );
}

4. 🌐 The Main Page Component (app/page.tsx)

The main page is where the entire process starts. Since it is a Server Component, we can make it an async function and call our server-side data fetching utility directly.

// src/app/page.tsx

import { getPosts } from '@/lib/posts';
import BlogPost from '@/components/BlogPost';

// The 'async' keyword allows direct server-side data fetching
export default async function HomePage() {
  const posts = await getPosts(); // Data fetched BEFORE the component renders

  return (
    <main className="container mx-auto px-4 py-8 max-w-3xl">
      <h1 className="text-5xl font-extrabold text-center text-gray-900 mb-12">
        My Awesome RSC Blog
      </h1>
      <section>
        {posts.map((post) => (
          <BlogPost key={post.id} post={post} />
        ))}
      </section>
    </main>
  );
}

Conclusion: Performance by Default

By using Next.js Server Components, we achieve three major benefits:

  1. Zero-Bundle Static Content: The vast majority of the blog post text is rendered to HTML on the server, avoiding client-side JavaScript download for the content.

  2. Efficient Data Fetching: Data retrieval happens close to the source (the server), eliminating the need for client-side API roundtrips and complex state management (useEffect, loaders).

  3. Clean Separation of Concerns: We clearly separate server logic (data, secrets) from client logic (state, events), leading to cleaner, more maintainable code.

This pattern—Server Components for content and data, Client Components for interaction—is the blueprint for building performant, modern web applications.

Useful links below:

Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service

Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2

Best email marketing automation solution on the market! http://www.aweber.com/?373860

Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29

Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff

Buy me a coffee ☕️https://buymeacoffee.com/tyronneratcliff

{ 1 comment }