<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Ethan Groene</title>
    <description>The latest articles on Forem by Ethan Groene (@egroene).</description>
    <link>https://forem.com/egroene</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2622813%2F8127aee0-4e00-47a9-885a-f0b76b362f21.PNG</url>
      <title>Forem: Ethan Groene</title>
      <link>https://forem.com/egroene</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/egroene"/>
    <language>en</language>
    <item>
      <title>React.js: How to Notify Users of Changing Connection Status</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Sat, 23 Aug 2025 17:17:15 +0000</pubDate>
      <link>https://forem.com/egroene/reactjs-how-to-notify-users-of-changing-connection-status-4o5l</link>
      <guid>https://forem.com/egroene/reactjs-how-to-notify-users-of-changing-connection-status-4o5l</guid>
      <description>&lt;p&gt;We’ve all had been there; we’re watching a captivating video, or reading our favorite fan-fiction site; then, out of nowhere, one of the most frustrating things of modernity happens: our internet connection fails.&lt;/p&gt;

&lt;p&gt;Sometimes, the only indication of this is a loading icon that won’t go away appears over a video. While browsing other sites, all site UI will disappear, and some UI with an error message, generated by the browser, will display.&lt;/p&gt;

&lt;p&gt;It can be a nice touch to have your website itself notify the users of a disconnection or reconnection to the internet. Here’s a way you could accomplish that in a React.js application.&lt;/p&gt;




&lt;p&gt;_To implement this functionality on all pages of your project, all of the following steps should be done inside the &lt;code&gt;App.jsx&lt;/code&gt; or &lt;code&gt;App.tsx&lt;/code&gt; file. The toast library is also used; to install that, run &lt;code&gt;npm i react-hot-toast&lt;/code&gt; and make sure to import it into your &lt;code&gt;App.jsx&lt;/code&gt; or &lt;code&gt;App.tsx&lt;/code&gt; file.&lt;br&gt;
_&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;1. Define &lt;code&gt;isOnline&lt;/code&gt;in state. Initialize to value of &lt;code&gt;navigator.onLine&lt;/code&gt; , which is a &lt;code&gt;boolean&lt;/code&gt; value that checks if an internet connection exists:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [isOnline, setIsOnline] = useState&amp;lt;boolean&amp;gt;(navigator.onLine);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Create a &lt;code&gt;useEffect&lt;/code&gt;, dependent on &lt;code&gt;isOnline&lt;/code&gt;:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {

}, [isOnline]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Inside the &lt;code&gt;useEffect&lt;/code&gt;, create function &lt;code&gt;handleOnlineStatusChange&lt;/code&gt;:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleOnlineStatusChange = () =&amp;gt; {
    setIsOnline(navigator.onLine);

    isOnline
      ? toast("You are offline", {
           style: {
            background: theme === "light" ? "#242424" : "rgb(233, 231, 228)",
            color: theme === "dark" ? "black" : "white",
            border: "2px solid red",
           },
        })
       : toast("Back online!", {
           style: {
            background: theme === "light" ? "#242424" : "rgb(233, 231, 228)",
            color: theme === "dark" ? "black" : "white",
            border: "2px solid green",
           },
        });
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;handleOnlineStatusChange&lt;/code&gt; sets &lt;code&gt;isOnline&lt;/code&gt; to updated &lt;code&gt;navigator.onLine&lt;/code&gt;, then, depending on the value of &lt;code&gt;isOnline&lt;/code&gt;, triggers a &lt;code&gt;toast&lt;/code&gt;, notifying user of connection status.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Below &lt;code&gt;handleOnlineStatusChange&lt;/code&gt; &amp;amp; still inside &lt;code&gt;useEffect&lt;/code&gt;, add, then clean up event listeners on window ‘s “online” and “offline” events. An anonymous function removing these event listeners is then returned from the &lt;code&gt;useEffect&lt;/code&gt;:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.addEventListener("online", handleOnlineStatusChange);
window.addEventListener("offline", handleOnlineStatusChange);

return () =&amp;gt; {
  window.removeEventListener("online", handleOnlineStatusChange);
  window.removeEventListener("offline", handleOnlineStatusChange);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. To test, go to your DevTools and, under something like “Network”, switch to “Offline”. It should look something like this:&lt;/strong&gt;&lt;/p&gt;

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

&lt;p&gt;If all the steps above were taken correctly, this type of behavior should happen when you toggle the network online &amp;amp; offline:&lt;/p&gt;

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

&lt;p&gt;Check out the site where I enabled this: &lt;a href="https://palz-frontend.onrender.com/" rel="noopener noreferrer"&gt;https://palz-frontend.onrender.com/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Codebase (see code in &lt;code&gt;App.tsx&lt;/code&gt; in the src folder): &lt;a href="https://github.com/EGROENE/palz" rel="noopener noreferrer"&gt;https://github.com/EGROENE/palz&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;




&lt;p&gt;Read more from me here: &lt;a href="https://dev.to/egroene"&gt;https://dev.to/egroene&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>ux</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How I Integrated a MongoDB Database into my React.js Project</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Wed, 29 Jan 2025 17:26:53 +0000</pubDate>
      <link>https://forem.com/egroene/how-i-integrated-a-mongodb-database-into-my-reactjs-project-42k</link>
      <guid>https://forem.com/egroene/how-i-integrated-a-mongodb-database-into-my-reactjs-project-42k</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published to Medium for JavaScript in Plain English on October 30, 2024&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Today is the day you bid &lt;em&gt;adieu&lt;/em&gt; to being a half-ass developer (pardon my French).&lt;/p&gt;

&lt;p&gt;If you are a front-end developer, I’m sure you have daydreamed about what it would be like to be able to not only work with other people’s APIs, but to be able to set up &amp;amp; integrate your own as well.&lt;/p&gt;

&lt;p&gt;I’m here to tell you today that it’s not as difficult as it may seem, though it may take a while to familiarize yourself with the concepts behind your code. You may be able to carve out a nice career for yourself working on only one of the two ends, but, if you have SaaS ideas, or want to build a business off your apps, it would be really cool to know how to build out both ends.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Full disclosure; I don’t know everything there is to know about the backend, but I feel confident enough to explain a solution I found for a portfolio project I’m working on. It is not my way or the high way, so if you have found other ways to set it up, I would love it if you explained it in a comment. Also, this article does not cover how to deploy a full-stack app, just a way you can set up a backend that you can work with during development. In reality, there wouldn’t be too much more to do to deploy it, but I plan to write a separate article on how to do that, when I have the time.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As a JavaScript guy, Node.js was the quickest way for me to get set up with the backend, so if you plan to follow my solution, make sure Node.js is installed on your device. My solution will require you to install the Node packages Mongoose, Express, dotenv, cors, &amp;amp; Nodemon. I will explain these shortly. I also assume that you have already set up a MongoDB Atlas account &amp;amp; deployed a cluster; if you haven’t, click &lt;a href="https://www.mongodb.com/resources/products/fundamentals/create-database#using-the-mongodb-atlas-ui" rel="noopener noreferrer"&gt;here&lt;/a&gt; to learn how to do that. To implement my solution, you will need your MongoDB URI.&lt;/p&gt;

&lt;p&gt;To provide some context before we get into the steps, I am creating a site that allows users to create, delete, edit, RSVP to, &amp;amp; invite others to events, as well as interact with other users by messages. So far, I have created collections in the project’s MongoDB database that store data related to users &amp;amp; events. I will eventually need another one for messages, but I haven’t gotten to that point in my project yet. For the demos, I will be showing things related only to the users collection.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;1. Create a ‘backend’ folder at the root of your project, then cd into it&lt;/strong&gt;&lt;/p&gt;

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

&lt;p&gt;After creating the &lt;code&gt;backend&lt;/code&gt; folder, set it as the current directory by typing &lt;code&gt;cd backend&lt;/code&gt; into the terminal &amp;amp; hitting ‘Enter’.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Install necessary Node packages&lt;/strong&gt;&lt;br&gt;
Make sure the current directory is the backend folder you’ve just created, then install the packages as follows:&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i mongoose
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mongoose is what’s called an ‘object-modeling tool’, a kind of middleman between your code &amp;amp; your database. It manages relationships between data, provides schema validation (kind of like checking for types with TypeScript), &amp;amp; translates between objects in code &amp;amp; the representation of those objects in MongoDB.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://mongoosejs.com/" rel="noopener noreferrer"&gt;Mongoose Docs&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/mongoose" rel="noopener noreferrer"&gt;Mongoose NPM page&lt;/a&gt;&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i express
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Express.js is a framework that makes it easy to set up APIs by using JavaScript on the server side.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://expressjs.com/" rel="noopener noreferrer"&gt;Express.js Docs&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/express" rel="noopener noreferrer"&gt;Express.js NPM page&lt;/a&gt;&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i dotenv
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;dotenv is a zero-dependency module that makes it possible to load variables that you may want to keep private (like your MongoDB URI) stored in the &lt;code&gt;.env&lt;/code&gt; file into &lt;code&gt;process.env&lt;/code&gt;, which can be applied, in this case, throughout the backend folder. You should add the &lt;code&gt;.env&lt;/code&gt; file to your &lt;code&gt;.gitignore&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.dotenv.org/docs/" rel="noopener noreferrer"&gt;dotenv Docs&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/dotenv" rel="noopener noreferrer"&gt;dotenv NPM page&lt;/a&gt;&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i nodemon
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nodemon is a tool that automatically refreshes the Node application whenever changes are made in the files. It’s a wonderful thing, unless you would prefer closing &amp;amp; restarting the server after you make changes to files (/sarcasm ;) ).&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i cors
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This package is used to enable Cross-Origin Resource Sharing (CORS). This will help you avoid getting an error in the console that reads something like “Access to fetch at  from origin  has been blocked by CORS policy…”, which occurs because the Same Origin Policy prevents the response from being received, due to the originating &amp;amp; receiving domains being different due to the port number. This may cause your page to not display at all, or to display in a way you hadn’t planned.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/cors" rel="noopener noreferrer"&gt;cors NPM page&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Create the server file&lt;/strong&gt;&lt;br&gt;
At the root of the backend directory, create a &lt;code&gt;server.cjs&lt;/code&gt; file. In it, we need to following code (please read the comments explaining everything I’m doing):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Import &amp;amp; enable dotenv in the file:
require("dotenv").config();

// Express app:
const express = require("express");
const app = express();

// Import Mongoose:
const mongoose = require("mongoose");

// Import &amp;amp; apply cors package:
const cors = require("cors");
app.use(cors()); // more on .use() method below...

/* Assign routes (which we will later define in respective files), 
  to variables (in my app so far, : */
const userRoutes = require("./routes/users.cjs");
const eventRoutes = require("./routes/events.cjs");

// MIDDLEWARE

/* .use() is a method on an Express app. It mounts the specified 
middleware function(s) at the specified path: the middleware 
function is executed when the base of the requested path matches path */

/* If any request has data that it sends to the server, 
   the code on the next line attaches it to request object, 
   so we can access it in request handler */
app.use(express.json());

/* Whenever an HTTP request is made to a certain endpoint/path,
   log the path &amp;amp; type of request to console (seen in terminal) */
app.use((req, res, next) =&amp;gt; {
  console.log(req.path, req.method);
  next();
});

// ROUTES
// Attach defined routes to their corresponding endpoints:
app.use("/palz/users", userRoutes);
// app.use("/palz/events", eventRoutes);
// app.use("/palz/messages", messageRoutes);

// Connect to Mongoose:
mongoose
  .connect(process.env.MONGODB_URI)
  .then(() =&amp;gt; {
    // Listen for requests only after connecting to DB:
    app.listen(process.env.PORT, () =&amp;gt; {
      console.log(`Connected to DB &amp;amp; listening on port ${process.env.PORT}!`);
    });
  })
  // If there's an error connecting, we will see that in the terminal:
  .catch((error) =&amp;gt; console.log(error));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can see I used some variables from my &lt;code&gt;.env&lt;/code&gt; file above. Here’s what my &lt;code&gt;.env&lt;/code&gt; file looks like so far (with top-secret info redacted):&lt;/p&gt;

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

&lt;blockquote&gt;
&lt;p&gt;‘.cjs’ means ‘common JavaScript’, which is used in server-side environments, like Node.js. I think it helped eliminate trivial type errors as opposed to using the .js extension, but I don’t quite remember. It has worked just fine, so I haven’t dived too deeply into it. I wouldn’t make too big a fuss over the file extension here if I were you.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;4. Set up data models&lt;/strong&gt;&lt;br&gt;
To ensure any data that gets sent to the database fits the defined shape, we need to define a model that each document sent to a collection in the database will need to fit. Mongoose can help with this. If data we try to send to the database doesn’t match the specified shape, it will result in a bad request, and nothing will be added to the database.&lt;/p&gt;

&lt;p&gt;Let’s set up a data model for the documents in the &lt;code&gt;/users&lt;/code&gt; collection. We’ll do this in &lt;code&gt;userModel.js&lt;/code&gt; in folder &lt;code&gt;models&lt;/code&gt;, which should be at the root of the &lt;code&gt;backend&lt;/code&gt; directory. Below is only the user data model, but you can see all model files &lt;a href="https://github.com/EGROENE/palz/tree/main/backend/models" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require("mongoose");

const Schema = mongoose.Schema;

// Create a new instance of mongoose.Schema, assign to 'userSchema' variable:
// Each user document in DB should fit this schema
const userSchema = new Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  city: {
    type: String,
    required: false,
  },
  stateProvince: {
    type: String,
    required: false,
  },
  country: {
    type: String,
    required: false,
  },
  phoneCountry: {
    type: String,
    required: false,
  },
  phoneCountryCode: {
    type: String,
    required: false,
  },
  phoneNumberWithoutCountryCode: {
    type: String,
    required: false,
  },
  instagram: {
    type: String,
    required: false,
  },
  facebook: {
    type: String,
    required: false,
  },
  x: {
    type: String,
    required: false,
  },
  interests: {
    type: Array,
    required: true,
  },
  about: {
    type: String,
    required: false,
  },
  friendRequestsReceived: {
    type: Array,
    required: true,
  },
  friendRequestsSent: {
    type: Array,
    required: true,
  },
  hostingCredits: {
    type: Number,
    required: true,
  },
  profileImage: {
    type: String,
    required: false,
  },
  profileVisibleTo: {
    type: String,
    required: true,
  },
  subscriptionType: {
    type: String,
    required: false,
  },
  whoCanAddUserAsOrganizer: {
    type: String,
    required: true,
  },
  whoCanInviteUser: {
    type: String,
    required: true,
  },
  username: {
    type: String,
    required: true,
  },
  friends: {
    type: Array,
    required: true,
  },
  emailAddress: {
    type: String,
    required: true,
  },
});

