<?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>DEV Community: Okure U. Edet Kingsley🧑‍💻🚀</title>
    <description>The latest articles on DEV Community by Okure U. Edet Kingsley🧑‍💻🚀 (@itzz_okure).</description>
    <link>https://dev.to/itzz_okure</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%2F1042133%2F2c2314a3-46b3-4281-8f22-a115482fb02d.jpg</url>
      <title>DEV Community: Okure U. Edet Kingsley🧑‍💻🚀</title>
      <link>https://dev.to/itzz_okure</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/itzz_okure"/>
    <language>en</language>
    <item>
      <title>CRUD operations with mongoose models: a step-by-step guide</title>
      <dc:creator>Okure U. Edet Kingsley🧑‍💻🚀</dc:creator>
      <pubDate>Thu, 31 Aug 2023 11:08:01 +0000</pubDate>
      <link>https://dev.to/itzz_okure/crud-operations-with-mongoose-models-a-step-by-step-guide-o77</link>
      <guid>https://dev.to/itzz_okure/crud-operations-with-mongoose-models-a-step-by-step-guide-o77</guid>
      <description>&lt;h2&gt;
  
  
  Table of Contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;What are CRUD operations?&lt;/li&gt;
&lt;li&gt;Setting up MongoDB&lt;/li&gt;
&lt;li&gt;Defining a mongoose model&lt;/li&gt;
&lt;li&gt;CRUD operations with Mongoose models&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;Recently, I started learning how to use MongoDB and I was hit with bugs when setting up MongoDB especially when it came to performing CRUD(create, read, update and delete) operations with Mongoose models. I was finally able to do so. I wrote this article to guide developers and those new to MongoDB on performing CRUD operations with Mongoose models. By the end of this article, you will be able to set up MongoDB, create a mongoose model and perform CRUD operations with the model. In short, this article will get you started on performing your own CRUD operations with Mongoose models.&lt;/p&gt;

&lt;h3&gt;
  
  
  What are CRUD operations?
&lt;/h3&gt;

&lt;p&gt;CRUD stands for create, read, update and delete. Most software applications utilize some form of CRUD functionality. In MongoDB, data retrieved from a user is stored in a collection as a document. These documents can then be read, updated and even deleted. In this article, you will understand how these operations work in the context of a form.&lt;/p&gt;

&lt;h3&gt;
  
  
  Setting up MongoDB
&lt;/h3&gt;

&lt;p&gt;Open your Chrome browser or any browser you currently use and navigate to this website: &lt;a href="https://www.mongodb.com/"&gt;https://www.mongodb.com/&lt;/a&gt;. Hover over the &lt;em&gt;Products&lt;/em&gt; link and click on &lt;em&gt;community server&lt;/em&gt;. Select the platform you want to download MongoDB to. It may be Windows x64 or macOS x64. Once you are done with downloading and installing MongoDB, do not forget to download MongoDB compass.&lt;/p&gt;

&lt;p&gt;Create a new directory for this project and run the following command in 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;npm init -y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will initialise a new node.js project. Once it is done, you should see a package.json file in your project directory.&lt;/p&gt;

&lt;p&gt;After installing MongoDB and Mongo compass, go ahead and install mongoose:&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Creating a server&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The server will be created using Express. So go ahead and install Express:&lt;br&gt;
&lt;/p&gt;

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

&lt;/div&gt;



&lt;p&gt;Inside your directory, create an &lt;em&gt;index.js&lt;/em&gt; file. You can use a code editor to do this. Inside this file, add the following code:&lt;br&gt;
&lt;/p&gt;

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

const app = express();

