The Journey of #100DaysOfCode (Baqer_Qabalan)

Hello community!

I’ve been challenged to start the #100DayCodeChallenge, and guess what?! Challenge Accepted!! So for the next 100 days, I’ll be sharing my knowledge, learning, and experiences.

Below is my progress from previous days, and I’ll now be updating regularly from today. If you’re up for it, join me on this adventure!

7e886ab87e66a70d1ba74283be9d2ce98a0fdabe_2_690x388

3 Likes

Imagine you order a pizza, so the process can be broken into several steps: You call the bakery and place an order for a pizza, then the bakery confirms your order and gives you an estimated delivery time. At this point, a promise is created and it is in the “pending” state. During this time, you’re waiting for the pizza to be delivered, and you don’t know if it will arrive on time, be delayed, or if there might be an issue with the bakery. So, the promise is still in the “pending” state. Now, there are two cases: if the pizza arrives (order is fulfilled), the promise is fulfilled. If there is an issue with the bakery and the pizza doesn’t arrive (order is rejected), the promise is rejected.

In this code:
A function called orderPizza is created that returns a new Promise, so this promise starts in the “pending” state.
The setTimeout function is used to simulate the wait time for the pizza delivery. This represents the period during which the promise is pending.
After 2 seconds, a random boolean value called isPizzaDelivered determines whether the pizza is delivered or not:
If the boolean is true, the promise is resolved by calling resolve, so the promise is moved to the “fulfilled” state.
If the boolean is false, the promise is rejected by calling reject, and the promise is moved to the “rejected” state.
The then method is used to handle the case when the promise is fulfilled, while the catch method is used to handle the case when the promise is rejected.

As a result, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide a way to handle asynchronous operations more efficiently than traditional callback-based approaches.
100daysofcode lebanon-mug

4 Likes

Day2: How MongoDB leverages BSON?

BSON (Binary JSON) is a binary-encoded serialization format that is used to store documents and make remote procedure calls in MongoDB. It extends the JSON model to provide additional data types and to be efficient for encoding and decoding within different languages.

Consider the following JSON document:

{
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Elm St",
    "city": "Somewhere",
    "state": "CA"
  },
  "phones": ["123-456-7890", "987-654-3210"],
  "isActive": true
}

In BSON:
\x16\x00\x00\x00\x02name\x00\x08\x00\x00\x00John Doe\x00\x10age\x00\x1e\x00\x00\x00\x03address\x00\x3d\x00\x00\x00\x02street\x00\x09\x00\x00\x00123 Elm St\x00\x02city\x00\x09\x00\x00\x00Somewhere\x00\x02state\x00\x03\x00\x00\x00CA\x00\x00\x04phones\x00\x1f\x00\x00\x00\x020\x00\x0c\x00\x00\x00123-456-7890\x0001\x00\x0c\x00\x00\x00987-654-3210\x00\x00\x08isActive\x00\x01\x00\x00\x00

As a result:
Using BSON, MongoDB combines the flexibility of JSON with the efficiency of binary encoding, making it a robust solution for handling large and complex datasets.
100daysofcode lebanon-mug

3 Likes

Day 3: Arrow Functions
Arrow functions in JavaScript are a concise syntax for writing function expressions.
How to implement it?
1-Simple Arrow Functions:
const addArrow = (x, y) => x + y;

2-Arrow Function with single parameter:
const squareArrow = x => x * x;

3-Arrow Function with no parameters:
const greetArrow = () => 'Hello, world!';

2 Likes

Day 4: What is a Blob?

A Blob (Binary Large Object) in JavaScript represents raw binary data, like images or files. It’s often used to handle and store large amounts of data, allowing web applications to read, save, and send this data efficiently.

How to use it?

const jsonData = { name: "John", age: 30 };
const jsonString = JSON.stringify(jsonData);
const jsonBlob = new Blob([jsonString], { type: 'application/json' });

console.log(jsonBlob);

In this code, first, the JSON data is converted into a string using JSON.stringify(). Then, this stringified JSON data is used to create a Blob with a JSON file.

100daysofcode lebanon-mug

3 Likes

Day 5: What is Node.js?

Node.js is a powerful JavaScript runtime built on Chrome’s V8 engine. It allows developers to run JavaScript on the server-side, enabling the creation of fast and scalable network applications. Here’s why Node.js is so popular:

  1. Asynchronous and Event-Driven: Node.js is designed to handle many connections simultaneously, making it ideal for building real-time applications like chat servers, online gaming, and live streaming.
  2. Single Programming Language: Use JavaScript for both client-side and server-side development, streamlining your development process.
  3. NPM Ecosystem: Node.js comes with the Node Package Manager (NPM), which hosts thousands of reusable packages and libraries, making development faster and easier.