// Export, so that schema can be used in other files
module.exports = mongoose.model("User", userSchema);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Certain properties on a user object, like &lt;code&gt;about&lt;/code&gt;, will be initialized to an empty string when a new user document is sent to the database, so they should not be required in the schema, else a bad request will result. For the sake of brevity, I won’t show here my &lt;code&gt;eventModel.js&lt;/code&gt; file, but it would look very similar to the user model above, just with different properties &amp;amp; specifications on those properties. You can see that file &lt;a href="https://github.com/EGROENE/palz/blob/main/backend/models/eventModel.js" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Set up controllers&lt;/strong&gt;&lt;br&gt;
At the root of the &lt;code&gt;backend&lt;/code&gt; directory, I created a &lt;code&gt;controllers&lt;/code&gt; folder, which will store a controllers file for each endpoint. Controllers essentially handle HTTP CRUD requests made to the endpoint. You should only create as many as are needed for your situation, but for this one involving users, I will need 5.&lt;/p&gt;

&lt;p&gt;As the handlers will return a Promise, we’ll need to handle requests that succeed &amp;amp; ones that fail. Again, I will only show you my &lt;code&gt;userControllers.js&lt;/code&gt; file for the sake of brevity, but you can see all my controllers files &lt;a href="https://github.com/EGROENE/palz/tree/main/backend/controllers" rel="noopener noreferrer"&gt;here&lt;/a&gt;. Please see the comments in the code below to understand what I’m doing to set up these handlers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Import Mongoose:
const mongoose = require("mongoose");

// Import data model for user objects:
const User = require("../models/userModel");

// get all users:
const getAllUsers = async (req, res) =&amp;gt; {
  // use .find() method on User data schema to fetch all user objects:
  // leave obj in .find() blank, as all users are being fetched
  const allUsers = await User.find({});

  /* Set HTTP status to 200 (ok) &amp;amp; convert response to JSON. The result is
  an object in JSON that contains info on all users */
  res.status(200).json(allUsers);
};

/* get a single user by their id (unique property added to each user object
   upon its creation in MongoDB */
const getUser = async (req, res) =&amp;gt; {
  // Get id from request parameters:
  const { id } = req.params;

  /* If id is not a valid MongoDB ObjectId, set HTTP status to 400 (bad 
     request) and return error message in JSON form */
  if (!mongoose.Types.ObjectId.isValid(id)) {
     return res.status(400).json({ error: "Bad request (invalid id)" });
  }

  /* assign user to document in DB that has id that matches the 
     id defined in this method: */
  const user = await User.findById(id);

  /* If no user id in database matches id from the request parameter,
     set HTTP status to 404 and return error message in JSON form */
  if (!user) {
    return res.status(404).json({ error: "User doesn't exist" });
  }

  /* If a user object (document) has an id that matches id in the 
     request parameters, set HTTP status to 200 &amp;amp; return that user object in
     JSON format */
  res.status(200).json(user);
};