app.listen(3000, function () {
  console.log("App listening on port 3000...");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code imports express, stores it into an app variable and then starts the server at port 3000. You can of course use another port.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Connecting to MongoDB from node&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Inside the &lt;em&gt;index.js&lt;/em&gt; file, add the following code:&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')

mongoose.connect("mongodb://localhost:27017/db", { useNewUrlParser: true });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Mongoose is imported and used to establish a connection with the MongoDB database. The &lt;code&gt;mongoose.connect&lt;/code&gt; method takes in a parameter and a database name. The name of the database we want to connect to is &lt;code&gt;db&lt;/code&gt;. if this database does not exist, one will be created for us.&lt;/p&gt;

&lt;h3&gt;
  
  
  Defining a mongoose model
&lt;/h3&gt;

&lt;p&gt;Inside your project directory, create another directory or folder called &lt;em&gt;models&lt;/em&gt;. A model encloses a mongoose schema. A Mongoose schema is similar to a blueprint that defines the essential properties of a document. Inside this directory, create a file called &lt;code&gt;User.js&lt;/code&gt; and add the following code:&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;

const UserSchema = new Schema({
  username: String,
  email: String,
});

const User = mongoose.model("User", UserSchema);

module.exports = User;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A schema is created using the &lt;code&gt;mongoose.Schema&lt;/code&gt; method. A schema of a document in a collection will look like. Once that is done, we access the database through the &lt;code&gt;mongoose.model&lt;/code&gt; method. This method accepts a model name and the schema. Mongoose automatically creates a plural version of the model name. In our case, it will be &lt;em&gt;Users&lt;/em&gt; instead of User as specified.&lt;/p&gt;

&lt;h3&gt;
  
  
  CRUD operations with Mongoose models
&lt;/h3&gt;

&lt;p&gt;By now, you must have established a connection with MongoDB using mongoose. It is now time to illustrate CRUD(create, read, update and delete) operations using Mongoose.&lt;br&gt;
In your root folder, create an &lt;em&gt;example.js&lt;/em&gt; file and add the following code:&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 User = require("./models/User");

mongoose.connect("mongodb://127.0.0.1:27017/db", { useNewUrlParser: true });

User.create({
  username: "Kingsley",
  email: "kingsley@gmail.com",
})
  .then(function (user) {
    console.log(user);
  })
  .catch(function (error) {
    console.log(error);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;em&gt;User&lt;/em&gt; model is first imported. Then a connection with MongoDB is established. Once that is done, we then use a method in the &lt;em&gt;User&lt;/em&gt; model called &lt;code&gt;create&lt;/code&gt;. This method allows us to create a new document in line with our schema. We log the User object to the console. To see if our code is working, open your terminal and execute example.js:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node example.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It should show something 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;{
  username: 'Kingsley',
  email: 'kingsley@gmail.com',
  _id: new ObjectId("64ef25aeaf83ce8e4d4fd786"),
  __v: 0
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is important to note that every document in MongoDB has a unique &lt;code&gt;_id&lt;/code&gt; as you can see in the &lt;code&gt;_id&lt;/code&gt; property.&lt;/p&gt;

&lt;p&gt;You can see the data created for you in MongoDB compass. Just open it up. It will look something like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--lG3K5KMq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u56mgb3qd7wgenm7c9q0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--lG3K5KMq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u56mgb3qd7wgenm7c9q0.png" alt="Mongo compass" width="800" height="274"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Reading data from MongoDB&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you want to retrieve one document in the User collection, use the &lt;code&gt;.findOne()&lt;/code&gt; method. This method accepts two parameters: specification and projection. The former specifies the criteria used to find the documents. The latter determines which fields are returned.&lt;br&gt;
For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;User.findOne({ email: "kingsley@gmail.com" }, { username: 1 })
  .then((user) =&amp;gt; {
    console.log(user);
  })
  .catch((err) =&amp;gt; {
    console.log(err);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node example.js
{ _id: new ObjectId("64ef7f38d29a236158c77b62"), username: 'Kingsley' }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Documents with the email &lt;em&gt;&lt;a href="mailto:kingsley@gmail.com"&gt;kingsley@gmail.com&lt;/a&gt;&lt;/em&gt; are found and the username is returned.&lt;/p&gt;

&lt;p&gt;You can also use the &lt;code&gt;.find()&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;User.find()
  .then((user) =&amp;gt; {
    console.log(user);
  })
  .catch((err) =&amp;gt; {
    console.log(err);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node example.js
[
  {
    _id: new ObjectId("64ef7f38d29a236158c77b62"),
    username: 'Kingsley',
    email: 'kingsley@gmail.com',
    __v: 0
  }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This finds all the documents in the User collection.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;User.find({ username: /K/ })
  .then((user) =&amp;gt; {
    console.log(user);
  })
  .catch((err) =&amp;gt; {
    console.log(err);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node example.js
[
  {
    _id: new ObjectId("64ef7f38d29a236158c77b62"),
    username: 'Kingsley',
    email: 'kingsley@gmail.com',
    __v: 0
  }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This finds all the documents that begin with &lt;code&gt;K&lt;/code&gt;. Note that we used the &lt;code&gt;//&lt;/code&gt;. It is similar to how it is used in a regular expression.&lt;/p&gt;

&lt;p&gt;You can use the &lt;code&gt;.findById()&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;const id = "64ef7f38d29a236158c77b62";
User.findById(id)
  .then((user) =&amp;gt; {
    console.log(user);
  })
  .catch((err) =&amp;gt; {
    console.log(err);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node example.js
{
  _id: new ObjectId("64ef7f38d29a236158c77b62"),
  username: 'Kingsley',
  email: 'kingsley@gmail.com',
  __v: 0
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This finds a document by its unique ID.&lt;br&gt;
To get a full appraisal of methods that can be used to find a document, visit: &lt;a href="https://www.mongodb.com/docs/manual/tutorial/query-documents/"&gt;https://www.mongodb.com/docs/manual/tutorial/query-documents/&lt;/a&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Updating data in MongoDB&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To update a document in MongoDB is quite simple. You can use the &lt;code&gt;.findByIdAndUpdate()&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;const id = "64ef7f38d29a236158c77b62";
User.findByIdAndUpdate(id, { email: "kingsleyokgeorge@gmail.com" })
  .then((user) =&amp;gt; {
    console.log(user);
  })
  .catch((err) =&amp;gt; {
    console.log(err);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node example.js
{
  _id: new ObjectId("64ef7f38d29a236158c77b62"),
  username: 'Kingsley',
  email: 'kingsleyokgeorge@gmail.com',
  __v: 0
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The email was updated to &lt;em&gt;&lt;a href="mailto:kingsleyokgeorge@gmail.com"&gt;kingsleyokgeorge@gmail.com&lt;/a&gt;&lt;/em&gt;. Try it and see!&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Deleting data from MongoDB&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const id = "64ef7f38d29a236158c77b62";
User.findByIdAndDelete(id)
  .then((user) =&amp;gt; {
    if (!user) {
      console.log("Deleted!");
    }
  })
  .catch((err) =&amp;gt; {
    console.log(err);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node example.js
Deleted!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you check MongoDB compass, you will discover that there is no document in the User collection. It has been deleted.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Throughout this article, you have learned how to perform and simulate CRUD operations with Mongoose models. You have learned how to create, read, update and delete documents from a collection. You can apply what you have learned in this article to your side projects. For more information on Mongoose models and CRUD operations, refer to the docs: &lt;a href="https://www.mongodb.com/docs/manual/crud/"&gt;https://www.mongodb.com/docs/manual/crud/&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>UNDERSTANDING THE ASYNCHRONOUS NATURE OF NODE.JS</title>
      <dc:creator>Okure U. Edet Kingsley🧑‍💻🚀</dc:creator>
      <pubDate>Thu, 17 Aug 2023 07:11:07 +0000</pubDate>
      <link>https://dev.to/itzz_okure/understanding-the-asynchronous-nature-of-nodejs-3blg</link>
      <guid>https://dev.to/itzz_okure/understanding-the-asynchronous-nature-of-nodejs-3blg</guid>
      <description>&lt;h2&gt;
  
  
  Prerequisite
&lt;/h2&gt;

&lt;p&gt;This article provides a clear understanding of asynchronous code in node.js. The reader should have a basic knowledge of JavaScript.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Content
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;Brief overview of node.js&lt;/li&gt;
&lt;li&gt;What is asynchronous programming?&lt;/li&gt;
&lt;li&gt;Blocking and non-blocking code in node.js&lt;/li&gt;
&lt;li&gt;Event loop in node.js&lt;/li&gt;
&lt;li&gt;Thread pool&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;Node.js is a very powerful runtime environment that can be used to build performant and scalable web applications. Though it is single-threaded, it can perform asynchronous operations with the use of asynchronous code. Node.js then executes such code using the event loop which is at the heart of asynchronous programming in node.js. By the end of this article, you will understand what asynchronous programming means in node.js, blocking and non-blocking code, event loop and thread pool. Let us begin!&lt;/p&gt;

&lt;h3&gt;
  
  
  Brief overview of node.js
&lt;/h3&gt;

&lt;p&gt;JavaScript code can be executed outside the browser using node.js. But what is node.js? Node.js is an asynchronous, event-driven JavaScript runtime environment. It is built on Google's V8 JavaScript engine. The V8 engine is open source. Using JavaScript outside the browser with the aid of node.js allows JavaScript to do things it could not previously do such as better networking capabilities or accessing a file system. With the power of node.js, JavaScript can now be used on the server side of web development to build performant and highly scalable network applications. One characteristic of node.js is that it is single-threaded and based on an event-driven, non-blocking model. This model ensures that node.js is efficient for building scalable web applications. Now you may be pondering what it means for node.js to be single-threaded. Well, a single-threaded process is when a sequence of code is executed one after another. &lt;br&gt;
For example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// index.js
const greeting = "Hello";
const firstName = "Kingsley";

const sentence = `${greeting}, my name is ${firstName}`;
console.log(sentence); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node index.js
Hello, my name is Kingsley
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In a single-threaded environment, the code above will be executed line by line. It is immaterial if one line of the code takes a very long time to be executed. If this is the case, then this line will block the rest of the code. This can cause an application to slow down especially when there are many users. Thankfully, in node.js, there is a solution to this problem. It is called the event loop. The event loop allows node.js to perform asynchronous, non-blocking I/O operations. It does this by moving aside operations that require a longer time to execute. This article will examine asynchronous I/O non-blocking code and how node.js implements it.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is asynchronous programming?
&lt;/h3&gt;

&lt;p&gt;To examine how node.js implements asynchronous code, it is essential to understand what asynchronous programming is and why developers may sometimes need it.&lt;br&gt;
Asynchronous programming according to the MDN Docs(&lt;a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing"&gt;https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing&lt;/a&gt;) is defined "as a technique that enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished. Once that task has finished, your program is presented with the result". This means that a process on your system is running in parallel with other processes. One of the benefits of asynchronous programming is that it allows various tasks to be handled almost simultaneously thereby ensuring a faster application. In node.js, asynchronous I/O non-blocking code is used to perform more or less heavy tasks. I/O means input and output. Asynchronous code is said to be non-blocking code while synchronous code is said to be blocking code. Let's examine what blocking and non-blocking code mean in the context of asynchronous programming in node.js.&lt;/p&gt;
&lt;h3&gt;
  
  
  Blocking and non-blocking code
&lt;/h3&gt;

&lt;p&gt;Node.js has synchronous blocking code and asynchronous non-blocking code. Synchronous code is described as blocking code since each code is executed line by line. This then means that if one line of code takes a longer time to process, all other code will be 'blocked' from execution.&lt;/p&gt;

&lt;p&gt;Take a look at the synchronous code below:&lt;br&gt;
&lt;/p&gt;

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

console.log("------------Synchronous code-----------");
const textIn = fs.readFileSync("./txt/input.txt", "utf-8");
const textOut = `This is what we know about node.js: ${textIn}.\nCreated on ${Date.now()}`;
fs.writeFileSync("./txt/output.txt", textOut);
console.log(textOut);
console.log("File written");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node index.js
------------Synchronous code-----------
This is what we know about node.js: Node.js is an asynchronous, event-driven JavaScript runtime designed to build scalable network applications.
Created on 1691915393994
File written
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above will be executed line by line. It reads a file synchronously and logs it to the console. Now, this may be okay when dealing with a small application that in turn has a small number of users. However, it becomes a problem when dealing with a large number of users who want to access your application all at the same time. The solution to this problem is to always use non-blocking code. Asynchronous non-blocking code is a very essential part of the node.js architecture. It enables us to perform heavy operations without blocking the rest of the code.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
reading a file using asynchronous non-blocking code.&lt;br&gt;
&lt;/p&gt;

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

fs.readFile("./txt/input.txt", "utf-8", function (err, fileContent) {
  if (err) {
    console.log("ERROR!");
  } else {
    console.log(fileContent);
  }
});

console.log("----------Asynchronous code-----------");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node index.js
----------Asynchronous code-----------
Node.js is an asynchronous, event-driven JavaScript runtime designed to build scalable network applications.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you take a look at the above code, you may have guessed the order in which the code will be executed. Node.js first starts reading the file in the background and then moves on to the next line of code. It then prints &lt;code&gt;----------Asynchronous code-----------&lt;br&gt;
&lt;/code&gt; to the console. After the file has been read, it will then execute the callback function and log the file to the console. Unlike synchronous blocking code, asynchronous non-blocking code like the one shown above does not block other codes in the program from executing. It relegates the line of code that may take time to process to the background. &lt;br&gt;
Thus node.js eliminates the blocking of code through the use of asynchronous non-blocking I/O model. &lt;/p&gt;
&lt;h3&gt;
  
  
  Event loop in node.js
&lt;/h3&gt;

&lt;p&gt;The event loop is the core innovation of node.js. The execution of asynchronous I/O operation is made possible by the event loop. The event loop runs in the single thread provided by node.js. This means that blocking the event loop will result in the blocking of the entire thread. The event loop automatically commences when a process begins and ends when there is no longer any callbacks to be processed. The event loop delegates intensive operations to the thread pool which is part of the &lt;em&gt;libuv&lt;/em&gt; library. It manages these operations and notifies the event loop when the operations are ready to be executed. More on thread pool later.&lt;br&gt;
According to the node documentation, the event loop has six phases: timers, pending I/O call backs, waiting/idle phase, I/O polling, &lt;code&gt;setImmediate()&lt;/code&gt; callbacks and close callbacks. These six phases create one loop usually referred to as a tick.&lt;br&gt;
These phases will be examined below.&lt;/p&gt;

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

&lt;p&gt;Timers in node.js are used to schedule the execution of a block of code after a particular time, usually in milliseconds has passed. JavaScript provides two main asynchronous timers: &lt;code&gt;setTimeout()&lt;/code&gt; and &lt;code&gt;setInterval()&lt;/code&gt;. These functions are contained in a &lt;em&gt;timers&lt;/em&gt; module provided to node.js. These timers take in a callback and delay the execution of the callback until the passing of a specified time in milliseconds. Both of these global functions are executed by the event loop. At the beginning of the timer phase, the event loop updates its time and checks a queue of timers. The event loop will select the timer with the shortest delay time and then compare it with the event loop's time. If the wait time has elapsed, it will execute the callback once the call stack is empty. It is important to note that timers may execute later than the time specified. This may be because the call stack is not emptied for the timer in question to be called. Also, a while loop may obstruct the execution of a timer. &lt;br&gt;
For example:&lt;br&gt;
&lt;/p&gt;

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

let time = false;
setTimeout(function () {
  console.log("Timer 1");
}, 1000);

while (time === false) {
  console.log("waiting for a second...");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node index.js
waiting for a second...
waiting for a second...
waiting for a second...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, the while loop blocks the event loop from running. This is possible because node.js is single threaded and blocking the event loop is synonymous to blocking all other code from execution.&lt;br&gt;
As you have seen earlier, there are two types of timer provided by the timer module: &lt;code&gt;setTimeout()&lt;/code&gt; and &lt;code&gt;setInterval()&lt;/code&gt;. The difference is that the &lt;code&gt;setInterval()&lt;/code&gt; is used to execute a function periodically or after a particular interval. In this case, the &lt;code&gt;setInterval()&lt;/code&gt; is placed back into the queue to be executed again and again. &lt;br&gt;
For example:&lt;br&gt;
&lt;/p&gt;

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

setInterval(function () {
  console.log("Interval 1");
}, 1000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node index.js
Interval 1
Interval 1
Interval 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example, the call back function is executed every second. Thus, this timer schedules the repeated execution of call back after a specified millisecond. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;I/O call backs&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is the pending call back phase. In this phase of the event loop, the asynchronous non-blocking I/O model becomes crucial. &lt;br&gt;
Here's an example:&lt;br&gt;
&lt;/p&gt;

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

const fs = require("fs"); // file system

fs.readFile("./txt/input.txt", "utf-8", function (err, fileContent) {
  if (err) {
    console.log(err);
  } else {
    console.log(`Here is the file content: ${fileContent}`);
  }
});

console.log("Asynchronous non-blocking I/O model");
console.log("");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node index.js
Asynchronous non-blocking I/O model

Here is the file content: Node.js is an asynchronous, event-driven JavaScript runtime designed to build scalable network applications.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;fs.readFile()&lt;/code&gt; is an asynchronous code. While node.js attempts to read a file from the OS, this operation does not block the execution of other code in the application.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Waiting/Idle phase&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this phase, the event loop performs the internal operations of the call backs. This phase is used for gathering information on what needs to be executed during the next tick of the event loop. No code needs to be executed during this phase.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;I/O polling phase&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;According to the node documentation(&lt;a href="https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick"&gt;https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick&lt;/a&gt;), the poll phase has two main function: "calculating how long it should block and poll for I/O and processing events in the poll queue". In this phase, the event loop manages the I/O work load and executes the call backs synchronously after iterating through the queue of callbacks. If the poll queue is empty, it will move on to the check phase to execute the &lt;code&gt;setImmediate()&lt;/code&gt; function. If no scripts have been scheduled by the &lt;code&gt;setImmediate()&lt;/code&gt; function, the event loop will wait for callbacks to be added to the poll queue and then execute them immediately. If the event loop is empty, it will check for timers that have not been executed and if there are, it will double back to the timer phase to execute the timer callbacks.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;setImmediate()&lt;/code&gt;/check phase&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The &lt;code&gt;setImmediate()&lt;/code&gt; is usually executed after the poll phase. It runs as soon as the poll queue is empty. If the &lt;code&gt;setImmediate()&lt;/code&gt; is within an I/O cycle, it will be executed before any timers.&lt;br&gt;
&lt;/p&gt;

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

const fs = require("fs"); // file system

fs.readFile(__filename, () =&amp;gt; {
  setTimeout(() =&amp;gt; {
    console.log("Timer 1");
  }, 0);

  setTimeout(function () {
    console.log("Timer 2");
  }, 100);

  setImmediate(() =&amp;gt; {
    console.log("immediate");
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ node index.js
immediate
Timer 1
Timer 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;setImmediate()&lt;/code&gt; and the timer functions are within an I/O callback and so the &lt;code&gt;setImmediate()&lt;/code&gt; will always be executed before the &lt;code&gt;setTimeout()&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Close callbacks&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this phase, the callbacks of all &lt;em&gt;close events&lt;/em&gt; are executed. For example the &lt;code&gt;process.exit()&lt;/code&gt; method. Or where a socket or handle is closed i.e &lt;code&gt;socket.destroy()&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;To recap, when a node process begins to run, the event loop kicks off. It starts with the timer phase and executes the timers with the least delay time, then it moves on to I/O callbacks, then it does some internal processing, after this phase, it then moves on to execute callbacks on the poll queue. This is done synchronously. The event loop then executes &lt;code&gt;setImediate()&lt;/code&gt; and finally it executes close callbacks. It repeats this loop/tick until there are no more callbacks to execute. At this point, it is essential to note that there are some tasks that are too heavy to be executed by the event loop. And that is where the thread pool comes into play. &lt;/p&gt;

&lt;h3&gt;
  
  
  Thread pool
&lt;/h3&gt;

&lt;p&gt;The thread pool is another fundamental part of the node.js architecture. The &lt;em&gt;libuv&lt;/em&gt; library provides us with the thread pool. The thread pool provides four additional threads that are completely separate from the main single thread. The thread pool can be configured up to one hundred and twenty eight threads. However, most of the time, these four threads are enough. When the event loop encounters heavy tasks, these tasks are then automatically delegated to the thread pool. Tasks like operations dealing with files, compression related functions, DNS lookups and so on are usually delegated to the thread pool. The reason these tasks are delegated to the thread pool is so as to avoid prevent them from blocking the event loop.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;In summary, the asynchronous I/O model is a fundamental part of how node.js handles relatively heavy tasks. This article has laid down the basic idea of how asynchronous programming works in node.js using the event loop and the thread pool. Both of these are provided for by the &lt;em&gt;libuv&lt;/em&gt; library which is written in C++. This whole architecture helps you as a developer to build performant and scalable web applications.&lt;/p&gt;

</description>
      <category>node</category>
      <category>javascript</category>
    </item>
    <item>
      <title>HOW TO VALIDATE A SIMPLE FORM USING REGULAR EXPRESSIONS(REGEX) IN JAVASCRIPT</title>
      <dc:creator>Okure U. Edet Kingsley🧑‍💻🚀</dc:creator>
      <pubDate>Fri, 04 Aug 2023 06:32:37 +0000</pubDate>
      <link>https://dev.to/itzz_okure/how-to-validate-a-simple-form-using-regular-expressionsregex-in-javascript-1fp8</link>
      <guid>https://dev.to/itzz_okure/how-to-validate-a-simple-form-using-regular-expressionsregex-in-javascript-1fp8</guid>
      <description>&lt;h2&gt;
  
  
  Prerequisite
&lt;/h2&gt;

&lt;p&gt;This article aims to show the reader how to validate a simple form using regular expressions(regex) in JavaScript. To understand the contents of this article, the reader must have basic knowledge of HTML, CSS and JavaScript.&lt;/p&gt;

&lt;h2&gt;
  
  
  Table of Content
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Introduction&lt;/li&gt;
&lt;li&gt;What is a regular expression?&lt;/li&gt;
&lt;li&gt;How to create regular expressions(regex) in JavaScript&lt;/li&gt;
&lt;li&gt;Common regex patterns&lt;/li&gt;
&lt;li&gt;Building a form&lt;/li&gt;
&lt;li&gt;Validating the username&lt;/li&gt;
&lt;li&gt;Validating the password&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;As a developer, when building HTML forms, you may want to ensure that the value the user inputs into the form matches your preferred pattern. For example, a form may contain a field for the user to input a password. You may want the password to contain only lowercase letters, and numbers but no hyphens. You can create a pattern and then test it against the value inputted by the user. The easiest way to do this is to use matching patterns known as regular expressions(regex). By the end of this article, you will understand what regular expressions are, their syntax and how to use them by building a login form and validating the input fields with regular expressions. &lt;/p&gt;

&lt;h3&gt;
  
  
  What are regular expressions(regex)?
&lt;/h3&gt;

&lt;p&gt;Regular expressions in JavaScript are sequences of characters used to create patterns. These matching patterns are then tested against a combination of characters in a string. For example, regex patterns can be used to check strings like emails or passwords to determine if their character combinations match the regex patterns defined.  Regular expressions are objects. This means that they inevitably have methods. Regular expressions are not unique to JavaScript, they form part of other programming languages like Python and Java. &lt;/p&gt;

&lt;h3&gt;
  
  
  How to create regular expressions in JavaScript
&lt;/h3&gt;

&lt;p&gt;There are two ways of creating regular expressions in JavaScript. They can be created using a constructor function or by using forward slashes (&lt;code&gt;/&lt;/code&gt;).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Regular expression constructor&lt;/strong&gt;
Syntax: &lt;code&gt;new RegExp(pattern, flag)&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Example&lt;/em&gt;&lt;/p&gt;

&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

const str = 'JavaScript'
const regex = new RegExp('s' 'i');
console.log(regex.test(str)); // true


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

&lt;p&gt;The above example tests whether the regex pattern &lt;code&gt;s&lt;/code&gt; with a flag of &lt;code&gt;i&lt;/code&gt; which means &lt;em&gt;case insensitive&lt;/em&gt; matches any character in the string inside the &lt;code&gt;str&lt;/code&gt; variable. The &lt;code&gt;test()&lt;/code&gt; method returns a boolean &lt;code&gt;true&lt;/code&gt; because there is a match.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Regular expression literal&lt;/strong&gt;
Syntax: &lt;code&gt;/pattern/flag&lt;/code&gt;
```
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;const text = "JavaScript";&lt;br&gt;
const regPattern = /[a-z\d]/i;&lt;/p&gt;

&lt;p&gt;console.log(regPattern.test(text));&lt;/p&gt;


&lt;pre class="highlight plaintext"&gt;&lt;code&gt;The `regPattern` variable has a pattern that tests for letters from a to z as well as any numbers. It also has a flag of `i` which means case insensitive.

### Common regex patterns
Here are common regular expression(regex) patterns:

- **Telephone number validation pattern**
Regex pattern: 
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;/^\d{11}$/&lt;/p&gt;


&lt;pre class="highlight plaintext"&gt;&lt;code&gt;or 
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;/^[0-9]{11}$/&lt;/p&gt;


&lt;pre class="highlight plaintext"&gt;&lt;code&gt;The pattern above matches any number from 0-9 at the beginning of the input and the end of the input. The pattern is also specified to be eleven numbers long.
The `^` and `$` characters are known as an *assertion*. The former is used to signify the beginning of an input and the latter is used to match the end of an input.

- **Username validation pattern**
Regex pattern:
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;/^[a-z\d]{5,12}$/i&lt;/p&gt;


&lt;pre class="highlight plaintext"&gt;&lt;code&gt;The pattern above matches any case-insensitive letter from a-z and any number from 0-9. The pattern is also specified to be between five and twelve characters long. The `i` character is a flag. The flag means that the letters should be case-insensitive.

- **Password validation pattern**
Regex pattern: 
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;/^[\w@-]{8,20}$/&lt;/p&gt;


&lt;pre class="highlight plaintext"&gt;&lt;code&gt;The pattern above matches any letter which is case insensitive, any number from 0-9, an underscore, an @ symbol or a hyphen. The pattern is specified to be between 8 and 20 characters long. The `\w` character simply means any capital or small letter, any number and an underscore.

The above patterns can be modified depending on what you want. If you want to delve deeper into regex patterns and syntax, you can check out the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions

### Building the form
- **Setting up**
Open your Integrated Development Environment(IDE). Ideally, you should have VS code installed. Open a new folder and give it whatever name you want. After doing that, create a new file, an index.html file and a style.css file. if you are familiar with using tailwindcss, then install it. For information on how to install tailwindcss in your IDE, visit the tailwind docs: https://tailwindcss.com/docs/installation.
For this tutorial, I will be using tailwindcss since it is faster and easier to use.

 - **The HTML code**
After setting up, your HTML code will look something like this(of course you can write your HTML anyhow you like):

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


&lt;p&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;br&gt;
&lt;br&gt;
  &lt;/p&gt;
&lt;br&gt;
    &lt;br&gt;
    &lt;br&gt;
    Document&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
    &lt;br&gt;
      &lt;br&gt;
        &lt;br&gt;
          &lt;br&gt;
            Login Form&lt;br&gt;
            &lt;br&gt;
              &lt;h1&gt;Login Form&lt;/h1&gt;
&lt;br&gt;
            &lt;br&gt;
            &lt;br&gt;
              &lt;br&gt;
                Username&lt;br&gt;
                &lt;p id="userfeed"&gt;username valid!&lt;/p&gt;
&lt;br&gt;
                
                  type="text"&lt;br&gt;
                  name="username"&lt;br&gt;
                  id="username"&lt;br&gt;
                  placeholder="username"&lt;br&gt;
                /&amp;gt;&lt;br&gt;
                &lt;p id="userfeed1"&gt;username invalid&lt;/p&gt;
&lt;br&gt;
              &lt;br&gt;
              &lt;br&gt;
                Password&lt;br&gt;
                &lt;p id="passwordfeed"&gt;password valid!&lt;/p&gt;
&lt;br&gt;
                
                  type="password"&lt;br&gt;
                  name="password"&lt;br&gt;
                  id="password"&lt;br&gt;
                  placeholder="password"&lt;br&gt;
                /&amp;gt;&lt;br&gt;
                &lt;p id="passwordfeed1"&gt;password invalid!&lt;/p&gt;
&lt;br&gt;
              &lt;br&gt;
            &lt;br&gt;
            &lt;br&gt;
              &lt;br&gt;
                Sign In&lt;br&gt;
              &lt;br&gt;
              &lt;br&gt;
                &lt;a&gt;Forgot Password?&lt;/a&gt;&lt;br&gt;
              &lt;br&gt;
            &lt;br&gt;
          &lt;br&gt;
        &lt;br&gt;
      &lt;br&gt;
    &lt;br&gt;
    &lt;br&gt;
  &lt;br&gt;



&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
Output:


![HTML Form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g3titze759bh3s1yzxxt.png)

If you are using tailwindcss, you can take advantage of the plugin for forms. Open a terminal in your VS code and install the plugin form:
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;npm install -D &lt;a class="mentioned-user" href="https://dev.to/tailwindcss"&gt;@tailwindcss&lt;/a&gt;/forms&lt;/p&gt;


&lt;pre class="highlight plaintext"&gt;&lt;code&gt;After doing that, add the plugin to your `tailwind.config.js` file:
&lt;/code&gt;&lt;/pre&gt;


&lt;p&gt;// tailwind.config.js&lt;br&gt;
module.exports = {&lt;br&gt;
  theme: {&lt;br&gt;
    // ...&lt;br&gt;
  },&lt;br&gt;
  plugins: [&lt;br&gt;
    require('&lt;a class="mentioned-user" href="https://dev.to/tailwindcss"&gt;@tailwindcss&lt;/a&gt;/forms'),&lt;br&gt;
  ],&lt;br&gt;
}&lt;/p&gt;


&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- **Adding CSS to the HTML** 

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


&lt;p&gt;&amp;lt;!DOCTYPE html&amp;gt;&lt;br&gt;
&lt;br&gt;
  &lt;/p&gt;
&lt;br&gt;
    &lt;br&gt;
    &lt;br&gt;
    &lt;br&gt;
    TECHNICAL WRITING&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
    &lt;br&gt;
      &lt;br&gt;
        &lt;br&gt;
          
            class="grid sm:border-2 justify-center px-6 pb-20 pt-10 bg-gray-100 sm:bg-white sm:px-10 sm:rounded-md sm:shadow-md"&lt;br&gt;
          &amp;gt;&lt;br&gt;
            &lt;br&gt;
              Login Form&lt;br&gt;
            &lt;br&gt;
            
              class="sm:grid sm:justify-center sm:mb-10 hidden font-bold text-lg"&lt;br&gt;
            &amp;gt;&lt;br&gt;
              &lt;h1&gt;Login Form&lt;/h1&gt;
&lt;br&gt;
            &lt;br&gt;
            &lt;br&gt;
              &lt;br&gt;
                Username&lt;br&gt;
                &lt;p id="userfeed"&gt;&lt;br&gt;
                  username valid!&lt;br&gt;
                &lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;            &amp;lt;input
              type="text"
              name="username"
              id="username"
              placeholder="username"
              class="form-input px-4 py-3 rounded-md bg-gray-300"
            /&amp;gt;
            &amp;lt;p class="text-red-700 hidden" id="userfeed1"&amp;gt;
              username invalid
            &amp;lt;/p&amp;gt;
          &amp;lt;/div&amp;gt;
          &amp;lt;div class="py-2 grid" id="Pword"&amp;gt;
            &amp;lt;label class="text-lg font-semibold"&amp;gt;Password&amp;lt;/label&amp;gt;
            &amp;lt;p class="text-blue-500 hidden" id="passwordfeed"&amp;gt;
              password valid!
            &amp;lt;/p&amp;gt;
            &amp;lt;input
              type="password"
              name="password"
              id="password"
              placeholder="password"
              class="form-input px-4 py-3 rounded-md bg-gray-300"
            /&amp;gt;
            &amp;lt;p class="text-red-500 hidden" id="passwordfeed1"&amp;gt;
              password invalid!
            &amp;lt;/p&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div class="flex gap-8 mt-5"&amp;gt;
          &amp;lt;div&amp;gt;
            &amp;lt;button
              class="border-2 bg-blue-600 text-white p-1 hover:bg-slate-600"
            &amp;gt;
              Sign In
            &amp;lt;/button&amp;gt;
          &amp;lt;/div&amp;gt;
          &amp;lt;div&amp;gt;
            &amp;lt;a href="#" class="text-blue-500 hover:text-blue-800"
              &amp;gt;Forgot Password?&amp;lt;/a
            &amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/fieldset&amp;gt;
    &amp;lt;/form&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;script src="index.js"&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;




&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
The result will look like this:

![A login form with HTML AND CSS on PC](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g7wwv7l33g3qsyxwb34s.png)

or if you are using a mobile phone like this:

![A login form with HTML AND CSS on mobile](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohbl5p5a160w5vu474vn.png)

### Validating the username with regex
Firstly, you will create an `index.js` file and inside the file, you will reference all the elements you will need:
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;"use script";&lt;/p&gt;

&lt;p&gt;const form = document.querySelector("#form");&lt;br&gt;
const username = document.querySelector("#username");&lt;br&gt;
const password = document.querySelector("#password");&lt;br&gt;
const userfeed = document.querySelector("#userfeed");&lt;br&gt;
const userfeed1 = document.querySelector("#userfeed1");&lt;br&gt;
const passwordfeed = document.querySelector("#passwordfeed");&lt;br&gt;
const passwordfeed1 = document.querySelector("#passwordfeed1");&lt;/p&gt;



&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Then we will go ahead and create an object called `pattern`. This object will store the patterns for the username and password. We want the username to contain case-insensitive letters, and numbers and the username must be between 5-12 characters long.
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;const pattern = {&lt;br&gt;
  username: /^[a-z\d]{5,12}$/i,&lt;br&gt;
};&lt;/p&gt;



&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Once that is done, we will go ahead and create a function that validates and checks if the input by the user matches the regex pattern that we want:
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;const validatingFunc = function (idvalid, idinvalid, field, fieldName) {&lt;br&gt;
  if (pattern[fieldName].test(field.value)) {&lt;br&gt;
    userfeed.classList.add("hidden");&lt;br&gt;
    passwordfeed.classList.add("hidden");&lt;br&gt;
    idvalid.classList.remove("hidden");&lt;br&gt;
    idinvalid.classList.add("hidden");&lt;br&gt;
  } else if (field.value === "") {&lt;br&gt;
    idinvalid.classList.add("hidden");&lt;br&gt;
    idvalid.classList.add("hidden");&lt;br&gt;
  } else {&lt;br&gt;
    userfeed.classList.add("hidden");&lt;br&gt;
    passwordfeed.classList.add("hidden");&lt;br&gt;
    idinvalid.classList.remove("hidden");&lt;br&gt;
    idvalid.classList.add("hidden");&lt;br&gt;
  }&lt;br&gt;
};&lt;/p&gt;



&lt;pre class="highlight plaintext"&gt;&lt;code&gt;The function above takes in four parameters; `idvalid`, `idinvalid`, `field`, `fieldName`. The first two parameters refer to the `id` of elements that are hidden from the DOM. The `field` parameter refers to the element that has an `addEventListener()` function attached to it when an event is triggered. The `fieldName` parameter refers to the name of the element. This name is then used to access the name of the property that contains the pattern.
The function is all set but how do we know it is working? well, we attach an `addEventListener()` function to the input fields which will listen for a `keyup` event. The `validatingFunc()` will be called inside the `addEventListener()` function.
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;username.addEventListener("keyup", function (e) {&lt;br&gt;
  validatingFunc(userfeed, userfeed1, e.target, e.target.attributes.name.value);&lt;br&gt;
});&lt;/p&gt;



&lt;pre class="highlight plaintext"&gt;&lt;code&gt;When we were referencing the elements, we referenced elements with a tag name of `p`. These elements were hidden from the DOM but the `validatingFunc()` makes them visible depending on whether the pattern entered by the user is *username valid* or *username invalid*. Once you type into the username input field, a *username invalid* message appears as long as the pattern is not a match but once it is a match, a *username valid* message appears.


![A message of username invalid appears under the input field signifying that the pattern does not match the user's input](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0bkvm37l28j0psjlbl5x.png)

The above username is not a match because it is not at least 5 characters long. Under the input field, a message of _username invalid_ appears.


![A message of username valid appears above the input field signifying that the pattern matches the user's input](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/spswl3g1wsfe79akqusm.png)

The username matches the pattern and a message of username valid appears above the input field.

### Validating the password
You have created and tested a regex pattern for the username now it is time to do the same for the password. It is not difficult to do this once you have validated the username. All you need to do is create a pattern for the password and include it inside the `pattern` object.


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



&lt;p&gt;const pattern = {&lt;br&gt;
  username: /^[a-z\d]{5,12}$/i,&lt;br&gt;
  password: /^[\w@-]{8,20}$/,&lt;br&gt;
};&lt;/p&gt;



&lt;pre class="highlight plaintext"&gt;&lt;code&gt;We want our password to contain letters that are case-insensitive, numbers, underscores, an @ symbol and a hyphen. The password must be between 8 and 20 characters long. The `\w` character signifies any letter, number or underscore. The letters are case insensitive.

After creating the regex pattern, we will attach an `addEventListener()` function to the password input field. We had earlier referenced this input field with the `id` name `password`. The `validatingFunc()` will be called inside the `addEventListener()` function.

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



&lt;p&gt;password.addEventListener("keyup", function (e) {&lt;br&gt;
  validatingFunc(&lt;br&gt;
    passwordfeed,&lt;br&gt;
    passwordfeed1,&lt;br&gt;
    e.target,&lt;br&gt;
    e.target.attributes.name.value&lt;br&gt;
  );&lt;br&gt;
});&lt;/p&gt;



&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Of course, after this is done, we want to make sure it works so we will input a value into the password input field.

![The password does not match the regex pattern](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vez3ufvn060h98u55myq.png)

The password we input does not match the regex pattern we created so the message *password invalid* appears below the input field.


![The password matches the regular pattern](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xg48ky8g4gzu3vgsx72.png)

The password matches the regex pattern we earlier created so the message *password valid* appears above the input field.

### Conclusion
In summary, this article has provided background knowledge on regular expressions in JavaScript, how they are created and common regex patterns. You have also learnt how to test and validate a simple login form using regex in JavaScript. If you want to learn more about regular expressions, you can visit the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions
&lt;/code&gt;&lt;/pre&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>web3</category>
    </item>
    <item>
      <title>How Event Propagation and Delegation Work in JavaScript</title>
      <dc:creator>Okure U. Edet Kingsley🧑‍💻🚀</dc:creator>
      <pubDate>Thu, 13 Jul 2023 06:08:00 +0000</pubDate>
      <link>https://dev.to/itzz_okure/how-event-propagation-and-delegation-work-in-javascript-5efe</link>
      <guid>https://dev.to/itzz_okure/how-event-propagation-and-delegation-work-in-javascript-5efe</guid>
      <description>&lt;h2&gt;
  
  
  Table of Contents
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Introduction &lt;/li&gt;
&lt;li&gt;What are events?&lt;/li&gt;
&lt;li&gt;Event propagation&lt;/li&gt;
&lt;li&gt;The capturing phase of event propagation&lt;/li&gt;
&lt;li&gt;The bubbling phase of event propagation&lt;/li&gt;
&lt;li&gt;Event .stopPropagation method&lt;/li&gt;
&lt;li&gt;Event delegation&lt;/li&gt;
&lt;li&gt;How to use event delegation in JavaScript&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Prerequisite
&lt;/h3&gt;

&lt;p&gt;For the reader to understand this article, it is important to have at least a basic knowledge of HTML, CSS and JavaScript.&lt;/p&gt;

&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;In JavaScript, events travel to and fro the Document Object Model(Dom) tree. This is generally known as event propagation, which comes in two phases: capturing and bubbling. The fact that events pass through the parent element of the target element that triggered such events can then help you to decide where to handle these events. This is known as event delegation. In this article, you will learn how event propagation and delegation work in JavaScript and how to effectively use them to handle events on your page.&lt;/p&gt;

&lt;h3&gt;
  
  
  What are events?
&lt;/h3&gt;

&lt;p&gt;JavaScript events are actions or occurrences that trigger certain behavior on a page. Developers can then listen for these events in JavaScript by attaching a function known as Event Listeners. Examples of events in JavaScript include; a click event, where a user clicks on an element in a web page; a submit event, in cases where a user submits a form, page loading; a keyboard event, where the user chooses a key on the keyboard. For more about events, see this &lt;a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events" rel="noopener noreferrer"&gt;https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Event propagation
&lt;/h3&gt;

&lt;p&gt;Event propagation in JavaScript refers to how events travel the Document Object Model(DOM) tree. This behavior can be likened to an electric current traveling through the DOM tree once an event is triggered. Event propagation has two phases; capturing and bubbling.&lt;/p&gt;

&lt;h3&gt;
  
  
  The capturing phase of event propagation
&lt;/h3&gt;

&lt;p&gt;When an event is triggered or fired, the window object gets notified of the event first and then followed by the document element as well as the subsequent parent elements of the target element. This process is known as event capturing.&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;!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 name="viewport" content="width=device-width, initial-scale=1.0" /&amp;gt;
    &amp;lt;link type="text/css" href="style.css" rel="stylesheet" /&amp;gt;
    &amp;lt;title&amp;gt;TODO LIST&amp;lt;/title&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body class="bg-blue-200"&amp;gt;
    &amp;lt;div class="ul"&amp;gt;
      &amp;lt;ul class="list"&amp;gt;
        &amp;lt;li&amp;gt;Read a book&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Finish writing my article&amp;lt;/li&amp;gt;
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;script src="script.js"&amp;gt;&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;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.querySelector("li").addEventListener("click", function () {
  alert("My todo list!");
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, the &lt;code&gt;ul&lt;/code&gt; element is a parent element of the &lt;code&gt;li&lt;/code&gt; element. The &lt;code&gt;div&lt;/code&gt; element is also a parent element of the &lt;code&gt;ul&lt;/code&gt; element. It continues like this to the top of the DOM tree and to the window object itself. When an event such as a click event is triggered on the &lt;code&gt;li&lt;/code&gt; element, The window object is first alerted or notified of the event. Then it travels downward through each of the parent elements of the target element till it reaches the target element. After the target element has been notified of the event, then begins the second phase of event propagation, also known as event bubbling.&lt;/p&gt;

&lt;h3&gt;
  
  
  The bubbling phase of event propagation
&lt;/h3&gt;

&lt;p&gt;Once the target element has been notified of the event, the event once again travels up to the root of the DOM tree. Just like in the capturing phase, the event passes through all of its parent elements. This process is known as event bubbling.  So as an event ‘bubbles’ through its parent elements, it is as if the event was triggered in that very element. In the code above, once the &lt;code&gt;li&lt;/code&gt; element has been alerted of the event, the event then travels upward through the &lt;code&gt;ul&lt;/code&gt; element, the &lt;code&gt;div&lt;/code&gt; element, passing through the parent elements back to the root of the DOM. Generally, events are always handled either at the target or bubbling phase. However, event listeners can be set up in a way that they listen to events in the capturing phase instead. It is important to note that not all events have a capturing and bubbling phase. Some events, like the focus event, are generated right at the target element and can only be handled there.&lt;/p&gt;

&lt;h3&gt;
  
  
  Event .stopPropagation() method
&lt;/h3&gt;

&lt;p&gt;Throughout this article, you have seen how event capturing and bubbling work. However, there are times in your code when you may not want an event to bubble. In such cases, you can use the &lt;code&gt;e.stopPropagation()&lt;/code&gt; method.  This method prevents an event triggered in the target element from bubbling up the DOM tree.&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;!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 name="viewport" content="width=device-width, initial-scale=1.0" /&amp;gt;
    &amp;lt;title&amp;gt;TODO LIST&amp;lt;/title&amp;gt;
    &amp;lt;style&amp;gt;
      body {
        background-color: violet;
      }
      .ul {
        border: 2px solid blue;
        border-radius: 5px;
        margin: auto;
        width: 50%;
        padding: 10px;
        margin-top: 70px;
      }
      ul {
        background: rgb(214, 230, 222);
        padding: 20px;
      }
      ul li {
        background: rgb(217, 230, 212);
        color: black;
        margin: 5px;
      }

      .list {
        background: rgb(21, 75, 75);
      }
    &amp;lt;/style&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body class="bg-blue-200"&amp;gt;
    &amp;lt;div class="ul"&amp;gt;
      &amp;lt;ul class="list"&amp;gt;
        &amp;lt;li&amp;gt;Read a book&amp;lt;/li&amp;gt;
        &amp;lt;li&amp;gt;Finish writing my article&amp;lt;/li&amp;gt;
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;

    &amp;lt;script&amp;gt;
      // Target element
      document.querySelector("li").addEventListener("click", function () {
        alert("My todo list!");
      });

      // Parent element
      document.querySelector("ul").addEventListener("click", function () {
        this.style.background = "red";
      });
    &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;&lt;a href="https://media.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%2Fxylbba18bfpewezkbbld.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fxylbba18bfpewezkbbld.png" alt="The result of the above code"&gt;&lt;/a&gt;&lt;br&gt;
In the above code, an &lt;code&gt;addEventListener()&lt;/code&gt; function is attached to the &lt;code&gt;li&lt;/code&gt; element and its parent element &lt;code&gt;ul&lt;/code&gt;. When the &lt;code&gt;li&lt;/code&gt; element is clicked, the function attached to it executes before its parent function by event bubbling.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fz47f7cpjrl1i1pv654lx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fz47f7cpjrl1i1pv654lx.png" alt="The function attached to the  raw `li` endraw  element is executed first"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2Fmo8ro6lins7hwv904yle.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2Fmo8ro6lins7hwv904yle.png" alt="The function attached to the  raw `ul` endraw  element is executed after"&gt;&lt;/a&gt;&lt;br&gt;
We can prevent this from happening by adding an &lt;code&gt;e.stopPropagation()&lt;/code&gt; method. This will then prevent the event from propagating when the target element is clicked.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Target element
      document.querySelector("li").addEventListener("click", function (e) {
        e.stopPropagation();
        alert("My todo list!");
      });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Event delegation
&lt;/h3&gt;

&lt;p&gt;Event delegation is essentially the use of the knowledge that events bubble to instead handle events at any of the parent elements of the target element where the event was triggered. Events are said to be ‘delegated’ to a parent element of the target element so they can be handled right at that element.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to use event delegation in JavaScript
&lt;/h3&gt;

&lt;p&gt;When you want to use event delegation in your code, there are two things you need to do. Firstly, you add the event listener function to the parent element. After that is done, the next step is to figure out which element triggered the event. Event delegation has many benefits, one of which is to help improve the performance of your code.&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;!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 name="viewport" content="width=device-width, initial-scale=1.0" /&amp;gt;
    &amp;lt;title&amp;gt;TODO LIST&amp;lt;/title&amp;gt;
    &amp;lt;style&amp;gt;
      body {
        background-color: violet;
      }
      .ul {
        border: 2px solid blue;
        border-radius: 5px;
        margin: auto;
        width: 50%;
        padding: 10px;
        margin-top: 70px;
      }
      ul {
        background: rgb(214, 230, 222);
        padding: 20px;
      }
      ul li {
        background: rgb(217, 230, 212);
        color: black;
        margin: 5px;
      }

      .list {
        background: rgb(21, 75, 75);
      }
    &amp;lt;/style&amp;gt;
  &amp;lt;/head&amp;gt;
  &amp;lt;body class="bg-blue-200"&amp;gt;
    &amp;lt;div class="ul"&amp;gt;
      &amp;lt;ul class="list"&amp;gt;
        &amp;lt;li class="l1 li"&amp;gt;Read a book&amp;lt;/li&amp;gt;
        &amp;lt;li class="l2 li"&amp;gt;Finish writing my article&amp;lt;/li&amp;gt;
        &amp;lt;li class="l3 li"&amp;gt;Draft my resume&amp;lt;/li&amp;gt;
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;

    &amp;lt;script&amp;gt;
      // Parent element
      document.querySelector("ul").addEventListener("click", function (e) {
        const target = e.target;
        if (target.classList.contains("li")) {
          target.style.background = "red";
        }
      });
    &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;In the code above, you will notice that an &lt;code&gt;addEventListener()&lt;/code&gt; function has been added to the parent class of the &lt;code&gt;li&lt;/code&gt; element. The &lt;code&gt;target&lt;/code&gt; property of the event object has been accessed and stored into a &lt;code&gt;target&lt;/code&gt; variable. This is then used to check if the target element contains a class of &lt;code&gt;li&lt;/code&gt;. If that is true, the code in the &lt;code&gt;if&lt;/code&gt; block executes anytime a target element is clicked.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.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%2F2wz11qpi5me8ahyqcwff.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.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%2F2wz11qpi5me8ahyqcwff.png" alt="This image displays a list turning red once it is clicked."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;In summary, this article has tried to shed more light on event propagation and delegation in JavaScript as well as how they work. While event propagation, with its two phases: capturing and bubbling, describe how events travel up and down the Document Object Model(DOM) tree when they are fired on the target element, event delegation is how you can use the knowledge that events travel through the DOM tree to handle events at any of the parent elements of the target element concerned. Moreover, you can decide to stop the propagation of events by using the &lt;code&gt;e.stopPropagation()&lt;/code&gt; method.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>web3</category>
      <category>programming</category>
    </item>
    <item>
      <title>Things Every Beginner Needs to Know About Objects In JavaScript</title>
      <dc:creator>Okure U. Edet Kingsley🧑‍💻🚀</dc:creator>
      <pubDate>Sat, 08 Jul 2023 07:30:09 +0000</pubDate>
      <link>https://dev.to/itzz_okure/things-every-beginner-needs-to-know-about-objects-in-javascript-bgc</link>
      <guid>https://dev.to/itzz_okure/things-every-beginner-needs-to-know-about-objects-in-javascript-bgc</guid>
      <description>&lt;p&gt;&lt;strong&gt;Prerequisite&lt;/strong&gt;&lt;br&gt;
For the reader to understand the contents of this article, it is essential to&lt;br&gt;
have an understanding of HTML, CSS, and basic JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Table of Contents&lt;/strong&gt;&lt;br&gt;
• Introduction&lt;br&gt;
• What are objects?&lt;br&gt;
• Creating objects in JavaScript &lt;br&gt;
• Accessing and modifying the property and value of objects in JavaScript &lt;br&gt;
• Object method and the ‘this’ keyword&lt;br&gt;
• When to use objects in our code&lt;br&gt;
• conclusion&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
Data types and data structures are common to all programming languages. In JavaScript, data types include; numbers, strings, Booleans, undefined, null, &lt;em&gt;bigint&lt;/em&gt;, and symbols. Other data structures include objects, arrays, maps, and sets. This article will explain what objects are, basic object syntax and how they are created, how to access properties and methods of objects, object methods, the 'this' keyword, and when it should be used.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are objects?&lt;/strong&gt;&lt;br&gt;
Objects are a non-primitive data type used to store complex collections of data. It functions as an entity that stores data in key-value pairs. It consists of functions and variables, which are called methods and properties. Just like an array, any expression can be input into an object value. Thus when creating objects, you may choose to give them a static value called a property or a dynamic value called a method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating objects in JavaScript&lt;/strong&gt;&lt;br&gt;
There are various ways of creating objects. They can be created by using the object literal syntax, constructor functions, ECMAScript 6 classes, and the _&lt;em&gt;object.create&lt;/em&gt;  method. Let us examine them individually.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Object literal syntax&lt;/strong&gt;
This is the most obvious way of creating objects in JavaScript. It involves declaring a variable and giving the values assigned to the variable a name. This is what we mean when we say an object stores data in key-value pairs. For example, the code below has three properties; &lt;em&gt;name,&lt;/em&gt; &lt;em&gt;job&lt;/em&gt;, and &lt;em&gt;birthYear&lt;/em&gt;, and a method &lt;em&gt;calcAge&lt;/em&gt;: &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EP3slp0v--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cvbtnozd39pop1a6nifr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EP3slp0v--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cvbtnozd39pop1a6nifr.png" alt="Image description" width="800" height="608"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This syntax enables values to be assigned names called keys. For example, the key ‘name’ has a value of 'John Samuels.' This is what JavaScript object syntax looks like.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Constructor functions&lt;/strong&gt;
Another way of creating an object is by using a function to build an object. This function is called a constructor function. A function expression or a function declaration can be used to create a constructor function. However, an arrow function will not work as a constructor function simply because it does not have its own ‘this’ keyword which is essential to a constructor function. The function is then called with the new operator. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the code below, a function called ‘Individual’ is created with the parameters of &lt;em&gt;name,&lt;/em&gt; &lt;em&gt;job,&lt;/em&gt; and &lt;em&gt;birthYear&lt;/em&gt;. The function is then called using the new operator. When the new operator is used to call a constructor function, like in the code below, an empty object is created, and the 'this' keyword is set to that empty object which is then linked to a prototype and returned by the function. If you take a look at the code below, the properties are declared with the 'this' keyword inside the constructor function, and the new empty object will then contain all those properties, which are then returned as &lt;em&gt;john().&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ms4mHqKc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ly0h0l09red7exph3ggi.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ms4mHqKc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ly0h0l09red7exph3ggi.png" alt="Image description" width="800" height="348"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can also define methods on the constructor function which will then be accessed by every object created by that constructor function. This is generally known as prototypal inheritance. The prototype property exists on all functions, including a constructor function. For example, in the code below, the &lt;em&gt;calcAge _method has been defined on the prototype property of the constructor function _Individual.&lt;/em&gt; The &lt;em&gt;john _object, which has been created using the constructor function, will get access to the _calcAge&lt;/em&gt; method.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sWcZ5oCv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gxv10boaaswkclbk69ms.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sWcZ5oCv--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gxv10boaaswkclbk69ms.png" alt="Image description" width="800" height="574"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;ES6 Classes&lt;/strong&gt;
ECMAScript 6 introduced the use of the class keyword to create objects in JavaScript. ES6 classes allow us to do the same thing we did on the constructor function using a more modern syntax. A class is like a function, and like functions, a class can be created by a class expression or declaration. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the code below, an &lt;em&gt;Individual _class is created with a constructor method inside it. The constructor method functions like a constructor function declaring the properties with the ‘this’ keyword. The _calcAge&lt;/em&gt; method is defined outside the constructor method, and it is automatically added to the prototype property of the class, which can then be inherited by any object created using the class &lt;em&gt;Individual&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--T0myU7to--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/818j4vr0pka4a12qrrqm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--T0myU7to--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/818j4vr0pka4a12qrrqm.png" alt="Image description" width="800" height="412"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Object dot create method&lt;/strong&gt;.
&lt;em&gt;Object.create&lt;/em&gt; is a function that works differently from ES6 classes and constructor functions. Prototypal inheritance does exist. However, the new operator is not used to call the function, and constructor functions are not needed. Instead, the &lt;em&gt;object.create&lt;/em&gt; function is used to manually set the prototype of an object to any other object we create. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the code below, an object called &lt;em&gt;individual&lt;/em&gt; is created using the object literal syntax. A method called property which contains the parameters of the properties to be set is defined inside the object. The &lt;em&gt;calcAge&lt;/em&gt; method is also defined in the object. An object called &lt;em&gt;john&lt;/em&gt; is then created, and the _object.create _method is used to set the prototype of this empty object to the Individual object. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--dcA4ueRy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ns9a2y5irjkvpcnqtkbf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--dcA4ueRy--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ns9a2y5irjkvpcnqtkbf.png" alt="Image description" width="800" height="685"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;object.create&lt;/em&gt; method is important as it can also be used to implement inheritance between classes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Accessing and modifying the property and value of an object&lt;/strong&gt;&lt;br&gt;
We have seen from the above illustrations the various ways of creating objects. It is also important for you to know how to access and modify the property and value of an object. There are two common ways of doing this: using the dot notation and the bracket notation. Apart from these two ways, the value of an object can also be accessed by destructuring. Let us consider them one by one.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Dot notation&lt;/strong&gt;
This way of accessing data from an object is straightforward. All we have to do is use the dot operator between the object and the property we want to access. For example: In the code below, the property name was retrieved from the object using the dot notation, and it was then logged to the console.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--pNdHGIJH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sfzpghj4s9dmx0f206t4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--pNdHGIJH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sfzpghj4s9dmx0f206t4.png" alt="Image description" width="800" height="433"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The dot can also be used to add new properties to the object. For example, the code below adds a property called &lt;em&gt;birthYear _with a value of ‘2002’ to the _john&lt;/em&gt; object using an equal to operator.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ilAE7fVe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/spszliopv3bkw62smu0l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ilAE7fVe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/spszliopv3bkw62smu0l.png" alt="Image description" width="800" height="278"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Bracket notation&lt;/strong&gt;
Properties are accessed or added to objects using brackets. The difference between the dot notation and the bracket notation is that any expression can be put inside the bracket. See the example below:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ADA1rzE1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6o7ajpcphqyytxeg02i6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ADA1rzE1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6o7ajpcphqyytxeg02i6.png" alt="Image description" width="800" height="357"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; &lt;strong&gt;Destructuring&lt;/strong&gt;
Destructuring is a feature in JavaScript that allows you to retrieve data from an object or even an array and store them in variables. This is very useful when we receive data from a web API which is usually stored in objects. The syntax for destructuring an object is quite similar to that used in destructuring an array. The only difference is when destructuring an object, you should use the curly braces like this:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--UQhgq8QD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3k7hkkhc295z7cav9kc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--UQhgq8QD--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3k7hkkhc295z7cav9kc.png" alt="Image description" width="800" height="305"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the code above, the curly braces come after the keyword &lt;em&gt;const&lt;/em&gt;, and the variable names inside the curly braces are identical to the property names. The variables are then used to form a sentence, as seen above.&lt;br&gt;
We can, however, change the variable names like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--AsC6wIbd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p91yxw45w6fr0y82jrq6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--AsC6wIbd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p91yxw45w6fr0y82jrq6.png" alt="Image description" width="800" height="325"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Thus in the code above, the new variable names are defined in a similar way we define properties in object literals.&lt;/p&gt;

&lt;p&gt;However, what if the property we want to retrieve does not exist on the object? Normally in such a situation, it is supposed to show us undefined. Nevertheless, when destructuring our object, we can give such variable a default value like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cxwaHIyJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tqag6qdu2xx6l1bp6aqk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cxwaHIyJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tqag6qdu2xx6l1bp6aqk.png" alt="Image description" width="800" height="253"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above code, the property &lt;em&gt;birthYear&lt;/em&gt; does not exist, but we gave it a default value of two thousand and two using the equal to and brackets sign.  &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Object methods and the ‘this’ keyword&lt;/strong&gt;&lt;br&gt;
If you have come so far in this article, you will discover that we have used methods a few times. Methods are like properties of an object. They are more dynamic, however. A method is essentially a function that is a property of an object. They can be likened to an action performed on an object. For example, the &lt;em&gt;calcAge&lt;/em&gt; method in the code below calculates the age of the object &lt;em&gt;john&lt;/em&gt; and returns it. It is then logged to the console in a nice string.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--PIDUkX6L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wb3uv2ak6q3rd022ob7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--PIDUkX6L--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wb3uv2ak6q3rd022ob7.png" alt="Image description" width="800" height="496"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The ‘this’ keyword functions differently in JavaScript than it does in other programming languages. It is more like a special variable that is created for every function. The 'this' keyword points to the function in which it is called. This means that it takes the value of the object. The values of the 'this' keyword are, however, not static. It depends on how the function is called, and its value is assigned when the function is executed or called. A function may be called as a property of an object that is, a method, in which case it points to the object that is calling that method. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--BobepjtA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39talnyk1a4x6qde121x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--BobepjtA--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39talnyk1a4x6qde121x.png" alt="Image description" width="800" height="469"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the above example, the ‘this’ keyword points to the john object, which is the object calling the &lt;em&gt;calcAge&lt;/em&gt; method.&lt;br&gt;
Functions may also be called normally. That is, without it being a property of an object. In this case, the ‘this’ keyword will be undefined if it is in strict mode else, it will point to the global object, which in the case of the browser is the (window object).&lt;br&gt;
An arrow function does not have its own ‘this’ keyword. Using the ‘this’ keyword in an arrow function will only point to its outer or parent function.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--S91fj9L8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5crgbcazwpcbjuxwxd63.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--S91fj9L8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5crgbcazwpcbjuxwxd63.png" alt="Image description" width="800" height="384"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the example above, the arrow function &lt;em&gt;func&lt;/em&gt; points to the outer &lt;em&gt;calcAge&lt;/em&gt; method.&lt;br&gt;
Lastly, it is important to note that if a function is called as an event listener, the ‘this’ keyword will always point to the DOM element that the handler function is attached to.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--78DIj3e8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v032i56wfref5xag0lvw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--78DIj3e8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v032i56wfref5xag0lvw.png" alt="Image description" width="800" height="212"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When to use objects in our code&lt;/strong&gt;&lt;br&gt;
Since objects are containers for storing data, usually complex data, it is advisable to use them when we want to do just that. Also, unlike arrays, data in an object does not need to be structured. This means that if we want to store unstructured data, objects are our best bet. We can also decide to organize our code in an object-like manner. This is known as Object Oriented Programming(OOP).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
This article has tried to give you a brief overview of objects in JavaScript. This includes what objects are, their syntax and how they are created, how we can access object properties, their methods and the 'this' keyword, and when we should use objects in our code. Of course, there is still a lot to learn about objects in JavaScript, such as how prototypes work and Object Oriented Programming in JavaScript. If you wish to learn more, you can visit this site &lt;a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects"&gt;https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects&lt;/a&gt; for more info.&lt;/p&gt;

&lt;p&gt;This article was written by Okure U. Edet Kingsley. You can follow me on Twitter &lt;a class="mentioned-user" href="https://dev.to/itzz_okure"&gt;@itzz_okure&lt;/a&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>web3</category>
    </item>
  </channel>
</rss>