Why Choose Node.js?

  1. High Performance.
  2. Fast Development.
  3. Community Support.

100daysofcode lebanon-mug

3 Likes

Day 6: CSS (Cascading Style Sheets)

Imagine Google’s intro page without CSS.
Would anyone be interested in visiting this platform? Of course not.
So, what does CSS do?

That’s what CSS does. CSS is essential for styling web pages, making them look attractive and user-friendly.

100daysofcode lebanon-mug

3 Likes

Day 7: Local Storage in JavaScript

:mag: What is Local Storage?

Local Storage is a web storage feature that allows you to store data in the browser. Unlike cookies, the storage limit is much larger (typically around 5MB) and the data is not sent to the server with every request.

:blue_book: Why Use Local Storage?

  • Persistence: Data remains stored even after the browser is closed and reopened.
  • Capacity: Can store more data compared to cookies.
  • Simple API: Easy to use with a straightforward API.

:sparkles: Basic Usage of Local Storage

Here’s how you can use Local Storage to store, retrieve, and remove data:

Storing Data

To store data, use the setItem method. The data is stored as a key-value pair.

// Store a string
localStorage.setItem('name', 'John Doe');

Retrieving Data

To retrieve data, use the getItem method. Remember to parse it back to an object if it was stored as a JSON string.

// Retrieve a string
const name = localStorage.getItem('name');
console.log(name); // Outputs: John Doe

Removing Data

To remove data, use the removeItem method.

localStorage.removeItem('name');

Clearing All Data

To clear all data stored in Local Storage, use the clear method.

localStorage.clear();

As a conclusion, Local Storage is a powerful feature for storing data on the client side.
100daysofcode lebanon-mug

3 Likes

Day 8: MongoDB Indexes

:mag: MongoDB Indexes in Action: A Real-Life Scenario

Imagine you are managing an online bookstore, and your MongoDB database has a collection named books to store information about each book. Here’s how indexes can help improve the performance of various queries.

:books: The books Collection

Each document in the books collection might look something like this:

{
  "_id": "1",
  "title": "JavaScript: The Good Parts",
  "author": "Douglas Crockford",
  "year": 2008
}

:mag: Common Query and How Indexes Help

Finding a Book by Title

Query:

db.books.find({ title: "JavaScript: The Good Parts" });

Without an Index: MongoDB scans every document in the books collection to find the match, which can be slow if there are thousands of books.

With a Single Field Index: Create an index on the title field:

db.books.createIndex({ title: 1 });

This index allows MongoDB to quickly locate books by title, significantly speeding up the query.

100daysofcode lebanon-mug

3 Likes

Day 9: Regular Expressions (RegEx) in JavaScript

:mag: What are Regular Expressions?

Regular Expressions, commonly known as RegEx, are patterns used to match character combinations in strings. In JavaScript, RegEx provides powerful pattern-matching capabilities that allow you to search, replace, and validate text efficiently.

:blue_book: Why Use RegEx?

  • Validation: Validate input fields, such as email addresses, phone numbers, and passwords.
  • Searching: Search for specific patterns within strings.
  • Replacing: Replace occurrences of a pattern with a new substring.
  • Extracting: Extract substrings that match a pattern.

:sparkles: How to Create a RegEx?

There are two ways to create a RegEx in JavaScript:

  • Using literal notation:
const pattern = /abc/;
  • Using the RegExp constructor:
const pattern = new RegExp('abc');

:sparkles: There are several methods that RegEx use such as test, exec, match, replace, split… each has its usage

#Example:

Matching Digits

const pattern = /\d+/;
console.log(pattern.test('123')); // true

100daysofcode lebanon-mug

3 Likes

Day 10: Session Storage in JavaScript

:mag: What is Session Storage?

Session Storage is a type of web storage that allows you to store data for the duration of a page session. This means the data is accessible only while the browser is open and the page session is active. Once the browser is closed, the data is cleared.

:sparkles: Basic Operations

  1. Storing Data

To store data in session storage, use the setItem method:

sessionStorage.setItem('key', 'value');

Example:

sessionStorage.setItem('username', 'Baqer_Qabalan');
  1. Retrieving Data

To retrieve data from session storage, use the getItem method:

const value = sessionStorage.getItem('key');

Example:

const username = sessionStorage.getItem('username');
console.log(username); // Output: 'Baqer_Qabalan''
  1. Removing Data

To remove a specific item, use the removeItem method:

sessionStorage.removeItem('key');

Example:

sessionStorage.removeItem('username');
  1. Clearing All Data