// create new user
const createNewUser = async (req, res) =&amp;gt; {
  // Destructure all user-object properties from request body:
  const {
    firstName,
    lastName,
    password,
    city,
    stateProvince,
    country,
    phoneCountry,
    phoneCountryCode,
    phoneCountryWithoutCountryCode,
    instagram,
    facebook,
    x,
    interests,
    about,
    friendRequestsReceived,
    friendRequestsSent,
    hostingCredits,
    profileImage,
    profileVisibleTo,
    subscriptionType,
    whoCanAddUserAsOrganizer,
    whoCanInviteUser,
    username,
    friends,
    emailAddress,
  } = req.body;

  // Try creating new user document in users collection in DB
  /* If successful, set HTTP status to 200 &amp;amp; return the newly created user
     document in JSON format. If it fails, set HTTP status to 400 
     (bad request) &amp;amp; return error message in JSON format. */
  try {
    const user = await User.create({
      firstName,
      lastName,
      password,
      city,
      stateProvince,
      country,
      phoneCountry,
      phoneCountryCode,
      phoneCountryWithoutCountryCode,
      instagram,
      facebook,
      x,
      interests,
      about,
      friendRequestsReceived,
      friendRequestsSent,
      hostingCredits,
      profileImage,
      profileVisibleTo,
      subscriptionType,
      whoCanAddUserAsOrganizer,
      whoCanInviteUser,
      username,
      friends,
      emailAddress,
    });
    res.status(200).json(user);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
};

// Delete a user:
const deleteUser = async (req, res) =&amp;gt; {
  // Get user document from request parameters by its id:
  const { id } = req.params;

  /* If id is not a valid MongoDB ObjectId, set HTTP status to 400 (bad 
     request) and return error message in JSON form */
  if (!mongoose.Types.ObjectId.isValid(id)) {
     return res.status(400).json({ error: "Bad request (invalid id)" });
  }

  /* Use the findOneAndDelete() method to delete user document with
     id that matches id in request parameters */
  const user = await User.findOneAndDelete({ _id: id });

  /* If no user id in database matches id from the request parameter,
     set HTTP status to 404 and return error message in JSON form */
  if (!user) {
    return res.status(404).json({ error: "User doesn't exist" });
  }

  /* If a user object (document) has an id that matches id in the 
     request parameters, set HTTP status to 200 &amp;amp; return that user object in
     JSON format. The user document will no longer exist in the DB. */
  res.status(200).json(user);
};

// Update a user document:
const updateUser = async (req, res) =&amp;gt; {
  // Get user document from request parameters by its id:
  const { id } = req.params;

  /* If id is not a valid MongoDB ObjectId, set HTTP status to 400 (bad 
     request) and return error message in JSON form */
  if (!mongoose.Types.ObjectId.isValid(id)) {
     return res.status(400).json({ error: "Bad request (invalid id)" });
  }

  /* Use the .findOneAndUpdate() method to get a particular user document,
     then update its values. */
  /* 2nd argument in .findOneAndUpdate() is an object containing the 
     properties to be updated, along with their updated values */
  /* 3rd argument will return the updated user object after a 
     successful request */
  const user = await User.findOneAndUpdate({ _id: id }, { ...req.body }, 
    { new: true });

  /* If no user id in database matches id from the request parameter,
     set HTTP status to 404 and return error message in JSON form */
  if (!user) {
    return res.status(404).json({ error: "User doesn't exist" });
  }

  /* If a user object (document) has an id that matches id in the 
     request parameters, set HTTP status to 200 &amp;amp; return that user object in
     JSON format. The updated version of the user document 
     will now be in the place of the old version in the DB. */
  res.status(200).json(user);
};

// Export the controllers:
module.exports = {
  createNewUser,
  getAllUsers,
  getUser,
  deleteUser,
  updateUser,
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Set up routes, test HTTP CRUD requests&lt;/strong&gt;&lt;br&gt;
Remember &lt;code&gt;userRoutes&lt;/code&gt; &amp;amp; &lt;code&gt;eventRoutes&lt;/code&gt; that we imported into the &lt;code&gt;server.cjs&lt;/code&gt; file? Those come from info in the &lt;code&gt;users.cjs&lt;/code&gt; &amp;amp; &lt;code&gt;events.cjs&lt;/code&gt; files, which I put inside the &lt;code&gt;routes&lt;/code&gt; folder at the root of the &lt;code&gt;backend&lt;/code&gt; directory. In a &lt;code&gt;routes&lt;/code&gt; file, we need to import the HTTP CRUD request handlers &amp;amp; assign them to run in the appropriate request type &amp;amp; on a certain path.&lt;/p&gt;

&lt;p&gt;As before, I will only show what the file that has to do with user, &lt;code&gt;users.js&lt;/code&gt;, looks like, but you can see all route files &lt;a href="https://github.com/EGROENE/palz/tree/main/backend/routes" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Import Express:
const express = require("express");

// Import HTTP-CRUD-request handlers:
const {
  createNewUser,
  getAllUsers,
  getUser,
  deleteUser,
  updateUser,
} = require("../controllers/userControllers");

// Assign express.Router() to variable 'router':
const router = express.Router();

// Assign handlers to run on certain requests to router on certain paths:

// GET all users
router.get("/", getAllUsers);

// GET single user:
router.get("/:id", getUser);

// POST (create) a new user:
router.post("/", createNewUser);

// DELETE a user:
router.delete("/:id", deleteUser);

// PATCH (update) a user:
router.patch("/:id", updateUser);

// Export router:
module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, it’s time to test out our requests made to the database. You will first need to start the server we just set up. I have the scripts in my &lt;code&gt;package.json&lt;/code&gt; file in my backend directory set up like so:&lt;/p&gt;

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

&lt;p&gt;You should now be able to start up the server in the terminal (make sure the current directory is the &lt;code&gt;backend&lt;/code&gt; folder) by running &lt;code&gt;npm run dev&lt;/code&gt;. If successful, you should see the message “Connected to DB &amp;amp; listening on port 4000!”. If there is an error, it is likely due to a syntax error somewhere, or because you are trying to access your MongoDB cluster from an IP address that isn’t whitelisted (even if you allow access from any IP address, a VPN may cause this error to occur).&lt;/p&gt;

&lt;p&gt;Once you have completed the steps above, and you have the server up &amp;amp; running, you can try out your HTTP CRUD requests using something like Postman, which is super straightforward. If you need a body in a request, add one under the ‘Body’ header, where you should select ‘raw’, then select JSON format (not Text or anything else). Add properties &amp;amp; their values should be inside an object &amp;amp; in JSON format. We have set up error handling as such, that, if there is an erroneous request made, you should be able to figure out what is wrong rather quickly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. Build HTTP-CRUD-request handler functions to be called on the frontend&lt;/strong&gt;&lt;br&gt;
Now comes the part you’ve been waiting for; making it possible to make HTTP CRUD requests upon triggers we define in the frontend, like maybe in a React &lt;code&gt;useEffect&lt;/code&gt; or upon certain events the user triggers on the interface. I hope you’re as excited as I am.&lt;/p&gt;

&lt;p&gt;As mentioned, these request functions can be called in various places on the frontend, and, like any other function, we can pass in parameters to them, such as a user id or an object containing updated values of properties on a user object. It is often a good idea to call them inside a handler function, as some other things may need to happen at the same time these request functions are called.&lt;/p&gt;

&lt;p&gt;If you tested out the requests in Postman, you may have noticed the ‘Code’ button off to the right side. If you click on that, you’ll see the JS fetch option. You can simply copy this code &amp;amp; use it to create a request function. I adapted mine a bit from the code Postman spit out, so that my request functions return something of type &lt;code&gt;Promise&amp;lt;Response&amp;gt;&lt;/code&gt;, to which I apply a chain of &lt;code&gt;.then()&lt;/code&gt;, &lt;code&gt;.catch()&lt;/code&gt;, and maybe a &lt;code&gt;.finally()&lt;/code&gt; at the end when I call the request functions somewhere in the app, usually in a handler function. Here is a list containing examples of GET, POST, PATCH, and DELETE requests related to the &lt;code&gt;users/&lt;/code&gt; collection in the database, along with an example of them being used in a handler function:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Get all users&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Request function:
// Later added to an object named 'Requests', which is then default exported
const getAllUsers = (): Promise&amp;lt;TUser[]&amp;gt; =&amp;gt; {
  return fetch("http://localhost:4000/palz/users", {
    method: "GET",
    redirect: "follow",
  }).then((response) =&amp;gt; response.json() as Promise&amp;lt;TUser[]&amp;gt;);
};

/* Implementing getAllUsers() in a handler which sets allUsers state value
   to what the getAllUsers() returns: */
/* I call this when app initially loads &amp;amp; whenever a change is 
   made to the allUsers state value (called inside a useEffect()
   w/ allUsers in its dependency array */
const fetchAllUsers = (): Promise&amp;lt;void&amp;gt; =&amp;gt; Requests.getAllUsers().then(setAllUsers);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Create new user&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Request function:
/* Notice how newUserData (an object of type TUser) is passed in. 
   Certain values from that object are used to set initial values of some
   properties of new user's object, seen in 'raw'. 'raw' is then set
   as the body of the POST request. */
const createUser = (newUserData: TUser): Promise&amp;lt;Response&amp;gt; =&amp;gt; {
  const myHeaders = new Headers();
  myHeaders.append("Content-Type", "application/json");

  const raw = JSON.stringify({
    "firstName": newUserData.firstName,
    "lastName": newUserData.lastName,
    "username": newUserData.username,
    "password": newUserData.password,
    "emailAddress": newUserData.emailAddress,
    "hostingCredits": 0,
    "eventsOrganized": [],
    "eventsAttended": [],
    "city": "",
    "stateProvince": "",
    "country": "",
    "phoneCountry": "",
    "phoneCountryCode": "",
    "phoneNumberWithoutCountryCode": "",
    "instagram": "",
    "facebook": "",
    "x": "",
    "profileImage": newUserData.profileImage,
    "about": "",
    "subscriptionType": "",
    "interests": [],
    "friends": [],
    "friendRequestsReceived": [],
    "friendRequestsSent": [],
    "profileVisibleTo": newUserData.profileVisibleTo,
    "whoCanAddUserAsOrganizer": newUserData.whoCanAddUserAsOrganizer,
    "whoCanInviteUser": newUserData.whoCanInviteUser,
  });

  return fetch("http://localhost:4000/palz/users/", {
    method: "POST",
    headers: myHeaders,
    body: raw,
    redirect: "follow",
  });
};

// createUser() called inside handler handleNewAccountCreation():
/* As you can see, request success/failure is handled here (error is 
   logged to the console, and user is notified by a React Toast 
   popup). */
/* userData is the object that matches the required 'newUserData'
   parameter of createUser() */
const handleNewAccountCreation = (userData: TUser): void =&amp;gt; {
    Requests.createUser(userData)
      .then((response) =&amp;gt; {
        if (!response.ok) {
          setUserCreatedAccount(false);
        } else {
          setUserCreatedAccount(true);
        }
      })
      .catch((error) =&amp;gt; {
        toast.error("Could not create account. Please try again.");
        console.log(error);
      });
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Update user information&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Request function:
/* user parameter represents the user whose object must be updated. 
   The user's id is used to find that object (document) in the database. */
/* valuesToUpdate represents the object containing the property values
   on the user object that need to be updated. This is converted to JSON
   and set as the body of the PATCH request. */
const patchUpdatedUserInfo = (
  user: TUser | undefined,
  valuesToUpdate: TUserValuesToUpdate
): Promise&amp;lt;Response&amp;gt; =&amp;gt; {
  const myHeaders = new Headers();
  myHeaders.append("Content-Type", "application/json");

  const raw = JSON.stringify(valuesToUpdate);

  return fetch(`http://localhost:4000/palz/users/${user?._id}`, {
    method: "PATCH",
    headers: myHeaders,
    body: raw,
    redirect: "follow",
  });
};

// Use patchUpdatedUserInfo() in a handler:
const handleUpdateProfileInfo = () =&amp;gt; {
  // many other things...
  Requests.patchUpdatedUserInfo(currentUser, valuesToUpdate)
  .then((response) =&amp;gt; {
    if (!response.ok) {
      toast.error("Could not update profile info. Please try again.");
      // other things...
    } else {
      toast.success("Profile info updated");
      // many other things...
    })
   .catch((error) =&amp;gt; console.log(error));
   // other things...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In &lt;code&gt;handleUpdateProfileInfo&lt;/code&gt; above, there are several state values that will need to be changed, based on if the PATCH request succeeds or fails. Those state values are not accessible inside of &lt;code&gt;requests.tsx&lt;/code&gt;, where the request is defined, so this is a good example of why you should set up error handling functions in request handlers defined in a component or context in your React app, not in the request function itself. To reiterate how to do this, take the code given to you by Postman, but return the fetch part (a &lt;code&gt;Promise&lt;/code&gt;), delete the &lt;code&gt;.then()&lt;/code&gt;, &lt;code&gt;.catch()&lt;/code&gt; chain, then add that chain onto the call of the request function when you call it inside its handler.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Delete user&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Request function:
const deleteUser = (userID: string | undefined): Promise&amp;lt;Response&amp;gt; =&amp;gt; {
  const myHeaders = new Headers();
  myHeaders.append("Content-type", "application/json");

  return fetch(`http://localhost:4000/palz/users/${userID}`, {
    method: "DELETE",
    headers: myHeaders,
    redirect: "follow",
  });
};

// Request function used in a handler:
const handleAccountDeletion = () =&amp;gt; {
  // LOOOOTS of other things...
  Requests.deleteUser(currentUser?._id)
  .then((response) =&amp;gt; {
    if (!response.ok) {
      toast.error("Account deletion incomplete; please try again.");
      fetchAllEvents();
      fetchAllUsers();
    } else {
      toast.error("You have deleted your account. We're sorry to see you go!");
      logout();
      navigation("/");
      fetchAllEvents();
    }
  })
  .catch((error) =&amp;gt; console.log(error));
  // Other things...
 };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So that was a list of a handler function for each type of HTTP CRUD request (except for PUT) related to &lt;code&gt;users/&lt;/code&gt;; you may see all my request functions for the project here, then see how they’re used in handlers by searching ‘Requests.’, assuming you have it opened in an IDE.&lt;/p&gt;

&lt;p&gt;At this point, your &lt;code&gt;backend&lt;/code&gt; folder at the root of your project should look something like this ( &lt;code&gt;userControllers.js&lt;/code&gt;, &lt;code&gt;userModel.js&lt;/code&gt;, &lt;code&gt;users.cjs&lt;/code&gt;, &lt;code&gt;server.cjs&lt;/code&gt;, &lt;code&gt;package.json&lt;/code&gt;, &lt;code&gt;package-lock.json&lt;/code&gt;, &lt;code&gt;node_modules/&lt;/code&gt;, &amp;amp; &lt;code&gt;.env&lt;/code&gt; will be the only things there if you followed my instructions exactly, but this image shows you where you should add files relating to other endpoints, like &lt;code&gt;/events&lt;/code&gt; &amp;amp; &lt;code&gt;/messages&lt;/code&gt;).&lt;/p&gt;

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




&lt;p&gt;I hope this article helps you unlock new powers as a developer. I used a patchwork of information from YouTube videos, documentation, &amp;amp; Stack Overflow posts when trying to figure this stuff out, so I felt the need to write down, step by step, how I connected a database to my frontend app, not only so I could better understand what I did, but to maybe help others who are looking to take their first step into the backend world.&lt;/p&gt;

&lt;p&gt;This has been my longest article ever, so I thank &amp;amp; congratulate you if you made it to the end. I would love to hear your thoughts on it, so feel free to write a comment or give me a reaction. Pass it on to anyone who would find this helpful.&lt;/p&gt;

&lt;p&gt;Keep building.&lt;/p&gt;




&lt;p&gt;&lt;a href="https://github.com/EGROENE/palz/tree/main" rel="noopener noreferrer"&gt;My project’s GitHub repository&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.mongodb.com/resources/products/fundamentals/create-database" rel="noopener noreferrer"&gt;https://www.mongodb.com/resources/products/fundamentals/create-database&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://learn.mongodb.com/" rel="noopener noreferrer"&gt;MongoDB University&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>mongodb</category>
      <category>node</category>
      <category>fullstack</category>
    </item>
    <item>
      <title>To All the Haters of Prop Drilling…</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Tue, 28 Jan 2025 17:32:16 +0000</pubDate>
      <link>https://forem.com/egroene/to-all-the-haters-of-prop-drilling-39g9</link>
      <guid>https://forem.com/egroene/to-all-the-haters-of-prop-drilling-39g9</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published to Medium for JavaScript in Plain English on February 28, 2024&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;…I was like you once: learning the fundamentals of React, trying to understand what components are, along with key principles in creating them &amp;amp; how they communicate with each other. You have likely encountered by now the issue of prop drilling, the practice of sending data from a parent component through a series of child components, which may not even need the data, just so that some component(s) down the line can use it.&lt;/p&gt;

&lt;p&gt;If you have not seen for yourself how this could lead to clunky code that can be hard to change or decipher, I hope you can imagine it. And, if you have any semblance of the crazy mind that I have, you may have surmised that there must be a better way to share data throughout a React app.&lt;/p&gt;

&lt;p&gt;I am pleased to say that, yes, there are a number of ways to give all parts of a React app access to certain data, some of which you may remember hearing about, at least. There are State-management libraries, like Zustand or Redux, the concepts of which, I admit, I am only vaguely familiar with.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Fun fact: ‘Zustand’ is actually the German word for ‘state’ or ‘condition’&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Knowing how to work with such libraries is useful, and it may be worthwhile to become acquainted with them, but React itself has a built-in way of sharing data throughout an app, and this is with the React Context API. In my experience so far, it is much simpler to understand from the beginning, so it may be a good idea to first understand this, then move on to learning various libraries.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why use Context API?
&lt;/h2&gt;

&lt;p&gt;Context API eliminates the need for the lifting up of State, it increases the understandability of the dependencies between components (which is great, especially if you are trying to make sense of someone else’s code), and it makes components more independent and thus, more reusable. As I will point out below, data can be accessed in a component in a single line of code by using a custom hook instead of a prop that has been passed in through an untold number of components.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does Context API work?
&lt;/h2&gt;

&lt;p&gt;Setting up Context API &lt;strong&gt;involves creating a Context, a Provider&lt;/strong&gt;, which is where the data (be it State values &amp;amp; their setters, values derived from State, or methods) that is to be shared, is stored &lt;strong&gt;must then be created &amp;amp; implemented for that Context, then the Context is consumed&lt;/strong&gt; in components as needed. I will take you through the steps I took to use Context API to handle information relating to a quiz. I used TypeScript, so just ignore that stuff if you’re a JavaScript purist.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. In a file named &lt;code&gt;quizContext.tsx&lt;/code&gt;, create a Context &amp;amp; its Provider:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createContext, useState, ReactNode} from "react";

/* Any other necessary imports go here (useState &amp;amp; useEffect, which are often
used in Contexts, should be imported from 'react' above, if needed, as well 
as any other things from 'react'): */

// Context is defined here:
export const QuizContext = createContext&amp;lt;TQuizContext | null&amp;gt;(null);

// Context's Provider is defined here:
export const QuizContextProvider = ({ children }: { children: ReactNode }) =&amp;gt; {

  // Define values to be shared, here:
  /* These values are often State / derived-State values, setters, methods, 
  etc. */
  const [currentQuestions, setCurrentQuestions] = useState&amp;lt;TQuizQuestion[] | undefined&amp;gt;();
  const [questionIndex, setQuestionIndex] = useState&amp;lt;number&amp;gt;(0);

  // Any more values to be shared...

  /* Since several values are typically shared throughout the app from a 
  Context, it's my preference to put them all in an Object here, then pass this 
  Object to the 'value' property in QuizContext.Provider below. You could make 
  do without this Object below &amp;amp; directly pass all the to-be-shared values to 
  the 'value' property below, but it may look a bit sloppy. */
  const quizContextValues: TQuizContext = {
    currentQuestions,
    questionIndex,
    // Any further names of values to be shared, separated by commas, go here:
  };

  return (
    // Pass Object containing to-be-shared values to 'value' property:
    /* 'children' refers to the components that will have access to 
    the data from this context. They must be wrapped inside this Provider,
    which we'll see in the next step */
    // QuizContext is the name of the Context defined near the top of this file
    &amp;lt;QuizContext.Provider value={quizContextValues}&amp;gt;{children}&amp;lt;/QuizContext.Provider&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Implement the Context’s Provider&lt;/strong&gt;&lt;br&gt;
For the sake of simplicity, let’s pretend we’re making an app whose only function is to provide the user with a quiz to take. In &lt;code&gt;main.tsx&lt;/code&gt;, we need to import the Provider from above, then wrap the components that need its data, inside of it. In this case, it is the &lt;code&gt;&amp;lt;QuizMain /&amp;gt;&lt;/code&gt; component, which, we’ll say, is the parent of some other components relating to the quiz.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;These children of &lt;code&gt;&amp;lt;QuizMain /&amp;gt;&lt;/code&gt; (not seen here, but present in that component) will also have access to the data from &lt;code&gt;&amp;lt;QuizContextProvider&amp;gt;&lt;/code&gt; as long as &lt;code&gt;&amp;lt;QuizMain /&amp;gt;&lt;/code&gt; is wrapped inside &lt;code&gt;&amp;lt;QuizContextProvider&amp;gt;&lt;/code&gt; . This data can be consumed in &lt;code&gt;&amp;lt;QuizMain /&amp;gt;&lt;/code&gt; then passed to its children as props, or it can be consumed in its children by means of a custom hook, which we will see in the next step.&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Any other necessary imports...

// Import Context Provider
import { QuizContextProvider } from "./Contexts/quizContext.tsx";

// Import component that needs data from the Provider
import QuizMain from "./Components/QuizComponents/QuizMain/QuizMain.tsx";

ReactDOM.createRoot(document.getElementById("root")!).render(
  &amp;lt;React.StrictMode&amp;gt;
    &amp;lt;QuizContextProvider&amp;gt;
      &amp;lt;QuizMain /&amp;gt;
      /* Add any other components requiring data from QuizContextProvider 
      &amp;amp; that are not children of QuizMain, here */
    &amp;lt;/QuizContextProvider&amp;gt;
  &amp;lt;/React.StrictMode&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;&amp;lt;QuizMain /&amp;gt;&lt;/code&gt; , along with any other components inside &lt;code&gt;&amp;lt;QuizContextProvider&amp;gt;&lt;/code&gt; , corresponds to the &lt;code&gt;{children}&lt;/code&gt; value in the definition of &lt;code&gt;QuizContextProvider&lt;/code&gt; above, towards the end of the code block in Step 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Access the Context’s data!&lt;/strong&gt;&lt;br&gt;
Now comes the time to use the data from the Context. This is easily done if we create a custom hook for this purpose, so let’s see what that looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Import hook used to consume Context:
import { useContext } from "react";
// Import Context to be consumed:
import { QuizContext } from "../Contexts/quizContext";

// Define custom hook:
export const useQuizContext = () =&amp;gt; {
  // Consume Context &amp;amp; assign to variable:
  const context = useContext(QuizContext);

  /* If value of context is falsy, throw error (this happens if an attempt 
      is made to use the hook in a component not wrapped by the Context 
      Provider): */
  if (!context) {
    throw new Error("useQuizContext must be used inside QuizContext provider.");
  }

  // Else, return the consumed Context:
  return context;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;It’s a good idea to create hooks in their own, separate files. I named the file for the &lt;code&gt;useQuizContext&lt;/code&gt; hook &lt;code&gt;useQuizContext.tsx&lt;/code&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now that we have a custom hook that contains the data in our Context, let’s use the hook to access some data from the Context inside of a component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Import hook:
import { useQuizContext } from "../../../Hooks/useQuizContext";

const QuizMain = () =&amp;gt; {
  // Destructure values from custom hook that are needed in this component:
  const { currentQuestions, questionIndex } = useQuizContext();
  /* These values, defined in QuizContextProvider in our first code block 
     above, are now available to use throughout this component */
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, as long as a component is, in this case, wrapped inside &lt;code&gt;&amp;lt;QuizContextProvider&amp;gt;&lt;/code&gt; , the &lt;code&gt;useQuizContext&lt;/code&gt; hook can be used to pull any data from &lt;code&gt;QuizContext&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;When working on large projects, it is common to see multiple contexts being used. Their Providers can simply be wrapped inside of each other, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Any necessary imports...

ReactDOM.createRoot(document.getElementById("root")!).render(
  &amp;lt;React.StrictMode&amp;gt;
    &amp;lt;MainContextProvider&amp;gt;
      &amp;lt;AnotherContextProvider&amp;gt;
        &amp;lt;QuizContextProvider&amp;gt;
          &amp;lt;QuizMain /&amp;gt;
        &amp;lt;/QuizContextProvider&amp;gt;
      &amp;lt;AnotherContextProvider /&amp;gt;
    &amp;lt;MainContextProvider /&amp;gt;
  &amp;lt;/React.StrictMode&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, &lt;code&gt;&amp;lt;AnotherContextProvider&amp;gt;&lt;/code&gt; &amp;amp; &lt;code&gt;&amp;lt;QuizContextProvider&amp;gt;&lt;/code&gt; would be able to access data from &lt;code&gt;MainContext&lt;/code&gt; by using its custom hook, since they are nested inside &lt;code&gt;&amp;lt;MainContextProvider&amp;gt;&lt;/code&gt;, and so on and so forth down the tree. As you may have gathered, Context Providers in the tree should be sorted from those that contain the most universal data to those that contain the least universal data.&lt;/p&gt;




&lt;p&gt;I hope this article is an answered prayer for those of you who are sick of the infinite complexity of prop drilling. Whether you found this article helpful, or if you would suggest some changes to what I’ve written here, or if you would do things in a different way, I would love to hear from you, so feel free to leave a comment if you are so inclined.&lt;/p&gt;

&lt;p&gt;Peace out &amp;amp; happy coding!&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>tutorial</category>
      <category>reactjsdevelopment</category>
    </item>
    <item>
      <title>How to not Burn Money like Pablo Escobar while Fetching Data from an API in React.js</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Mon, 27 Jan 2025 17:42:56 +0000</pubDate>
      <link>https://forem.com/egroene/how-to-not-burn-money-like-pablo-escobar-while-fetching-data-from-an-api-in-reactjs-kef</link>
      <guid>https://forem.com/egroene/how-to-not-burn-money-like-pablo-escobar-while-fetching-data-from-an-api-in-reactjs-kef</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published to Medium for JavaScript in Plain English on November 10, 2023&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As a developer, you have probably had the chance to use APIs at some point. Many of these APIs, as you may know, make money by charging users every time they fetch data. In React.js, there is one crucial concept you need to be familiar with before working with APIs, and that is the Infinite Loop, which you have likely encountered, even if you have a miniscule amount of experience in React.js.&lt;/p&gt;

&lt;p&gt;As you have perhaps surmised, &lt;strong&gt;you never want to be fetching API data inside of an Infinite Loop&lt;/strong&gt;. Let’s take a look, first, at how we could cause a fetch call to be made inside of an Infinite Loop, then at how we could prevent this from happening.&lt;/p&gt;




&lt;p&gt;In the example below, I am fetching (pun not intended) information about various &lt;code&gt;dogs&lt;/code&gt; stored in a JSON file that runs on json-server, a Node package that is used to simulate a database. I then want to set the state value of &lt;code&gt;allDogs&lt;/code&gt;, an array of objects, to the dogs array of objects stored in the database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* In reality, it's probably best to define this in a separate file 
containing comparable functions */
const getAllDogs = () =&amp;gt; {
  // Returns a promise
  return fetch("http://localhost:3000/dogs").then((response) =&amp;gt; response.json());
};

export function FunctionalApp() {
  const [allDogs, setAllDogs] = useState([]);

  // Don't make the fetch call like this!!!
  getAllDogs().then(setAllDogs);

  // rest of component
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember, every time a component’s state value changes, the component is rendered. So, in the code above, the fetch call is made from scratch every time the component renders, which happens every time the fetch call is made. This nightmarish cycle will continue on forever if we don’t put a stop to it. Any guesses as to how we can do so?&lt;/p&gt;

&lt;p&gt;If your mind jumped to the &lt;code&gt;useEffect&lt;/code&gt; hook, then you have a brilliant one. There are, however, many great tools, such as Tanstack's React Query, that can make handling requests much easier, but I'll just cover the &lt;code&gt;useEffect&lt;/code&gt; way in this article. Here's a look at that in action:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getAllDogs = () =&amp;gt; {
  // Returns a promise
  return fetch("http://localhost:3000/dogs").then((response) =&amp;gt; response.json());
};

export function FunctionalApp() {
  const [allDogs, setAllDogs] = useState([]);

  /* Call the fetch function inside a useEffect callback to prevent an 
  Infinite Loop */
  useEffect(() =&amp;gt; {
    getAllDogs().then(setAllDogs);
  }, []);

  // rest of component
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For those unfamiliar, a &lt;code&gt;useEffect&lt;/code&gt; hook takes two arguments: a callback function, which contains the code for things you would like to happen, and a dependency array, which contains the values of things that would trigger the &lt;code&gt;useEffect&lt;/code&gt; to be called again. In the case that the dependency array is empty, as it is above, the &lt;code&gt;useEffect&lt;/code&gt; will be triggered only when the component is rendered for the first time, so by making the fetch call inside a &lt;code&gt;useEffect&lt;/code&gt; hook, we are preventing a new fetch call from being made every time the component is rendered.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If the dependency-array argument is omitted, the &lt;code&gt;useEffect&lt;/code&gt; behaves the same way as if it were empty, but it is not good practice to do so.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, can you think how a &lt;code&gt;useEffect&lt;/code&gt; hook could translate to a class component? Let's have a look:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class ClassApp extends Component {
  state = {
    allDogs: [],
    // rest of state
  };

  // Setter for allDogs:
  setAllDogs = (newValue) =&amp;gt; {
    this.setState((prevState) =&amp;gt; ({
      ...prevState,
      allDogs: newValue,
    }));
  };

  /* Using a lifecycle method like this prevents an infinite loop caused 
  by a fetch call in a class component */
  componentDidMount() {
    getAllDogs().then((dogs) =&amp;gt; {
      this.setAllDogs(dogs);
    });
  }

  // rest of component
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, using the &lt;code&gt;componentDidMount&lt;/code&gt; lifecycle method accomplishes the same thing as the &lt;code&gt;useEffect&lt;/code&gt; hook with an empty dependency array, thus preventing an infinite loop in a class component.&lt;br&gt;
To connect this all to the title of this article, imagine that you or the company you work for pays a few cents for every fetch call made to an API. If that is called, say, 300 times per second, the cost could add up quickly, and even more so if the application is deployed to users! This mistake of making a fetch call outside of the useEffect hook or a lifecycle method could easily cause thousands of dollars to go up in smoke.&lt;br&gt;
Thank God I didn't have to learn this lesson the hard way; hopefully you will remember this article and avoid learning this lesson the hard way, too.&lt;/p&gt;




&lt;p&gt;Thank you for reading! I hope you learned something. I would like to hear what you think, whether that's in a reaction of some kind, or in a comment. If you have any critiques of what I presented here, I'd also love to hear them. If you think someone could benefit from this article, please share it with them.&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>React.js: What I’ve Learned from My First Project</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Sat, 25 Jan 2025 21:51:15 +0000</pubDate>
      <link>https://forem.com/egroene/reactjs-what-ive-learned-from-my-first-project-g1f</link>
      <guid>https://forem.com/egroene/reactjs-what-ive-learned-from-my-first-project-g1f</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published to Medium for JavaScript in Plain English on April 2, 2023&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Over the past several weeks, I have begun learning another highly sought-after skill in the web development world: React.js. Feeling at least somewhat comfortable with a lot of things in JavaScript, and at the behest of some of my mentors, I figured this was the most logical step to take to reach my career goals. In this article, I will share with you some things I’ve learned about it as a rookie.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;For some context, I have only worked with Class Components in React, never with Functional Components I will not describe the differences here, since I don’t really know anything about Functional Components now. I will likely write an article someday contrasting the two types. Even at the time I write this article, it's recommended by everyone to use Functional Components, but it still pays to know how Class Components work, since older React projects may use them.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For my first project, I was tasked with building a debt calculator, in which the user can enter the Debt Principal, the Interest Rate, how much they want to pay. There are a few stipulations for these input fields, but you can read about those in the project’s README.md (link the GitHub repo is at the end of the article), or you can try it out yourself to see how it works. Once the user ‘submits’ a payment, a payment history item will appear, giving details about the Principal, Interest, &amp;amp; the Balance. Unless the user pays off the entire debt in the first payment, all input fields except the payment field are disabled when the first payment is made; if the entire debt is paid off, the entire form is disabled, &amp;amp; the user can view the history of the final payment, along with a message that they are debt-free.&lt;/p&gt;

&lt;p&gt;I will provide answers to the following questions I had about React while starting to learn about it:&lt;/p&gt;

&lt;p&gt;What is React.js, and why should it be used?&lt;/p&gt;

&lt;p&gt;How do I start building a React App?&lt;/p&gt;

&lt;p&gt;What does a typical component look like?&lt;/p&gt;

&lt;p&gt;How can I share info between components?&lt;/p&gt;

&lt;p&gt;Can I render things conditionally in React?&lt;/p&gt;

&lt;p&gt;How can I deploy a React app?&lt;/p&gt;




&lt;h2&gt;
  
  
  What is React.js, and why should it be used?
&lt;/h2&gt;

&lt;p&gt;React is a front-end JS library (not a framework 😉) ) that makes organizing large-scale projects easier. It was originally developed at Facebook more on that &lt;a href="https://www.youtube.com/watch?v=8pDqJVdNa44" rel="noopener noreferrer"&gt;here&lt;/a&gt;, &amp;amp; is now maintained, of course, by Meta, which also uses it for Instagram. It is now widely used on many sites across the interwebs, such as Airbnb, BBC, Imgur, &amp;amp; Netflix, among many others.&lt;/p&gt;

&lt;p&gt;React code consists of reusable components, which must be located inside the &lt;code&gt;src&lt;/code&gt; folder, &amp;amp; whose names must be in CamelCase form. Many components are written in JSX (JavaScript Syntax Extension), which is a kind of mix between HTML &amp;amp; JS. I call these components ‘reusable’ because they have the same structure &amp;amp; different information may be passed to them &amp;amp; displayed on the site. Components can also be written in normal JS. Different information, such as user account information, can then be passed to these components &amp;amp; they will all display in the same way.&lt;/p&gt;

&lt;h2&gt;
  
  
  How do I start building a React App?
&lt;/h2&gt;

&lt;p&gt;To initialize a React app, enter the following commands into the terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-react-app project-name
cd project-name
npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;npm start&lt;/code&gt; will open the project in your default browser in an empty port.&lt;br&gt;
It usually takes a few minutes for everything to be set up, so maybe do something productive in the meantime, like uploading a silly dance to TikTok, or &lt;a href="https://hogwarts-house-quiz.pages.dev/" rel="noopener noreferrer"&gt;finding out which Hogwarts House you would be sorted into&lt;/a&gt; (yes, I made that quiz).&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The official documentation now recommends using a framework to initialize a React app. I have not used one yet, but you can read more about that here.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  What does a typical component look like?
&lt;/h2&gt;

&lt;p&gt;Like I mentioned, I have only worked with Class Components so far, so I will only cover those in this article. The components I used for my first project are a bit large to put here, so please see the &lt;code&gt;App.js&lt;/code&gt; &amp;amp; the &lt;code&gt;PaymentHistory.jsx&lt;/code&gt; files in the &lt;code&gt;src&lt;/code&gt; folder in the repository linked at the end of the article to see them in action. Nevertheless, typical Class Component may look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Import React &amp;amp; ComponentOne:
import React from "react";
import ComponentOne from "./ComponentOne;

class App extends React.Component {
  /* Add props as params here, in case state values 
  are to be shared with another component */
  constructor(props) {
    super(props);

    // Initialize state values:
    this.state = {
      stateValue1: '',
      stateValue2: ''
    }
  }

  // Add some methods:
  changeFontColor = () =&amp;gt; {
    // do something
  }
  changeFont= () =&amp;gt; {
    // do something
  }

  // Determine what the component should render:
  render() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;p key="pgHeader" onClick={this.changeFontColor}&amp;gt;Header&amp;lt;/p&amp;gt;
        &amp;lt;p key="pgContent" onClick={this.changeFont}&amp;gt;Content&amp;lt;/p&amp;gt;
        &amp;lt;p key="pgFooter"&amp;gt;Footer&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
      // Give ComponentOne access to method changeFont by passing it in as a prop:
      &amp;lt;ComponentOne changeFont={this.changeFont} /&amp;gt;
    )
  }
}
export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that I added a key value to each &lt;code&gt;&amp;lt;p&amp;gt;&lt;/code&gt; element inside the &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt;. These are not necessarily crucial to the ability of the app to function properly, but it is best practice to include them. A unique key value should be added to each child of a parent element inside &lt;code&gt;return()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Like a normal JS Class, the first thing that should come is the &lt;code&gt;constructor()&lt;/code&gt;, followed by &lt;code&gt;super()&lt;/code&gt;. If we wish to share, for example, state values or methods from one class to another, we need to pass in props, short for 'properties', as the parameter for both &lt;code&gt;constructor()&lt;/code&gt; &amp;amp; &lt;code&gt;super()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Then, we should initialize state values. In my debt calculator project, I needed to use multiple state values to track various amounts of money pertaining to the Payment, Principal, Interest Owed, &amp;amp; Balance, but I also used a couple that determined how or if certain things should be rendered. Here's how I used the &lt;code&gt;isDebtFree&lt;/code&gt; state value to enable an input field when it equals &lt;code&gt;false&lt;/code&gt;, &amp;amp; disable it when it is &lt;code&gt;true&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Initialize isDebtFree:
// Should go inside the constructor, but left out here for brevity
this.state = {
  // other state values
  isDebtFree: false
  // other state values
}

// Change isDebtFree to true if payment equals the total remaining balance
// This method will be called upon payment submission
updateValues = () =&amp;gt; {
  // other stuff
  if (newBalance === 0) {
    this.setState({
      isDebtFree: true
    })
   }
}

// Set the disabled property of an input field to equal isDebtFree:
render() {
  return (
    &amp;lt;input disabled={this.state.isDebtFree} /&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we can change state values in Class Components by using a &lt;code&gt;setState&lt;/code&gt; function. Keep in mind that &lt;code&gt;setState&lt;/code&gt; runs asynchronously, so any functionality that requires the updated state values could be put in a callback. However, you should keep these callbacks as simple as possible, or you will end up in the confusing world of 'Callback Hell', so follow the Single-Responsibility Principle as best as you can when creating methods in the component. You should also know that each time state is changed within the component, the component re-renders.&lt;br&gt;
The DOM should not be manipulated directly inside of a method. Doing so is called an 'antipattern'. Notice how I did not access the DOM element directly by setting the disabled attribute inside the method, like so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// DO NOT ACCESS DOM ELEMENTS DIRECTLY INSIDE A METHOD!
updateValues = () =&amp;gt; {
  if (newBalance === 0) {
  document.getElementById('payment').disabled = true;
 }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Instead, parts of HTML elements in &lt;code&gt;return()&lt;/code&gt; should be set to a state value, which could change based on the execution of methods in the component, as I showed you in the code block before the one directly above this paragraph.&lt;/p&gt;

&lt;p&gt;One more thing to note is that the component's &lt;code&gt;return()&lt;/code&gt; expression should be as short as possible, so avoid putting any type of mathematical expressions there, as well as functionality that is defined here. I made this mistake at first when I tried setting the &lt;code&gt;min&lt;/code&gt; &amp;amp; &lt;code&gt;max&lt;/code&gt; values in the payment field, which change based on state values, which change when numbers are input into the Principal &amp;amp; Interest Rate fields, &amp;amp; when a payment is made.&lt;/p&gt;

&lt;p&gt;I instead made a method for each of these values, then set the &lt;code&gt;min&lt;/code&gt; &amp;amp; &lt;code&gt;max&lt;/code&gt; values to what these methods returned. The first method below worked, but it is not exactly a good way to do it in React, as, again, the &lt;code&gt;return()&lt;/code&gt; part of a component should be as short &amp;amp; easy-to-read as possible.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// You could put math operations directly inside elements in return()...
// ... but this is not the best way
render() {
  return (
    &amp;lt;input
      type="number"
      min={
        this.state.principal / 100 +
            (this.state.principal * Number(this.state.interestRate)) / 100 / 12;
      }
      max = {
        this.state.principal +
            (this.state.principal * Number(this.state.interestRate)) / 100 / 12;
      }
    /&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The method below is more in accordance with the spirit of React:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// A BETTER WAY
// Create 2 methods; one returns the min payment possible, the other the max:
getMinPmt = () =&amp;gt; {
  let minPmt =
    this.cleanValue(this.state.principal / 100) +
    this.cleanValue(
      (this.state.principal * Number(this.state.interestRate)) / 100 / 12
    );
  let totalBalance =
    this.state.principal +
    this.cleanValue(
      (this.state.principal * Number(this.state.interestRate)) / 100 / 12
    );
  if (totalBalance &amp;lt;= 100 &amp;amp;&amp;amp; totalBalance &amp;gt; 0) {
    minPmt = totalBalance;
  }
  return this.cleanValue(minPmt);
};
getMaxPmt = () =&amp;gt; {
  let maxPmt =
    this.state.principal + 
    this.cleanValue(
      (this.state.principal * Number(this.state.interestRate)) / 100 / 12
    );
  return this.cleanValue(maxPmt);
};

// Set the min &amp;amp; max values of the input to what the respective method returns:
render() {
  return (
    &amp;lt;input
      type="number"
      min={this.getMinPmt()}
      max={this.getMaxPmt()}
    /&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How can I share info between components?
&lt;/h2&gt;

&lt;p&gt;As we you can see in the first coding block in this article, I passed a method from one component to another using props. Now, let's look at how this second component could access what we passed to it from App in the first code block above. This is what that part looked like, in case you're too lazy to scroll all the way up to see it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Give ComponentOne access to method changeFont by passing it in as a prop:
&amp;lt;ComponentOne changeFont={this.changeFont} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, in &lt;code&gt;ComponentOne&lt;/code&gt;, let's import this method from &lt;code&gt;App&lt;/code&gt; &amp;amp; put it to use:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';

class ComponentOne extends React.Component {
    render() {
       /* 'Import' changeFont method from App.js, which was passed 
       in thru props, &amp;amp; deconstruct from this.props object immediately: */
      const { changeFont } = this.props;
      return (
        &amp;lt;h1 onClick={ changeFont }&amp;gt;HI, I'M A HEADER!&amp;lt;/h1&amp;gt;
      )
    }
}
export default ComponentOne;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, after accessing the &lt;code&gt;changeFont method&lt;/code&gt;, we call it when the &lt;code&gt;h1&lt;/code&gt; we render is clicked.&lt;/p&gt;

&lt;h2&gt;
  
  
  Can I render things conditionally in React?
&lt;/h2&gt;

&lt;p&gt;Yes! React is all about conditionally rendering things. There are a couple ways to do it. You can do this with a method, then set the value of an element in &lt;code&gt;return()&lt;/code&gt; to equal that. So, let's use the debt calculator example again. Let's say we want to display the message "You're debt-free!" if the state value of the balance is 0, &amp;amp; a button that prompts the user to make another payment if the balance is over 0. There are a couple ways we could do this.&lt;/p&gt;

&lt;p&gt;Let's first set the value of this element to what a method returns, based on the conditions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;getMsgOrBtn = () =&amp;gt; {
  let whatToDisplay = &amp;lt;button key='makeAddlPmtBtn'&amp;gt;Make Another Payment&amp;lt;/button&amp;gt;;
  if (this.state.totalBalance === 0) {
    whatToDisplay = &amp;lt;p key='debtFreeMsg'&amp;gt;You're Debt-Free!&amp;lt;/p&amp;gt;;
  }
  return whatToDisplay;
}

// Inside render(){} return():
&amp;lt;div className="messageOrButtonArea"&amp;gt;{this.getMsgOrBtn()}&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using a method may be advantageous, as it allows us to keep the &lt;code&gt;return()&lt;/code&gt; more concise. We can also add more-complex conditions, just like in a normal JS function.&lt;/p&gt;

&lt;p&gt;We can also use a ternary operator inside of &lt;code&gt;return()&lt;/code&gt; to accomplish the same thing:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div className="messageOrButtonArea"&amp;gt;
  {this.state.totalBalance === 0 
    ? &amp;lt;p key="debtFreeMsg"&amp;gt;You're debt-free!&amp;lt;/p&amp;gt; 
    : &amp;lt;button key="makeAddlPmtBtn"&amp;gt;Make another payment&amp;lt;/button&amp;gt;
  }
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If logic is simple enough to be expressed with a ternary operator &amp;amp; it's still easily read, go ahead and use one; otherwise, it's always acceptable to use a method.&lt;/p&gt;

&lt;p&gt;For example, if you have simple conditions &amp;amp; want to display nothing if conditions are not met, you can do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div className="msgOrNothingArea"&amp;gt;
  { (this.state.totalBalance === 0) &amp;amp;&amp;amp; "You're debt-free!" }
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If &lt;code&gt;this.state.totalBalance&lt;/code&gt; strictly equals 0, then the message will display. If not, then nothing will display.&lt;/p&gt;

&lt;h2&gt;
  
  
  How can I deploy a React app?
&lt;/h2&gt;

&lt;p&gt;I deployed my first React project through Netlify, to which I granted access to the project's GitHub repository. Before deploying, you should run &lt;code&gt;npm run build&lt;/code&gt; to build the app for production to the build folder. It bundles React in production mode and optimizes the build for best performance. You can update the site as you normally would another site.&lt;/p&gt;

&lt;p&gt;In your &lt;code&gt;index.html&lt;/code&gt; file, you may need to change a few paths, including the favicon url, in &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;. You should only need to replace '%PUBLIC_URL%' with &lt;code&gt;./&lt;/code&gt;. Look for instructions like this in &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;:&lt;/p&gt;

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




&lt;p&gt;So there were a few things I learned while building my first React project. My knowledge about React does not run all that deep yet, so if you have any suggestions for me or any information to add, please add a comment. If you found it helpful, please leave a nice comment or leave a reaction of some kind, &amp;amp; if you think someone else could benefit from reading this, pass it on to them.&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://react.dev/" rel="noopener noreferrer"&gt;Full React.js Documentation&lt;/a&gt;&lt;br&gt;
&lt;a href="https://hogwarts-house-quiz.pages.dev/" rel="noopener noreferrer"&gt;My First Project in Action&lt;/a&gt;&lt;br&gt;
&lt;a href="https://github.com/EGROENE/react-debt-free-calculator" rel="noopener noreferrer"&gt;Project's GitHub Repository&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>programming</category>
      <category>reactjsdevelopment</category>
    </item>
    <item>
      <title>JavaScript Array Methods, Under the Hood, Part 2/2</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Tue, 21 Jan 2025 17:23:50 +0000</pubDate>
      <link>https://forem.com/egroene/javascript-array-methods-under-the-hood-part-22-30im</link>
      <guid>https://forem.com/egroene/javascript-array-methods-under-the-hood-part-22-30im</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published to Medium for JavaScript in Plain English on February 13, 2023&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Thanks for coming to part two of this series on JS array methods. If this article is your first encounter with the series, and you want to read the first part first, check it out &lt;a href="https://dev.to/egroene/javascript-array-methods-under-the-hood-part-12-257g"&gt;here&lt;/a&gt;. As the title of this article suggests, I’ll be giving you an alternative way to look at a few additional common JS array methods, &amp;amp; that is by using &lt;code&gt;for&lt;/code&gt; loops to accomplish the same tasks. I’ll be covering the &lt;code&gt;Math.max()&lt;/code&gt;, &lt;code&gt;Math.min()&lt;/code&gt;, &lt;code&gt;.reverse()&lt;/code&gt;, &lt;code&gt;.filter()&lt;/code&gt; , &amp;amp; &lt;code&gt;.reduce()&lt;/code&gt; methods. Hopefully, the examples I present here will bring you some clarity, in case you find some of these methods hard to understand. Let’s get started.&lt;/p&gt;




&lt;h2&gt;
  
  
  Math.min() , Math.max()
&lt;/h2&gt;

&lt;p&gt;The purpose of these methods is to return the lowest or the highest number in a series of numbers. You can either enter the numbers as parameters or call this method on an array by passing in the array with the rest operator. Let’s look at some examples, shall we?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// RETURN THE SMALLEST VALUE IN AN ARRAY:
// Using a 'for' loop:
function findMinValueInArray(array) {
  let min = array[0];
  for (let i = 0; i &amp;lt; array.length; i++) {
    let currentNum = array[i];
    if (currentNum &amp;lt; min) {
      min = currentNum;
    }
  }
  return min;
}
findMinValueInArray([33, -5544, 55, 66]); // returns: -5544

// Using Math.min():
function findMinValueInArray(array) {
  return Math.min(...array);
}
findMinValueInArray([33, -5544, 55, 66]); // returns: -5544
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, using &lt;code&gt;Math.min()&lt;/code&gt; requires much fewer steps, reducing your chances of making a mistake along the way. &lt;code&gt;Math.max()&lt;/code&gt; functions in the exact same way, but the ‘for’ loop we could use in its place looks slightly different than that of &lt;code&gt;Math.min()&lt;/code&gt;. Let’s take a look at that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// RETURN THE LARGEST VALUE IN AN ARRAY:
// Using a 'for' loop:
function findMaxValueInArray(array) {
  let max = array[0];
  for (let i = 0; i &amp;lt; array.length; i++) {
    let currentNum = array[i];
    if (currentNum &amp;gt; max) {
      max = currentNum;
    }
  }
  return max;
}
findMaxValueInArray([33, -5544, 66, 55]); // returns: 66

// Using Math.max():
function findMaxValueInArray(array) {
  return Math.max(...array);
}
findMaxValueInArray([33, -5544, 66, 55]); // returns: 66
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  .reverse()
&lt;/h2&gt;

&lt;p&gt;This method can be called on an array in order to reverse the order in which its elements appear. Once done, it overwrites the order of the original array. Let’s see first how we could do this with a &lt;code&gt;for&lt;/code&gt; loop, then by using the method itself:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// REVERSE ORDER OF ARRAY'S ELEMENTS
// Using a 'for' loop:
function reverseArray(array) {
  let reversedArray = [];
  for (let i = array.length - 1; i &amp;gt;= 0; i--) {
    reversedArray.push(array[i]);
  }
  return reversedArray;
}
reverseArray([1, 2, 3, 4, 5]); // returns: [5, 4, 3, 2, 1]

// Using .reverse():
function reverseArray(array) {
  return array.reverse();
}
reverseArray([1, 2, 3, 4, 5]); // returns: [5, 4, 3, 2, 1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Again, using the array method is much more efficient. When using a &lt;code&gt;for&lt;/code&gt; loop, we’d have to declare an empty array, &lt;code&gt;reversedArray&lt;/code&gt; at the beginning of the function, then loop through the given array in reverse, pushing each element to &lt;code&gt;reversedArray&lt;/code&gt;, then return this array once the loop stops running. Even for a relatively simple example like this, the array method makes it much less likely that we’ll mess something up.&lt;/p&gt;

&lt;h2&gt;
  
  
  .filter()
&lt;/h2&gt;

&lt;p&gt;The purpose of this method is to return an array of elements in a given array that satisfy a condition.&lt;/p&gt;

&lt;p&gt;Let’s pretend we have an array of bank accounts, each of which has a &lt;code&gt;balance&lt;/code&gt; property, &amp;amp; let’s return an array of accounts that have no money in them.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Using a 'for' loop:
function getClientWithNoMoney(array) {
  let acctsWithZeroBalance = [];
  for (let account of array) {
    if (account.balance === 0) {
      acctsWithZeroBalance.push(account);
    }
  }
  return acctsWithZeroBalance;
}

// Using .filter():
function getClientWithNoMoney(array) {
  return array.filter((account) =&amp;gt; account.balance === 0);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, if we use a ‘for’ loop, we’d have to complete several more steps than if we simply use the .filter() method, in that we’d need to initialize an empty array to which we push accounts that meet a condition specified in the loop we use to iterate through the array of accounts. Finally, we’d need to return the array containing the appropriate accounts. Again, you can see that we have many more opportunities (maybe that’s not the best word ;) ) of making a mistake if we use a ‘for’ loop instead of the method.&lt;/p&gt;

&lt;h2&gt;
  
  
  .reduce()
&lt;/h2&gt;

&lt;p&gt;The final method I’ll cover, &lt;code&gt;.reduce()&lt;/code&gt;, executes a callback function, as defined by you (or whoever is writing the code), on each element of an array. As it iterates through the array, it passes in the return value from the calculation on the preceding element &amp;amp; finally returns a single value.&lt;/p&gt;

&lt;p&gt;The most simple illustration of &lt;code&gt;.reduce()&lt;/code&gt; can be seen by using it to add up all the values of an array, but let’s take it one step further &amp;amp; use it to calculate the average of an array of numbers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// With 'for' loop:
function getAverage(array) {
  let sum = 0;
  for (let i = 0; i &amp;lt; array.length; i++) {
    sum += array[i];
  }
  return sum / array.length;
}
getAverage([10, 20, 30, 40]); // returns: 25

// With .reduce():
function getAverage(array) {
  return (
    array.reduce((cv, acc) =&amp;gt; {
      return cv + acc;
    }) / array.length;
  );
}
getAverage([10, 20, 30, 40]); // returns: 25
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While using a &lt;code&gt;for&lt;/code&gt; loop, we need to initialize a variable that represents the sum of all numbers in the array, which will be incremented by the current value in each iteration. Then, this sum will be divided by the length of the array to get the average. In this example, using &lt;code&gt;.reduce()&lt;/code&gt; doesn’t save all that much code, but it still reduces (pun intended) the likelihood we’ll make a silly mistake while defining a variable or setting up the loop.&lt;/p&gt;




&lt;p&gt;So there were a few more examples of how some common JS array methods would work if we use 'for' loops instead. The list of JS array methods is pretty extensive, &amp;amp; I think I would be boring you if I wrote about all of them, as I think writing about super techy things like this would stretch the bounds of my creative-writing skills. Either way, I don't have the time do so at the moment, as my goal with this two-part series was to unpack how some of the more-common methods work, &amp;amp; to give you an appreciation for the fact they exist.&lt;/p&gt;

&lt;p&gt;If you would like me to explain how some array methods work, &amp;amp; I haven’t written about them here, let me know in a comment here. Additionally, if you have any praise or criticism, I’d be happy to hear that too. If you think others would find this useful, please share it with them.&lt;/p&gt;

&lt;p&gt;Again, if you’d like to read part one, where I demonstrate how some other array methods would work with loops, go &lt;a href="https://dev.to/egroene/javascript-array-methods-under-the-hood-part-12-257g"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
      <category>programming</category>
    </item>
    <item>
      <title>JavaScript Array Methods, Under the Hood (Part 1/2)</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Tue, 21 Jan 2025 17:06:38 +0000</pubDate>
      <link>https://forem.com/egroene/javascript-array-methods-under-the-hood-part-12-257g</link>
      <guid>https://forem.com/egroene/javascript-array-methods-under-the-hood-part-12-257g</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published to Medium for JavaScript in Plain English on January 28, 2023&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In this article, I’ll be showing you how the JavaScript array methods of &lt;code&gt;.map()&lt;/code&gt; , &lt;code&gt;.includes()&lt;/code&gt; , &lt;code&gt;.concat()&lt;/code&gt; , &amp;amp; &lt;code&gt;.flat()&lt;/code&gt; work by accomplishing the same thing using &lt;code&gt;for&lt;/code&gt; loops. Those of you efficient-minded people out there screaming at me that using &lt;code&gt;for&lt;/code&gt; loops takes more time, looks clunkier, makes it harder for coworkers and/or managers to understand, etc. may have a point; however, you will gain a deeper understanding of array methods, as well as a deeper appreciation for the fact that they exist, once you finish reading. Anyway, to make you efficient-minded readers happy, let’s dive right into it.&lt;/p&gt;




&lt;h2&gt;
  
  
  .map()
&lt;/h2&gt;

&lt;p&gt;This array method creates a new array from calling a function for every item in a given array. It calls the function only once for each element that is not empty. It doesn’t change the original array whatsoever.&lt;/p&gt;

&lt;p&gt;Let’s say we are doing work for a bank &amp;amp; we want to compile a list of all client names as they appear in the data structure. The most-efficient way to do this would be to use the &lt;code&gt;.map()&lt;/code&gt; method, but let’s first take a look at how we could do this with a ‘for’ loop:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const bankAccounts = [
  {
    id: 1,
    name: "Susan",
    balance: 100.32,
    deposits: [150, 30, 221],
    withdrawals: [110, 70.68, 120],
  },
  { id: 2, name: "Morgan", balance: 1100.0, deposits: [1100] },
  {
    id: 3,
    name: "Joshua",
    balance: 18456.57,
    deposits: [4000, 5000, 6000, 9200, 256.57],
    withdrawals: [1500, 1400, 1500, 1500],
  },
  { id: 4, name: "Candy", balance: 0.0 },
  { id: 5, name: "Phil", balance: 18, deposits: [100, 18], withdrawals: [100] },
];

// Loop through data structure, then use 'for' loop to access the name from each account &amp;amp; push it to acctNames array:
function getAllClientNames(array) {
  let acctNames = [];
  for (let acct of array) {
    acctNames.push(acct.name);
  }
  return acctNames;
}
// Get all client names from bankAccounts:
getAllClientNames(bankAccounts); // returns: ['Susan', 'Morgan', 'Joshua', 'Candy', 'Phil']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We must first create an empty array to which we will push the values we want to it. Then, we need to run a &lt;code&gt;for&lt;/code&gt; loop through the given array, in this case &lt;code&gt;bankAccounts&lt;/code&gt;, then push the name of the current account to it, then finally return it once the loop has finished running.&lt;/p&gt;

&lt;p&gt;Now, let’s see how this looks if we use the &lt;code&gt;.map()&lt;/code&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Destructure data structure's elements to make array of all account names:
function getAllClientNames(array) {
  return array.map(function(acct) {
    return acct.name;
  });
}
// Get all client names from bankAccounts:
getAllClientNames(bankAccounts); // returns: ['Susan', 'Morgan', 'Joshua', 'Candy', 'Phil']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, using the array method requires fewer steps, reducing the chance that we’ll screw something up along the way. All we need to do here is apply the method to the given array, then call a function, which takes in a parameter by which we’d like to iterate through the array, then return the name from that parameter, which is a bank account in the bankAccounts array.&lt;/p&gt;

&lt;h2&gt;
  
  
  .includes()
&lt;/h2&gt;

&lt;p&gt;This method can be called on an array to determine if it contains a given value, &amp;amp; returns either &lt;code&gt;true&lt;/code&gt; or &lt;code&gt;false&lt;/code&gt; .&lt;/p&gt;

&lt;p&gt;Let’s create a function that takes an &lt;code&gt;array&lt;/code&gt; &amp;amp; a &lt;code&gt;value&lt;/code&gt; as its parameters, &amp;amp; determines if the &lt;code&gt;array&lt;/code&gt; contains the &lt;code&gt;value&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function doesArrayInclude(array, value) {
  let isIncluded = false
  for (let elem of array) {
    if (elem === value) {
      isIncluded = true;
    }
  }
  return isIncluded; // returns 'true' if any element in the array is strictly equal to the given value; otherwise, it returns 'false'
}
doesArrayInclude([1, 1, 2, 3, 5], 6); // returns: false
doesArrayInclude([1, 1, 2, 3, 5], 3); // returns: true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we’re going to use a ‘for’ loop to check if the &lt;code&gt;array&lt;/code&gt; includes the given value, it’s best to assign a variable, &lt;code&gt;isIncluded&lt;/code&gt;, to a default value of &lt;code&gt;false&lt;/code&gt;. Then, we can use a ‘for…of’ loop to check if each element in the array is equal to the given value. If so, the value of &lt;code&gt;isIncluded&lt;/code&gt; becomes &lt;code&gt;true&lt;/code&gt;; otherwise, it remains &lt;code&gt;false&lt;/code&gt;. Then, we return this variable at the end of the function.&lt;/p&gt;

&lt;p&gt;Here’s how it looks if we use the &lt;code&gt;.includes()&lt;/code&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function doesArrayInclude(array, value) {
  return array.includes(value);
}
doesArrayInclude([1, 1, 2, 3, 5], 6); // returns: false
doesArrayInclude([1, 1, 2, 3, 5], 3); // returns: true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  .concat()
&lt;/h2&gt;

&lt;p&gt;This array method puts two or more arrays together into one array, which this method returns. It does not change any elements in either array.&lt;/p&gt;

&lt;p&gt;Let’s create a function that concatenates two arrays, using &lt;code&gt;for&lt;/code&gt; loops:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function concatArrays(arr1, arr2) {
  let concatenatedArray = [];
  for (let elem of arr1) {
    concatenatedArray.push(elem);
  }
  for (let elem of arr2) {
    concatenatedArray.push(elem);
  }
  return concatenatedArray;
}
concatArrays([0, 1, 2], [5, 6, 7]); // returns: [0, 1, 2, 5, 6, 7]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Above, we first have to declare an empty array, &lt;code&gt;concatenatedArray&lt;/code&gt;, to which we then push each element of the two given arrays, using &lt;code&gt;for&lt;/code&gt; loops. Then, we’ll need to return this array at the end, of course.&lt;/p&gt;

&lt;p&gt;Now, with the &lt;code&gt;.concat()&lt;/code&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function concatArrays(arr1, arr2) {
  return arr1.concat(arr2);
}
concatArrays([0, 1, 2], [5, 6, 7]); // returns: [0, 1, 2, 5, 6, 7]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  .flat()
&lt;/h2&gt;

&lt;p&gt;When this method is called on an array, it extracts all elements in any nested arrays &amp;amp; puts them all into one, single array. This method takes a parameter, which specifies how deep the nested array should be flattened, so, for example, if there is an array, inside an array, inside an array, a parameter of ‘2’ should be passed for all values to appear as single elements in the flattened array, as . The default parameter is ‘1’. It can also be used to remove empty elements inside an array, such as empty spaces.&lt;/p&gt;

&lt;p&gt;In this example, we’ll flatten one array one level deep, using ‘for’ loops &amp;amp; with the method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// FLATTEN ARRAY AT ONE LEVEL DEEP:
// Flatten array with 'for' loop:
function flatArrays(array) {
  let flattenedArray = [];
  for (let elem of array) {
    if (Array.isArray(elem)) {
      for (let subElem of elem) {
        flattenedArray.push(subElem);
      }
    } else {
      flattenedArray.push(elem);
    }
  }
  return flattenedArray;
}
flatArrays([1, 2, 3, [4, [5, 6]], 10]; // returns: [1, 2, 3, 4, [5, 6], 10]

// Flatten array with .flat():
function flatArrays(array) {
  return array.flat();
}
flatArrays([1, 2, 3, [4, [5, 6]], 10]; // returns: [1, 2, 3, 4, [5, 6], 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When using &lt;code&gt;for&lt;/code&gt; loops, we again need to define an empty array, &lt;code&gt;flattenedArray&lt;/code&gt;, to which we will eventually push certain values. Then, we loop through the given array; if the element is itself an array, we loop through this one as well, pushing each value to &lt;code&gt;flattenedArray&lt;/code&gt;. If the element in the first loop is not an array, we simply push it to &lt;code&gt;flattenedArray&lt;/code&gt;. Using the &lt;code&gt;.flat()&lt;/code&gt; method, we could simply call it on the given array &amp;amp; return the result of this method call.&lt;/p&gt;

&lt;p&gt;Now, let’s flatten an array at two levels deep. As you can see, this is super fun to do with &lt;code&gt;for&lt;/code&gt; loops…&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// FLATTEN ARRAY AT TWO LEVELS DEEP:
// Flatten array with 'for' loop:
function flatArrays(array) {
  let flattenedArray = [];
  for (let elem of array) {
    if (Array.isArray(elem)) {
      for (let subElem of elem) {
        // Check if there's an array inside of a first-level array:
        if (Array.isArray(subElem)) {
          for (let subSubElem of subElem) {
            // If so, push elements in second-level array to flattenedArray:
            flattenedArray.push(subSubElem);
          }
        // If not, push elements in first-level array to flattenedArray:
        } else {
          flattenedArray.push(subElem);
        }
      }
    } else {
      flattenedArray.push(elem);
    }
  }
  return flattenedArray;
}
flatArrays([1, 2, 3, [4, [5, 6]], 10]; // returns: [1, 2, 3, 4, 5, 6, 10]

// Flatten array with .flat():
function flatArrays(array) {
  return array.flat(2);
}
flatArrays([1, 2, 3, [4, [5, 6]], 10]; // returns: [1, 2, 3, 4, 5, 6, 10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, the code becomes convoluted very quickly if we use ‘for’ loops to flatten arrays at levels higher than one, as we’d need to add a nested loop for every level. However, if we use the &lt;code&gt;.flat()&lt;/code&gt; method, all we need to do is pass in a number that corresponds to the number of levels we wish to flatten, as the method’s parameter.&lt;/p&gt;

&lt;p&gt;If you wish to flatten a gigantic array that contains an unknown number of subarrays, you could pass in some astronomical, virtually infinite number, like 203,345,976,997 as the method’s parameter, &amp;amp; each item in the base array, as well as those in all subarrays, will be returned as individual elements in the new array, &amp;amp; any empty elements will not appear in this new array.&lt;/p&gt;




&lt;p&gt;There you have it, some examples of how some common JS array methods would work if we use ‘for’ loops instead. As the title suggests, part two will be coming soon.&lt;/p&gt;

&lt;p&gt;If you have any comments or questions, I’d be happy to respond. If you found this article helpful, feel free to leave a reaction or a nice comment. If you think others would find this useful, please share it with them.&lt;br&gt;
Click &lt;a href="https://dev.to/egroene/javascript-array-methods-under-the-hood-part-22-30im"&gt;here&lt;/a&gt; to read part two of this two-part series, where I show how further array methods would work with loops!&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
      <category>programming</category>
    </item>
    <item>
      <title>How to Populate HTML Dynamically with Data from An API</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Thu, 16 Jan 2025 14:39:10 +0000</pubDate>
      <link>https://forem.com/egroene/how-to-populate-html-dynamically-with-data-from-an-api-11ij</link>
      <guid>https://forem.com/egroene/how-to-populate-html-dynamically-with-data-from-an-api-11ij</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published to Medium for JavaScript in Plain English on November 14, 2022&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As a web developer (and as a software developer in general), it is of utmost importance that you learn how to work with Application Programming Interfaces (APIs). To explain briefly, an API is a collection of data that you can access by using the &lt;code&gt;fetch()&lt;/code&gt; method in JavaScript. Instead of all that data being stored locally, it’s stored on another server somewhere &amp;amp; you can access all or part of the data when you need to. You will need to display that data on a certain part of your website or application &amp;amp; at a certain time.&lt;/p&gt;

&lt;p&gt;In the example I write about here, I will walk you through how I fetched data from an API containing info on Harry Potter characters to how I displayed that data on the page. Little did I know, retrieving the API data &amp;amp; displaying it would actually be one of the easiest parts of the project, but that’s a story for another day if I ever feel inclined to write about that. Enough babble, let’s get started.&lt;/p&gt;




&lt;h2&gt;
  
  
  Fetch API Data
&lt;/h2&gt;

&lt;p&gt;First, let’s assign the part of the HTML document (&lt;code&gt;chars-container&lt;/code&gt;) to a variable, which will eventually be populated with the character information we fetch from the API:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const charsSection = document.getElementById('chars-container');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, let’s assign the URL of the API to a variable (makes the code much neater when we fetch the API data) &amp;amp; create an asynchronous function, since we need to await the retrieval of data from the API):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Assign API URL to variable:
const charsURL = 'https://hp-api.herokuapp.com/api/characters';

// Function to return array of filtered character data objects from API:
async function getChars() {
    // Fetch API data:
    const response = await fetch(charsURL);

    // Convert API data to JSON:
    const allCharsArr = await response.json();

    // Push into iterable array, newCharsArr, all characters that are human &amp;amp; contain an image URL:
    let newCharsArr = [];
    for (let i = 0; i &amp;lt; allCharsArr.length; i++) {
        if (allCharsArr[i].species === 'human' &amp;amp;&amp;amp; allCharsArr[i].image.length &amp;gt; 0) {
            newCharsArr.push(allCharsArr[i]);
        }
    }
    return newCharsArr;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function, &lt;code&gt;getChars()&lt;/code&gt;, fetches the API data, converts that data to JavaScript Object Notation (JSON), then pushes each data object into a new, iterable array, &lt;code&gt;newCharsArr&lt;/code&gt;, as long as the object’s &lt;code&gt;.image&lt;/code&gt; property length was greater than 0 (all of the &lt;code&gt;.image&lt;/code&gt; properties in the API that were not empty contained a valid image URL) &amp;amp; as long as the object’s &lt;code&gt;.species&lt;/code&gt; property is equal to ‘human’.&lt;/p&gt;

&lt;p&gt;You may want to filter the API data for several reasons, one of which may that the API is incomplete, as is the case here. You can normally get around this issue if you know how to manipulate data in JS objects with loops, conditional statements, etc., as long as it satisfies your project requirements or until the API is complete. In this case, not every character data object in the API contained an image, &amp;amp; this was necessary for the project, so I filtered out data objects that didn’t contain an image.&lt;/p&gt;

&lt;p&gt;So, the &lt;code&gt;getChars()&lt;/code&gt; function above returns an iterable array containing data objects from the API whose &lt;code&gt;.species&lt;/code&gt; property is ‘human’ &amp;amp; whose &lt;code&gt;.image&lt;/code&gt; property length is greater than 0.&lt;/p&gt;

&lt;h2&gt;
  
  
  Populate the Page with Retrieved API Data
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function buildPage() {
    const newCharsArr = await getChars();
    // Populate character cards' HTML:
    for (let i = 0; i &amp;lt; newCharsArr.length; i++) {
        // Populate homepage (make cards visible by default)
        charsSection.innerHTML += 
            "&amp;lt;div class='char-card' data-name='" + newCharsArr[i].name.toLowerCase().replace(/\s/g, '-') + "' data-house='"
            + newCharsArr[i].house.toLowerCase().replace(/\s/g, '-') + "'&amp;gt;" 
                + "&amp;lt;div class='char-img-container'&amp;gt;"
                + "&amp;lt;button class='favs-btn' title='Add to Favorites'&amp;gt;&amp;lt;i class='far fa-heart'&amp;gt;&amp;lt;/i&amp;gt;&amp;lt;/button&amp;gt;"
                + "&amp;lt;img src='" + newCharsArr[i].image + "'&amp;gt;"
                + "&amp;lt;/div&amp;gt;"
                + "&amp;lt;header class='char-header'&amp;gt;" + newCharsArr[i].name + "&amp;lt;/header&amp;gt;"
                + "&amp;lt;p&amp;gt;&amp;lt;span&amp;gt;Ancestry: &amp;lt;/span&amp;gt;" + newCharsArr[i].ancestry + "&amp;lt;/p&amp;gt;"
                + "&amp;lt;p id='house-homepage'&amp;gt;&amp;lt;span&amp;gt;House: &amp;lt;/span&amp;gt;" + newCharsArr[i].house + "&amp;lt;/p&amp;gt;"
                + "&amp;lt;p&amp;gt;&amp;lt;span&amp;gt;Actor/Actress: &amp;lt;/span&amp;gt;" + newCharsArr[i].actor + "&amp;lt;/p&amp;gt;"
            + "&amp;lt;/div&amp;gt;"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember the &lt;code&gt;charsSection&lt;/code&gt; variable we declared at the beginning? The function above, &lt;code&gt;buildPage()&lt;/code&gt; , populates that with the filtered data objects we retrieved with the &lt;code&gt;getChars()&lt;/code&gt; function. Since &lt;code&gt;getChars()&lt;/code&gt; was asynchronous &amp;amp; had to await the retrieval of data from the API, &lt;code&gt;buildPage()&lt;/code&gt; must also be asynchronous &amp;amp; await the calling of &lt;code&gt;getChars()&lt;/code&gt; before it can populate the &lt;code&gt;innerHTML&lt;/code&gt; of &lt;code&gt;charsSection&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;I assigned the iterable array of filtered data objects to &lt;code&gt;newCharsArr&lt;/code&gt; in &lt;code&gt;buildPage()&lt;/code&gt; above. For every item in newCharsArr`, we dynamically create a card containing select information (character’s image, name, ancestry, Hogwarts house, &amp;amp; actor/actress) about the character which that item represents.&lt;/p&gt;




&lt;p&gt;Here’s an excerpt of the page once the characters’ information is fetched, filtered, and the page is populated with it. I did not include any info about the styling, but if you’d like to see my code for the entire project, go &lt;a href="https://github.com/EGROENE/api-project" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

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




&lt;p&gt;So there you have it, a brief example of how to dynamically populate a webpage with information fetched from an API. If you have any comments or questions, I’d be happy to respond. If you found this article helpful, I’d appreciate a nice comment or a clap or two, so I can know what content my readers like. If you think others would find this useful, please share it with them.&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;

&lt;h2&gt;
  
  
  Links
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://egroene.github.io/api-project/" rel="noopener noreferrer"&gt;Project in action&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/EGROENE/api-project" rel="noopener noreferrer"&gt;Project repo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction" rel="noopener noreferrer"&gt;MDN Web Docs ‘Introduction to Web APIs’&lt;/a&gt;&lt;/p&gt;

</description>
      <category>tutorial</category>
      <category>api</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>How to Use JavaScript to Reduce HTML Code: A Simple Example</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Wed, 15 Jan 2025 18:20:48 +0000</pubDate>
      <link>https://forem.com/egroene/how-to-use-javascript-to-reduce-html-code-a-simple-example-4469</link>
      <guid>https://forem.com/egroene/how-to-use-javascript-to-reduce-html-code-a-simple-example-4469</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on Medium for JavaScript in Plain English on September 28, 2022&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A huge part of being a good programmer is keeping your code as easy-to-debug as possible, as well as writing code that is easy to scale without making mistakes. If you’re working on, say, a blog website, the amount of content on the site will grow over time, so every time you come back to the project, you want to be able to do so quickly &amp;amp; without making mistakes, which could harm your client’s reputation by making the site look bad.&lt;/p&gt;

&lt;p&gt;Luckily for us, God (or rather, Brendan Eich) created JavaScript, which can help make our code more efficient &amp;amp; easier to debug. In this article, I will give a brief example of how I used JS to do exactly this while building a blog website.&lt;/p&gt;

&lt;p&gt;On a typical blog website, you should make it easy for visitors to find you on social media, as this is the best way to grow a following online. One way to do this is to display links to your social media channels on every page, maybe in a footer, or in a panel that sits on the side of the screen at all times, as seen in the photo below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fisxjgi066ko5plfxkqjk.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fisxjgi066ko5plfxkqjk.jpg" alt="Panel with social links (encircled)" width="667" height="323"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you want this panel to display on all pages of the site, one way to accomplish this would be to copy &amp;amp; paste several lines (14 in this case) of the same code onto every HTML page in the project. These lines are pictured below:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffv2dqajt0lf5iy1my87e.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffv2dqajt0lf5iy1my87e.jpg" alt="HTML to create the social media panel, as seen in the first picture in this article" width="475" height="241"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Fourteen lines of code may not seem like much to you, and, in a way, you’re right. It really wouldn’t be that difficult to just copy &amp;amp; paste these onto every new HTML page you create, especially if the project is small. However, it makes the code clunkier, meaning the page won’t load as soon as it would with fewer lines, as well as more difficult to modify or debug. In the photo above, I put hashtags in the &lt;code&gt;href&lt;/code&gt; part of the anchor tags, as this is only a demo.&lt;/p&gt;

&lt;p&gt;However, in a realistic situation, these would link to a real social media profile’s URL. So, imagine your client changes their Instagram username. This could lead to the URL, that is put into &lt;code&gt;href&lt;/code&gt;, being different than it was before. As the developer, you would have to get that new link &amp;amp; paste it into every single HTML page &amp;amp; in the appropriate spot. Not only is this cumbersome, but it could lead to errors if you are not careful, especially if you get bored doing this repetitive task.&lt;/p&gt;

&lt;p&gt;A better way to accomplish this would be to use JS. In the picture below, I created functionality in JS to add these links to a &lt;code&gt;div&lt;/code&gt; that is already present on all HTML pages, which is stored in the variable &lt;code&gt;socialsPanel&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg8xdmx7k0f31xudg04qj.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg8xdmx7k0f31xudg04qj.jpg" alt="Functionality to populate the social panel’s HTML" width="680" height="137"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When we use a function like this, we only need to enter each link’s information in one place: inside this function. So, if the information for a particular link changes, we would only need to change it here, instead of on every single HTML page if we hadn’t used JS &amp;amp; had instead used the copy/paste method. If we wanted to add or subtract links, we would only have to do so in this function.&lt;/p&gt;

&lt;p&gt;Not only is this a huge timesaver, but, as mentioned before, it saves lines of HTML code, since to populate a page with these links, we wouldn’t need to copy &amp;amp; paste the 13* lines of code into every HTML document, only call the function upon loading the page. Calling this function, &lt;code&gt;popSocialsPanel()&lt;/code&gt;, on a page, as you can see underlined in red in the next photo, adds no new line of code (just ignore the other functions there for now):&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Lines that contain the series of links in this case, since we kept the div , to which we wanted to add the links, on each HTML document&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9x72sp7k42ws1l2290d4.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9x72sp7k42ws1l2290d4.jpg" alt="Call function upon loading of a page where you want the social media panel to display" width="615" height="26"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let’s take a minute to do the math on all of this. Not including the comments, we added 9 new lines of code in our JS file, which we only have to write once, while subtracting 13 lines of HTML code. So, if our project had only one HTML document, we would still be saving 4 lines of code, which is good, but we would be saving 13 lines of code while implementing this functionality for every HTML document we add to the project, which is great.&lt;/p&gt;

&lt;h2&gt;
  
  
  On this particular project, I have saved 56 lines of code, so far, by using this method. For every page for a blog post I add, I will be saving another 13.
&lt;/h2&gt;

&lt;p&gt;I hope you found this relatively simple example helpful, but I guess the takeaway from this article would be that you should develop a certain instinct as a programmer; if you feel that you are repeating yourself while writing code, there is probably a more-efficient way to write it.&lt;/p&gt;

&lt;p&gt;If you have any comments or questions, I’d be happy to respond. If you found this article helpful, I’d appreciate a nice comment or a clap or two, so I can know what content my readers like. If you think others would find this useful, please share it with them.&lt;/p&gt;

&lt;p&gt;Thanks for reading!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>html</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Let’s Create a Random-Color Generator!</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Mon, 13 Jan 2025 17:19:48 +0000</pubDate>
      <link>https://forem.com/egroene/lets-create-a-random-color-generator-1c6l</link>
      <guid>https://forem.com/egroene/lets-create-a-random-color-generator-1c6l</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on Medium for JavaScript in Plain English on August 15, 2022&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you’re new to JavaScript, you have probably learned a lot about how the data types, logic, functions, etc. work. This is good; to use JS in more-complicated projects someday, you need to start with the fundamentals. However, depending on your attention span, you may soon start feeling the strong desire to put your JS skills to work on an actual website. Doing so can be a bit complicated (but not as complicated as Regular Expressions, amirite), but one of the simpler ones you can start with is, you guessed it, a random-color generator. In this article, I’ll take you through the steps I used to build one myself.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Add boilerplate HTML
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset="UTF-8"&amp;gt;
  &amp;lt;meta http-equiv="X-UA=Compatible" content="IE=edge"&amp;gt;
  &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
  &amp;lt;title&amp;gt;Random-Color Generator&amp;lt;/title&amp;gt;

  &amp;lt;!--Link stylesheets--&amp;gt;
  &amp;lt;link rel="stylesheet" href="./styling.css"&amp;gt;
  &amp;lt;link rel="stylesheet" href="./responsive.css"&amp;gt;
&amp;lt;/head&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you’re using VS Code, you can type '!' into the empty HTML document, then press 'Enter' to add this part (not sure about other text editors) if you didn’t know that already. Below the boilerplate, I added links to the CSS documents I used for this project. I recommend keeping your CSS in a separate file, just so that your HTML file doesn’t get too big &amp;amp; complicated. Since the JavaScript we’ll be writing is not super long, I’ll be adding that directly to the HTML file inside the &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag, which you’ll see in step 3. If you wanted to have a separate JS file and link it to your HTML file, you could do this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script type="text/javascript" src="main.js"&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Build the HTML ‘skeleton’
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;body onload="getNewColor()"&amp;gt;
  &amp;lt;div id="heading"&amp;gt;
    &amp;lt;h1&amp;gt;Need a random color? Then you've come to the right place!&amp;lt;/h1&amp;gt;
    &amp;lt;h2&amp;gt;Please select a color by clicking the button below.&amp;lt;/h2&amp;gt;
  &amp;lt;/div&amp;gt;
  &amp;lt;div class="color"&amp;gt;
    &amp;lt;span id="hex"&amp;gt;&amp;lt;/span&amp;gt;
    &amp;lt;button onclick="getNewColor()"&amp;gt;Get New Color!&amp;lt;/button&amp;gt;
  &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we’ve added the boilerplate HTML &amp;amp; linked our CSS documents in the &lt;code&gt;&amp;lt;head&amp;gt;&lt;/code&gt;, let’s add the body &amp;amp; build out our HTML. As you can see, the &lt;code&gt;getNewColor()&lt;/code&gt; function will run whenever the page loads. More on this function in the following steps.&lt;/p&gt;

&lt;p&gt;In the picture above, I add a &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt;, which contains a couple of headers, letting the user know where they are &amp;amp; what to do. I then add another &lt;code&gt;&amp;lt;div&amp;gt;&lt;/code&gt;, which contains a &lt;code&gt;&amp;lt;span&amp;gt;&lt;/code&gt; tag, which will eventually be populated with a HEX code and will display as text on the page. Next, I insert a button that the user clicks to generate a new HEX code. This is done by the &lt;code&gt;getNewColor()&lt;/code&gt; function, which I will explain soon.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Add JavaScript!
&lt;/h2&gt;

&lt;p&gt;Now we are at the point where the real magic starts to happen. Are you excited? I can tell. Here’s how you do that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
  function getNewColor() {
    let symbols = "0123456789ABCDEF";
    let color = "#";

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

&lt;/div&gt;



&lt;p&gt;For a relatively simple program like this, we can accomplish what we need to with only one function, the aforementioned &lt;code&gt;getNewColor()&lt;/code&gt; function. For this generator, let’s use HEX codes to determine the color, but using RGB values is also possible.&lt;/p&gt;

&lt;p&gt;Let’s first put all the possible HEX characters (integers 0–9 &amp;amp; letters A-F) in the form of a string, into a variable called &lt;code&gt;symbols&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Then, let’s initialize the &lt;code&gt;color&lt;/code&gt; variable with a hash mark in the form of a string. This variable will be mutated in the loop described below.&lt;/p&gt;

&lt;p&gt;Let’s now make a loop that runs 6 times, since there are 6 values in a HEX code. For every loop iteration, a single random value from the &lt;code&gt;symbols string&lt;/code&gt; is added to the variable &lt;code&gt;color&lt;/code&gt;, which, if you remember, starts with # in string form. At this point, whenever we call the &lt;code&gt;getNewColor()&lt;/code&gt;, we get a new HEX code. Now, let’s apply that code to our HTML page.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;In my experience, it’s worked best to put the &lt;code&gt;&amp;lt;script&amp;gt;&lt;/code&gt; tag at the end of the &lt;code&gt;&amp;lt;body&amp;gt;&lt;/code&gt; tag. Some would vehemently argue otherwise, and they may have a point, but I’m not going to discuss that in this article. Please have a keyboard war in the comment section below if you feel inclined, as it’s good for engagement.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Apply JS to HTML file
&lt;/h2&gt;

&lt;p&gt;Cool, we now have a function that gives us a random HEX code. However, this is useless unless we apply it to our HTML. In this case, it’d be nice to change the background of the entire page, so the user can have a preview of the random color, and to put the HEX code in text format, so they can copy it. We’ll first need to define these behaviors in our function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// continuing getRandomColor()...
    document.body.style.background = color;
    document.getElementByID("hex").textContent = color;
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Still operating inside the &lt;code&gt;getNewColor()&lt;/code&gt; function, we can access the &lt;code&gt;background&lt;/code&gt; styling property with the first line of code you see in the above photo. We could have also used &lt;code&gt;backgroundColor&lt;/code&gt;, which, by the way, translates to &lt;code&gt;background-color&lt;/code&gt; in CSS. In this step, we set the variable &lt;code&gt;color&lt;/code&gt;, which we randomly defined in the loop, as the background color for the page.&lt;/p&gt;

&lt;p&gt;In the second line of code, we access the previously defined &lt;code&gt;&amp;lt;span&amp;gt;&lt;/code&gt; tag by its id, ‘hex’. To add the variable &lt;code&gt;color&lt;/code&gt; in text form, we can use the method &lt;code&gt;.textContent&lt;/code&gt;, which I’ve used here, or the &lt;code&gt;.innerHTML&lt;/code&gt; method, to append color to the &lt;code&gt;&amp;lt;span&amp;gt;&lt;/code&gt; tag. See the link at the end of this article to read more on the difference between these. In the way we laid out our HTML above, this text will appear directly above the button so the user can see the exact color displayed &amp;amp; copy it if they want.&lt;/p&gt;

&lt;p&gt;Altogether, our JS looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
        function getNewColor() {
            let symbols = '0123456789ABCDEF';
            let color = '#'
            for (let i = 0; i &amp;lt; 6; i++) { // Hex code can only go up to 6, so i &amp;lt; 6. This loop runs once for every function call.
                color += symbols[Math.floor(Math.random() * 16)]; // 16 because of all the different possibilities in a hex code
            }
            document.body.style.background = color; // changes the background of the body to the value of var color
            document.getElementById("hex").textContent = color; /* text value of var color (current color's hex code) is displayed above the button &amp;amp; inside the span tag */
        }
    &amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Tell the program when to run the function
&lt;/h2&gt;

&lt;p&gt;There’s no point in making a function if we never run it, so let’s now tell our program when our getNewColor() function should be called. In this instance, let’s run getNewColor() whenever the page loads &amp;amp; when the ‘Get New Color!’ button is clicked. Here’s how we do that:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Run getNewColor() upon loading of page:
&amp;lt;body onload="getNewColor()"&amp;gt;

// Run getNewColor() when clicking "Get New Color!" button:
&amp;lt;button onclick="getNewColor()"&amp;gt;Get New Color!&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  6. Add styling
&lt;/h2&gt;

&lt;p&gt;You may do this part as you wish or not at all, but here is the styling I used on this project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/* styling.css */
body {
    margin: 0;
    padding: 0;
    font-family: 'Courier New', Courier, monospace;
}

#heading {
    background-color: rgba(0, 0, 0, 0.4);
    color: white;
    text-align: center;
    padding: 16px;
}

.color {
    text-align: center;
    background-color: rgba(0, 0, 0, 0.4);
    padding: 48px 32px;
    margin: 136px 384px;
}

#hex, #rgb {
    display: block;
    color: white;
    font-size: 40px;
    text-transform: uppercase;
    margin-bottom: 24px
}

#rgb {
    font-size: 32px;
}

.color button {
    background: none;
    outline: none;
    color: white;
    border: 3px solid white;
    cursor: pointer;
    font-size: 24px;
    padding: 8px;
    font-family: 'Courier New', Courier, monospace;
}

/* responsive.css */
@media screen and (max-width: 768px) {
    .color {
        margin: 118px 213px;
    }   

    #hex {
        font-size: 32px;
    }

    .color button {
        font-size: 20px;
        padding: 3px;
    }
}

@media screen and (max-width: 425px) {
    #heading {
        font-size: small;
    }

    .color {
        margin: 89px 66px;
    }


}

@media screen and (max-width: 325px) {
    .color {
        margin: 101px 66px;
    }

    #hex {
        font-size: 25px;
    }

    .color button {
        font-size: 14px;
        padding: 8px;
    }
}

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  7. Let’s test it out!
&lt;/h2&gt;

&lt;p&gt;If you correctly followed the steps above, a random color will be generated when the page loads, as well as when you click the button. The background of the page will be set to the random color &amp;amp; users can copy the HEX code.&lt;/p&gt;




&lt;p&gt;Thanks for reading this far! I hope you found it helpful. Remember, it’s OK to read articles &amp;amp; follow tutorials sometimes, but you should only be doing this to learn concepts. Once you think you’ve got the concepts down pat, try making programs yourself. No, you probably won’t get everything right the first time, but encountering a problem &amp;amp; figuring out how to solve it yourself, using concepts you’ve learned, is the way to becoming a better coder.&lt;/p&gt;

&lt;p&gt;If you found this article helpful, I’d appreciate a nice comment or a few claps, so I can know what content people find useful, and so I can focus on writing that content in the future.&lt;/p&gt;

&lt;p&gt;As always, happy coding!&lt;/p&gt;




&lt;p&gt;&lt;a href="https://egroene.github.io/Random-Color-Generator/" rel="noopener noreferrer"&gt;See this project in action&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/EGROENE/Random-Color-Generator" rel="noopener noreferrer"&gt;Link to this project’s GitHub repo&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.geeksforgeeks.org/difference-between-textcontent-and-innerhtml/" rel="noopener noreferrer"&gt;Link to article on differences between .innerHTML &amp;amp; .textContent&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>tutorial</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>New to JavaScript Classes? Read this.</title>
      <dc:creator>Ethan Groene</dc:creator>
      <pubDate>Sat, 11 Jan 2025 16:20:04 +0000</pubDate>
      <link>https://forem.com/egroene/new-to-javascript-classes-read-this-25pk</link>
      <guid>https://forem.com/egroene/new-to-javascript-classes-read-this-25pk</guid>
      <description>&lt;p&gt;&lt;em&gt;Originally published on Medium for JavaScript in Plain English on July 12, 2022&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you’ve been learning about JavaScript for a bit now, you’ve probably done some work with functions and objects. What if I told you that there was a way to make objects that have similar properties in a much more efficient way than creating each object individually, painstakingly making sure all the keys have the same names, the values are the right type, etc.?&lt;/p&gt;

&lt;p&gt;There are actually a number of different ways to do so, such as by using factory functions and classes, but for now, in case you somehow missed the title, we’ll focus on classes.&lt;/p&gt;

&lt;p&gt;You may be wondering how classes can help us manage data in real-life situations. In this article, I’ll be using the example of managing content in a library, but classes could also be used for managing personnel, tracking info about different branches or locations of a business (like a restaurant or a bank), for managing curriculum data at a university, &amp;amp; the list goes on.&lt;/p&gt;

&lt;p&gt;Before we look at our example, you should be aware that we must first make a parent class (a.k.a. ‘superclass’) before we create instances of the class. Each instance of a class is an object that contains the properties, methods, getters, &amp;amp; setters of the parent class, but has unique property values, and may contain their own properties, methods, etc.: more on this in the next paragraph. Think of the parent class as the template for constructing instances, as it contains the properties, getters, methods (functions that can be called on instances of the class), and setters (if necessary) that each instance &amp;amp; subclass has access to.&lt;/p&gt;

&lt;p&gt;Instances of a class may be slightly different than others in that they may contain unique properties or methods that were not established in the parent class. For cases like this, we should create a child class (a.k.a. ‘subclass’). These contain everything that the parent class contains, only we can add more properties, getters, methods, &amp;amp; setters if we need to, and these would all be unique to the child class. But enough theoretical talk, let’s get our hands theoretically dirty &amp;amp; look at our aforementioned library example.&lt;/p&gt;




&lt;p&gt;For the sake of brevity, let’s imagine that we live in 1889 &amp;amp; we have only one type of medium in our library: books. In a more realistic situation, there would be things like movies &amp;amp; CDs, for which we would want to create subclasses for. No doubt these will all have some properties, getters, methods, and maybe some setters in common, so let’s create a parent class called ‘Media’ with all of these, before making a subclass for books:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Create Parent Class ‘Media’&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg14tw39cetjy4e8dt54n.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg14tw39cetjy4e8dt54n.jpg" alt="Create superclass 'Media'" width="679" height="464"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let’s break down what’s happening in the picture above (the numbers below correspond to the numbers in the comments above):&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;We declare a class with the &lt;code&gt;class&lt;/code&gt; keyword, followed by the class name and a curly bracket. Class names must be capitalized &amp;amp; written in CamelCase.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We establish the classes properties with the constructorkeyword. The property names are passed into parentheses. We then set the values of the properties to default values, or to whatever is passed into the constructor parentheses when we later create instances of this class. Notice we use the &lt;code&gt;this._&lt;/code&gt; syntax.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For each property, we have to establish a corresponding getter so we can later access the corresponding values of each instance of the class.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We create the methods for the class, along with any necessary setters. In this example, we have a method that allows us to add a rating of 1–5 for the instance of this class (library item). This new rating is stored inside an array. Then, we have a method which uses the array where all the ratings are stored to determine the average rating of the library item. Finally, we have a method that toggles the checkout status of the item. This method requires a setter, so we put that directly before the method is declared.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Create ‘Book’, a Subclass of the Superclass ‘Media’
&lt;/h2&gt;

&lt;p&gt;Now, let’s create a child class for all the books in our library. Keep in mind that we’ll need to add the properties &lt;code&gt;author&lt;/code&gt; &amp;amp; &lt;code&gt;pages&lt;/code&gt;, which are unique to books &amp;amp; don’t exist in the parent class or in other child classes we may make later for other items.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvkov9ut5quz4gjbgjlal.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvkov9ut5quz4gjbgjlal.jpg" alt="Create class ‘Book’, a subclass of ‘Media’" width="679" height="374"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let’s go over what’s going on:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;We give the subclass a name, which follows the &lt;code&gt;class&lt;/code&gt; keyword. After the class name is declared, we use the keyword &lt;code&gt;extends&lt;/code&gt; to indicate the new class is a subclass of, in this case, &lt;code&gt;Media&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We use the constructor to establish properties of the subclass. These properties have no default value, so the &lt;code&gt;isCheckedOut&lt;/code&gt; &amp;amp; &lt;code&gt;ratingsproperties&lt;/code&gt; from the superclass are not included as part of the constructor for this subclass, since &lt;code&gt;isCheckedOut&lt;/code&gt; has a default value of &lt;code&gt;false&lt;/code&gt;, &amp;amp; &lt;code&gt;ratings&lt;/code&gt; is initially set to an empty array. The property &lt;code&gt;title&lt;/code&gt; from the superclass is included in the constructor, since it has no default value. This subclass inherits this property from the superclass if we enter keyword &lt;code&gt;super&lt;/code&gt; &amp;amp; put &lt;code&gt;title&lt;/code&gt; in parentheses behind it. Because of this, we don’t need to make a getter for it, since it inherits this property from the superclass. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since we added two new properties that are particular to this subclass, &lt;code&gt;author&lt;/code&gt; &amp;amp; &lt;code&gt;pages&lt;/code&gt;, we need to make a getter for each.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Create an Instance of Subclass ‘Book’
&lt;/h2&gt;

&lt;p&gt;Now it’s time to put our classes to use by creating an instance. Let’s create a book item, titled ‘How 2 Rap’ by Eminem that has, of all numbers, 666 pages:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8urayjmdiko1i9p0n02j.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8urayjmdiko1i9p0n02j.jpg" alt="Create new instance of subclass ‘Book’" width="677" height="68"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once an instance is created, it behaves like an object (it technically is one). We can call its getters on it &amp;amp; log those values to the console to make sure we set everything up correctly. We can also call the methods that we established in the super- and subclass, on it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo7jewq0hrk9mtsv9rg1n.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo7jewq0hrk9mtsv9rg1n.jpg" alt="Are our classes and instance working correctly? Yes." width="676" height="403"&gt;&lt;/a&gt;&lt;/p&gt;




&lt;p&gt;There you have it, a bit about JavaScript classes. There is some conflict on when you should use them, if at all, but I will let you get into those wars of words yourself, whether that be in a YouTube comment section, on StackOverflow, or elsewhere, maybe even in the comment section below.&lt;/p&gt;

&lt;p&gt;As always, let me know if you learned something or if you have questions. If you see I could have done something better, do tell.&lt;/p&gt;

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

&lt;p&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes" rel="noopener noreferrer"&gt;MDN Documentation on JS Classes&lt;/a&gt;&lt;/p&gt;

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