≡ Menu

In the world of JavaScript, there are two ways to solve a problem.

You can tell the computer exactly how to do something (Imperative), or you can describe what the result should look like using math-like logic (Functional).

As applications grow in complexity, the “Imperative” way often leads to “spaghetti code”—where changing a variable on line 10 breaks a feature on line 500.

Functional Programming (FP) is the antidote.

By mastering three core patterns—Pure Functions, Immutability, and Currying—you can write code that is predictable, testable, and incredibly easy to reason about.


1. The Foundation: Pure Functions

A function is “pure” when it behaves like a reliable machine: you put the same raw materials in, and you always get the exact same product out.

The Two Rules of Purity:

  1. Predictability: Given the same arguments, it always returns the same result.

  2. No Side Effects: It does not modify any state outside its own scope (no changing global variables, no fetching data, no console.log).

The Code:

// ❌ Impure: Depends on external state and modifies it
let tax = 0.5;
const calculateTotal = (price) => {
  tax = tax + 0.1; // Side effect!
  return price + (price * tax);
};

// ✅ Pure: Self-contained and predictable
const calculateTotalPure = (price, taxRate) => {
  return price + (price * taxRate);
};

Why use it? Pure functions are a dream for testing. You don’t need to “set up” a complex environment to test them; you just pass an input and check the output.


2. The Safety Net: Immutability

In JavaScript, objects and arrays are “mutable.” This means if you pass an array to a function, that function can accidentally change the original array.

Immutability is the practice of never changing data. Instead of modifying an existing object, you create a copy with the changes applied.

The Code:

const state = { user: 'Alex', points: 10 };

// ❌ Mutable: Changes the original object
const updatePoints = (player) => {
  player.points = 20; 
};

// ✅ Immutable: Returns a new object using the Spread Operator (...)
const updatePointsPure = (player) => {
  return { ...player, points: 20 };
};

Why use it? Immutability makes “Time Travel Debugging” possible. Since you never destroy old state, you can keep a history of every change in your app, making it nearly impossible to lose data to “stealth” bugs.


3. The Specialized Tool: Currying

Currying sounds intimidating, but it’s actually a simple trick: it’s the process of taking a function that takes multiple arguments and turning it into a series of functions that each take one argument.

The Code:

// The standard way
const multiply = (a, b) => a * b;

// The Curried way
const curriedMultiply = (a) => (b) => a * b;

// Why bother? Because you can create "Pre-configured" functions!
const double = curriedMultiply(2); 
const triple = curriedMultiply(3);

console.log(double(10)); // 20
console.log(triple(10)); // 30

Why use it? Currying allows you to create highly reusable “specialty” functions from a single general-purpose function. It’s perfect for handling configuration or repetitive logic.


Putting it All Together: The Pipeline

When you combine these three, you get Composition. You can pipe your data through a series of small, pure, curried functions like an assembly line.

// A simple pipeline
const getName = (user) => user.name;
const uppercase = (str) => str.toUpperCase();
const getGreeting = (name) => `HELLO, ${name}!`;

const user = { name: 'emily' };

// Functional Composition
const welcomeMessage = getGreeting(uppercase(getName(user)));
// "HELLO, EMILY!"

Summary

Functional Programming isn’t about being “smarter” than other developers; it’s about being safer.

  • Pure Functions remove surprises.

  • Immutability preserves your data’s integrity.

  • Currying lets you build a library of reusable tools.

The next time you’re about to update a global variable or write a massive 5-argument function, ask yourself: “How would a functional programmer do this?”

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 }

In the world of web development, data is king.

But data is rarely sitting right inside your code—it lives on external servers, waiting to be “fetched.”

Whether you’re building a stock market tracker, a social media feed, or a sports scoreboard, the Fetch API is the bridge between your user interface and the rest of the world.

It is the modern standard for making network requests in JavaScript, replacing the old, clunky methods of the past with a clean, Promise-based syntax.

But theory only takes you so far. To truly master Fetch, you need to build something real.

In this tutorial, we’re going to build a Modern Weather Dashboard.

We’ll learn how to:

  • Connect to a real-world API (OpenWeatherMap).

  • Handle multiple asynchronous calls using async/await.

  • Manage errors gracefully so your app doesn’t crash.

  • Transform raw JSON data into a beautiful, glassmorphism-inspired UI.

Ready to turn some code into a living, breathing application? Let’s dive in.

Prerequisites

  1. An API Key: Sign up for a free account at OpenWeatherMap and generate an API key.

  2. Basic HTML/CSS/JS knowledge.

  3. A code editor (like VS Code).


Step 1: The HTML Blueprint