To clear all data from session storage, use the clear method:

sessionStorage.clear();

Example:

sessionStorage.clear();

100daysofcode lebanon-mug

3 Likes

Day 11: Exploring the Fetch API in JavaScript

:mag: What is the Fetch API?

The Fetch API is a modern, promise-based approach to making network requests in JavaScript. It provides an easy and flexible way to interact with RESTful services and fetch resources across the web.

:blue_book: Why Use the Fetch API?

  • Simplicity: Easy to use with a clean and straightforward syntax.
  • Promises: Uses promises, allowing for better control over asynchronous operations.
  • Compatibility: Supported in all modern browsers.

:sparkles: Basic Usage

  1. Making a GET Request

To fetch data from a server, use the fetch function:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
  1. Making a POST Request

To send data to a server, use the fetch function with the POST method:

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'John', age: 30 })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

100daysofcode lebanon-mug

3 Likes

Day 12: Asynchronous JavaScript with Async/Await

:arrows_counterclockwise: What is Asynchronous JavaScript?

Asynchronous JavaScript allows you to perform long-running tasks, like fetching data from an API, without blocking the main thread. This makes your web applications more responsive and user-friendly.

:blue_book: Why Use Async/Await?

  • Simplified Syntax: Async/await provides a cleaner and more readable way to work with promises compared to chaining .then() and .catch() methods.
  • Error Handling: Easier error handling using try...catch blocks.
  • Sequential Execution: Allows for writing asynchronous code that looks and behaves like synchronous code.

:sparkles: How to Use Async/Await

  1. Defining an Async Function

An async function is declared using the async keyword before the function definition:

async function fetchData() {
  // Code inside here is asynchronous
}
  1. Using await

The await keyword pauses the execution of the async function until the promise is resolved:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
  1. Handling Errors

With async/await, you can handle errors using a try...catch block:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

100daysofcode lebanon-mug

3 Likes

Day 13: *** Responsive Design with CSS Media Queries***

:iphone: What are Media Queries?

Media queries are a powerful feature in CSS that allow you to create responsive designs. They enable your web pages to adapt to different screen sizes, orientations, and resolutions, ensuring a consistent and user-friendly experience across devices.

:blue_book: Why Use Media Queries?

  • Responsive Design: Tailor your layouts and styles for various screen sizes, from mobile phones to large desktops.
  • Optimized User Experience: Improve usability by adjusting the design based on the user’s device.
  • Future-Proofing: Prepare your website to handle new devices and screen sizes as technology evolves.

:arrows_counterclockwise: Example

Imagine you’re designing a website with a navigation menu that should look different on mobile and desktop. With media queries, you can hide the desktop menu on mobile and show a hamburger menu instead:

/* Desktop Menu */
.nav-menu {
  display: flex;
}

/* Mobile Menu */
@media (max-width: 768px) {
  .nav-menu {
    display: none;
  }

  .hamburger-menu {
    display: block;
  }
}

100daysofcode lebanon-mug

3 Likes

Day 14: JavaScript Spread Operator

:rocket: What is the Spread Operator?

The spread operator (...) in JavaScript is a powerful tool that allows you to expand arrays and objects into individual elements or properties. It simplifies the way you handle data structures, making your code more readable and concise.

:sparkles: How Does the Spread Operator Work?

  1. Copying Arrays

Create a new array that’s an exact copy of another:

const originalArray = [1, 2, 3];
const copiedArray = [...originalArray];

console.log(copiedArray); // Output: [1, 2, 3]
  1. Merging Arrays

Combine multiple arrays into one:

const array1 = [1, 2];
const array2 = [3, 4];
const mergedArray = [...array1, ...array2];

console.log(mergedArray); // Output: [1, 2, 3, 4]
  1. Copying Objects

Create a new object that’s an exact copy of another:

const originalObject = { a: 1, b: 2 };
const copiedObject = { ...originalObject };

console.log(copiedObject); // Output: { a: 1, b: 2 }

100daysofcode lebanon-mug

3 Likes

Day 15: Using pre-save middleware in MongoDB with Mongoose

:wrench: What is pre-save middleware?

In MongoDB, when using Mongoose as an Object Data Modeling (ODM) library, the pre-save middleware is a powerful tool that allows you to execute custom logic right before a document is saved to the database. This is incredibly useful for tasks like data validation, hashing passwords, or updating timestamps automatically.

:sparkles: How does pre-save middleware work?

userSchema.pre("save", async function(next){
    try{
        if(!this.isModified("password")){ 
            next();
        }
        this.password = await bcrypt.hash(this.password, 12);
    }catch(error){
        console.log(error); 
    }
});