We need a clean UI. We’ll use a search input, a main card for current weather, and a grid for the 5-day forecast.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Weather Dashboard</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <header>
            <h1>WeatherPro</h1>
            <div class="search-area">
                <input type="text" id="cityInput" placeholder="Search city...">
                <button id="searchBtn">Get Weather</button>
            </div>
        </header>

        <main id="weatherContent" class="hidden">
            <section class="current-card">
                <div class="main-info">
                    <h2 id="cityName">---</h2>
                    <img id="mainIcon" src="" alt="">
                    <h1 id="mainTemp">--°C</h1>
                </div>
                <div class="details">
                    <p>Humidity: <span id="humidity">--</span>%</p>
                    <p>Wind: <span id="wind">--</span> km/h</p>
                </div>
            </section>

            <section class="forecast-section">
                <h3>5-Day Forecast</h3>
                <div id="forecastGrid" class="grid"></div>
            </section>
        </main>
    </div>
    <script src="script.js"></script>
</body>
</html>

Step 2: Styling with CSS

Let’s give it a modern “Glassmorphism” look—popular for weather apps in 2026.

body {
    font-family: 'Segoe UI', sans-serif;
    background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
    color: white;
    min-height: 100vh;
    display: flex;
    justify-content: center;
}

.container { width: 90%; max-width: 800px; padding: 20px; }

.search-area { margin-bottom: 30px; display: flex; gap: 10px; }

input { 
    flex: 1; padding: 10px; border-radius: 8px; border: none; 
}

button { 
    padding: 10px 20px; border-radius: 8px; border: none; 
    background: #ff7e5f; color: white; cursor: pointer;
}

.current-card {
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    border-radius: 15px;
    padding: 30px;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 15px;
    margin-top: 20px;
}

.forecast-card {
    background: rgba(255, 255, 255, 0.05);
    padding: 15px;
    border-radius: 10px;
    text-align: center;
}

.hidden { display: none; }

Step 3: The Fetch Logic (script.js)

This is the “brain” of the app. We will use two different endpoints: one for current weather and one for the 5-day forecast.

const API_KEY = 'YOUR_API_KEY_HERE';
const searchBtn = document.getElementById('searchBtn');

searchBtn.addEventListener('click', async () => {
    const city = document.getElementById('cityInput').value;
    if (!city) return;

    try {
        // Fetching Current Weather
        const weatherRes = await fetch(
            `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}`
        );

        if (!weatherRes.ok) throw new Error('City not found');
        const weatherData = await weatherRes.json();

        // Fetching 5-Day Forecast
        const forecastRes = await fetch(
            `https://api.openweathermap.org/data/2.5/forecast?q=${city}&units=metric&appid=${API_KEY}`
        );
        const forecastData = await forecastRes.json();

        updateUI(weatherData, forecastData);
    } catch (err) {
        alert(err.message);
    }
});

function updateUI(current, forecast) {
    document.getElementById('weatherContent').classList.remove('hidden');
    
    // Update Current Weather
    document.getElementById('cityName').textContent = current.name;
    document.getElementById('mainTemp').textContent = `${Math.round(current.main.temp)}°C`;
    document.getElementById('humidity').textContent = current.main.humidity;
    document.getElementById('wind').textContent = current.wind.speed;
    document.getElementById('mainIcon').src = 
        `https://openweathermap.org/img/wn/${current.weather[0].icon}@2x.png`;

    // Update Forecast
    const grid = document.getElementById('forecastGrid');
    grid.innerHTML = ''; // Clear previous data

    // The API gives data in 3-hour blocks. We want 1 block per day (every 8th item).
    const dailyData = forecast.list.filter((_, index) => index % 8 === 0);

    dailyData.forEach(day => {
        const date = new Date(day.dt_txt).toLocaleDateString('en-US', { weekday: 'short' });
        grid.innerHTML += `
            <div class="forecast-card">
                <p><strong>${date}</strong></p>
                <img src="https://openweathermap.org/img/wn/${day.weather[0].icon}.png">
                <p>${Math.round(day.main.temp)}°C</p>
            </div>
        `;
    });
}

Step 4: Pro-Tips for Modern Apps

  1. Loading States: Before calling fetch(), change the button text to “Loading…” and disable it. Re-enable it once the data arrives.

  2. Environment Variables: In a real production app, never hardcode your API_KEY. Use a .env file or a backend proxy to hide it.

  3. Unit Switching: You can easily add a toggle that changes the URL parameter from units=metric to units=imperial to support Fahrenheit.


Final Thoughts

Using Fetch with async/await turns complex network logic into something that reads like a story.

You request data, wait for the response, check if it’s “OK,” and then display it.

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 }