:bar_chart: When to Use pre-save Middleware?

  • Sensitive Data
  • Automatic Field Updates
  • Custom Validation

:bulb: Conclusion

The pre-save middleware in Mongoose is an essential feature for anyone working with MongoDB. It gives you control over your data by allowing you to execute custom logic before saving documents.

100daysofcode lebanon-mug

2 Likes

Day 16: Exploring Query Functions in MongoDB

:mag: Unlocking Data with MongoDB Query Functions

MongoDB offers a range of powerful query functions that allow you to efficiently find, filter, and manipulate data within your collections. Whether you’re retrieving a single document or filtering complex datasets, these functions are your go-to tools for interacting with your database.

:sparkles: Key Query Functions

  1. find()

  2. findOne()

  3. findById()

  4. findOneAndDelete()

  5. findOneAndUpdate()

:bulb: Why Use MongoDB Query Functions?

  • Efficient Data Retrieval: Quickly find and filter the exact data you need.
  • Powerful Data Manipulation: Update, insert, and delete documents with ease.
  • Advanced Aggregation: Perform complex calculations and transformations directly within the database.

Stay tuned as we dive into each of these functions in upcoming posts! :blush:

2 Likes

Day 17: find() Query Function in MongoDB

:mag: Exploring the find() Query Function

The find() function in MongoDB is your go-to method for retrieving multiple documents from a collection. It allows you to filter through your data and return exactly what you need, making it an essential tool for working with MongoDB.

:sparkles: How It Works

The find() function can retrieve all documents or filter documents based on specific criteria. It returns a cursor, which you can iterate over to access the documents.

:computer: Example Usage

Let’s say you have a collection of users, and you want to find all users who have an active status:

users.find({ status: 'active' })

:bar_chart: What It Does

  • Filter Data: Only documents where the status field is 'active' will be returned.
  • Flexible Queries: You can combine multiple conditions to narrow down your search.
  • Returns a Cursor: This allows you to efficiently iterate through large datasets.

:bulb: Pro Tip:

You can further refine your query by adding projection, sorting, or limiting the results:

users.find({ status: 'active' }, { name: 1, email: 1 }).sort({ name: 1 }).limit(10)

This will return only the name and email fields of the first 10 active users, sorted by their names.
100daysofcode lebanon-mug

3 Likes

Day 18: *** findOne() Query Function in MongoDB***

:mag: Exploring the findOne() Query Function

The findOne() function in MongoDB is perfect when you need to retrieve a single document from a collection. It’s designed to return the first document that matches your query criteria, making it efficient and straightforward.

:sparkles: How It Works

Unlike the find() function, which returns multiple documents, findOne() stops searching after finding the first match. This is ideal when you’re looking for a unique record or just need a quick lookup.

:computer: Example Usage

Imagine you have a collection of users, and you want to find the user with a specific username:

users.findOne({ username: 'baqer_qabalan' })

:bar_chart: What It Does

  • Single Document Retrieval: Fetches the first document that matches the query criteria.
  • Simplicity: No need to iterate through results; you get the document directly.
  • Efficient Searches: Quickly locates the desired document without scanning the entire collection.

:bulb: Pro Tip:

You can also combine findOne() with projection to retrieve only specific fields from the document:

users.findOne({ username: 'baqer_qabalan' }, { name: 1, email: 1 })

This query will return only the name and email fields of the user with the username 'baqer_qabalan'.

100daysofcode lebanon-mug

2 Likes

Day 19: findById() Query Function in MongoDB

:mag: Exploring the findById() Query Function

The findById() function in MongoDB is a powerful and convenient method for retrieving a single document based on its unique _id. This function simplifies the process of fetching documents by their unique identifier, ensuring you get the exact record you need with minimal effort.

:sparkles: How It Works

Every document in MongoDB has a unique _id field, which acts as a primary key. The findById() function leverages this to quickly locate and return the document associated with a specific _id value.

:computer: Example Usage

Suppose you have a user collection, and you want to find a user by their unique ID:

const userId = "60d5f60bc25e4b456789abcd";
users.findById(userId)

:bar_chart: What It Does

  • Precise Document Retrieval: Fetches a document based on its unique _id, ensuring you get the correct record.
  • Simplifies Queries: No need to specify the query object; just pass the _id directly.
  • Efficiency: Optimized for quick lookups using the primary key.

:bulb: Pro Tip:

You can combine findById() with projection to retrieve only specific fields:

users.findById(userId, { name: 1, email: 1 })

This query will return only the name and email fields for the user with the specified _id.
100daysofcode lebanon-mug

2 Likes