Full Stack Devp

Download as pdf or txt
Download as pdf or txt
You are on page 1of 119

Install VS Code

Andarki Namaste! Ippud VS Code ela install cheyyalo chuddam :)

1. Download VS Code: Go to the official Visual Studio Code website at


https://code.visualstudio.com/ and click on the "Download for Windows," "Download
for macOS," or "Download for Linux" button, depending on your operating system.
2. Install VS Code on Windows:
o For Windows, the downloaded file will typically be an installer (.exe) file.
Run the installer by double-clicking it.
o Follow the on-screen instructions in the installer. You can choose the default
installation settings for most users.
3. Install VS Code on macOS:
o For macOS, the downloaded file will be a .zip archive. Double-click the
downloaded .zip file to extract it.
o Drag the Visual Studio Code application from the extracted folder to the
Applications folder. This will install VS Code on your Mac.
4. Install VS Code on Linux:
o For Linux, the download package will vary depending on your distribution.
Common package formats include .deb (Debian/Ubuntu) and .rpm (Red
Hat/Fedora). Download the appropriate package for your distribution.
o Install the package using your package manager. For example, on
Debian/Ubuntu-based systems, you can use the dpkg command: Replace
<package-name> with the actual name of the downloaded package.
o sudo dpkg -i <package-name>.deb
o
o You may also need to resolve any dependencies that are missing. Use your
package manager to install these dependencies.

Anthe VS Code ithe install ipoindi! Ippud andulo poy pani cheskundam :)

HTML Introduction

HTML stands for HyperText Markup Language. It is the standard markup language used to
create and structure content on the World Wide Web (WWW). HTML is the backbone of
most web pages and is used to define the structure and layout of web documents, including
text, images, links, forms, and multimedia.

Heading, Paragraph and Button tags

<h1>, <p>, and <button> tags gurinchi ithe chuddam mowa ippudu.

<h1> Tag (Heading 1):

 The <h1> tag is used to define the top-level or main heading of a webpage or a section
within a webpage.
 It represents the most important and largest heading on the page.
 Web browsers typically render text within <h1> tags in a larger and bold font to
emphasize its significance.
 It's good practice to use <h1> for the main title of a page, and you can use it
hierarchically with other heading tags like <h2>, <h3> ,<h4> <h5> ,<h6>for
subheadings with decreasing importance.

Example:

<h1>Welcome to MassCoders HTML Tutorial</h1>


<h2>Welcome to MassCoders HTML Tutorial</h2>
<h3>Welcome to MassCoders HTML Tutorial</h3>
<h4>Welcome to MassCoders HTML Tutorial</h4>
<h5>Welcome to MassCoders HTML Tutorial</h5>
<h6>Welcome to MassCoders HTML Tutorial</h6>

<p> Tag (Paragraph):

 The <p> tag is used to define a paragraph of text on a webpage.


 It's one of the most common HTML tags for structuring and formatting text content.
 Text enclosed within <p> tags is typically displayed with a line break before and after
it, creating distinct paragraphs.
 You can use <p> tags to separate and format different sections of text on a webpage.

Example:

<p>Founder - Dodagatta Nihar</p>

<button> Tag:

 The <button> tag is used to create a clickable button on a webpage.


 It can be used to trigger JavaScript functions or perform form submission actions
when clicked. (Deeni gurinchi manam mana future sessions lo telskuntam)
 You can include text or other HTML elements inside the <button> tag to create
custom button content.
 <button> elements are often used in forms to create submit buttons or for other
interactive features.

Example:

<button>Subscribe Here!</button>

Attempt Quiz → Click Here

Assignment Question:

Create an HTML webpage using the concepts introduced in this session, specifically
employing the <h1>, <p>, and <button> tags.

Congrats Mowa Successful ga complete chesnav! Next session lo kaluddam :)


 CSS Color and Background Color

Watch Tutorial → Click Here

Eeroj manam CSS vaadi rangul tho aadukundam :)

Introduction to CSS (Cascading Style Sheets)

o What is CSS?
 CSS stands for Cascading Style Sheets.
 It is a stylesheet language used for describing the presentation and
formatting of a document written in HTML (Hypertext Markup
Language).
 CSS allows you to control the layout, colors, fonts, and other visual
aspects of a web page, making it visually appealing and user-friendly.
o Why Use CSS?
 Separation of Concerns: CSS separates the content (HTML) from its
presentation, making it easier to maintain and update web pages.
 Consistency: CSS enables you to apply consistent styles across
multiple pages of a website.
 Flexibility: You can change the look and feel of a website without
altering its underlying structure (HTML).

Including CSS using External CSS File

<!-- External CSS -->


<head>
<link rel="stylesheet" href="style.css">
</head>

CSS Color

o Setting Text Color


 You can change the text color using the color property.
 CSS supports a set of named colors like "red," "blue," "green," etc.

/* style.css */
p {
color: blue; /* Using a named color */
}

Background Color

o Setting Background Color


 You can change the background color of an element using the
background-color property.
 Like text color, you can use named colors for background color as
well.
/* style.css */
body {
background-color: green; /* Using a named color for the background
*/
}

CSS allows for a wide range of styling options beyond just color and background
color, including font size, margin, padding, border, and more. Veeti gurinchi manam
further tutorials lo telskuntam. Stay tuned :)

Height and Width

In CSS, you can use the height and width properties to control the dimensions of
HTML elements. Here's how you can use them:

/* Set the height and width of an element with a class */


.box {
height: 100px; /* Set the height to 100 pixels */
width: 200px; /* Set the width to 200 pixels */
}

In this example, any element with the class box will have a height of 100 pixels and a
width of 200 pixels.

And in your HTML:

<div class="box">This is a box with a specified height and


width.</div>

This <div> element will have the specified height and width.

Text Alignment

The text-align property in CSS is used to control the horizontal alignment of text
within an element. Here's how it works:

/* Center-align text within a paragraph */


p {
text-align: center;
}

In this example, all text within <p> elements will be center-aligned.

<p>This is center-aligned text.</p>

Attempt Quiz → Click Here

Assignment Question:
Create a CSS rule that styles the header of the page with the following properties:

o Set the text color to green.


o Set the background color to pink.
o Set the height to 400px.
o Set the width to 500px.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 RGB HEX HSL Values | CSS Color

Watch Tutorial → Click Here

Color Picker → Click Here

Cloudinary → Click Here

Hello Mithrooooms! Eeroj manam enni rakalga color ki values ivacho chudham. In
CSS, there are several ways to specify color values. Each method has its own syntax
and use cases. Here are the most common types of color values in CSS:

Keyword Color Values:

CSS provides a set of predefined color keywords that represent common colors. These
keywords are easy to use and remember. For example:

color: red;
background-color: blue;

Some common keyword color values include red, blue, green, black, white,
yellow, and many others.

Hexadecimal Color Values:

Hexadecimal color values are represented as six-digit codes preceded by a hash


symbol (#). Each pair of digits represents the intensity of red, green, and blue (RGB)
in the color. For example:

color: #FF0000; /* Red */


background-color: #00FF00; /* Green */

In this example, #FF0000 represents the color red, where FF is the maximum intensity
of red, and 00 indicates no intensity of green and blue.

RGB Color Values:


RGB color values specify the intensity of red, green, and blue in a color using the
rgb() function. You can specify each color component's intensity as a percentage or
an integer value between 0 and 255. For example:

color: rgb(255, 0, 0); /* Red */


background-color: rgb(0, 255, 0); /* Green */

RGBA Color Values:

RGBA color values are similar to RGB, but they include an additional alpha channel,
which represents the opacity of the color. The alpha value is specified as a number
between 0 (fully transparent) and 1 (fully opaque). For example:

color: rgba(255, 0, 0, 0.5); /* Semi-transparent red */


background-color: rgba(0, 255, 0, 0.75); /* Semi-transparent green */

HSL Color Values:

HSL (Hue, Saturation, Lightness) color values represent colors by specifying the hue
(color), saturation (vividness), and lightness (brightness) using the hsl() function.
For example:

color: hsl(0, 100%, 50%); /* Red */


background-color: hsl(120, 100%, 50%); /* Green */

HSLA Color Values:

HSLA color values are similar to HSL, but they include an alpha channel for opacity,
just like RGBA. For example:

color: hsla(0, 100%, 50%, 0.5); /* Semi-transparent red */


background-color: hsla(120, 100%, 50%, 0.75); /* Semi-transparent
green */

These are the primary ways to specify color values in CSS. The choice of which
method to use depends on your specific design requirements and preferences.

Attempt Quiz → Click Here

Assignment Question:

Build a web page utilizing hexadecimal, RGB, RGBA, HSL, and HSLA color values.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 HTML Tags
Watch Tutorial → Click Here

Hi Prends! Eeroj manam HTML Tags ante entido chuddam.

HTML Tags

An HTML tag is a fundamental component of HTML (Hypertext Markup Language),


which is the standard language used to create and structure content on the World
Wide Web. HTML tags are used to define and format elements within a web page.
They consist of an opening tag, content, and a closing tag (in most cases).

Here's a breakdown of the parts of an HTML tag:

1. Opening Tag: The opening tag is enclosed in angle brackets (<>) and
indicates the beginning of an HTML element. It typically contains the name of
the element. For example, <p> is the opening tag for a paragraph element.
2. Content: The content is the actual information or text you want to display
within the HTML element. It appears between the opening and closing tags.
3. Closing Tag: The closing tag also uses angle brackets but includes a forward
slash (/) before the element name. It indicates the end of the HTML element.
For example, </p> is the closing tag for a paragraph element.

Here's a simple example of an HTML tag for a paragraph element:

<p>Subscribe to Dodagatta Nihar</p>

In this example:

o <p> is the opening tag.


o "Subscribe to Dodagatta Nihar" is the content.
o </p> is the closing tag.

HTML tags are the building blocks of web pages, and by using different tags and
attributes, you can structure text, insert images, create links, define headings, and
much more, allowing you to create rich and interactive web content.

HTML Tags with Closing Tags (Examples)

7. Headings (h1 - h6):


 Headings are used to define the headings or titles of sections on a
webpage.
 They range from <h1> (the highest level) to <h6> (the lowest level).
8. <h1>Welcome to MassCoders</h1>
9. <h2>Subscribe to Dodagatta Nihar</h2>
10. <h3>Follow me on Instagram at @niihaaarrrr</h3>
11.
12. Paragraphs (p):
 <p> tags are used to define paragraphs of text.
13. <p>Welcome to MassCoders. Subscribe to Dodagatta Nihar and
stay updated.</p>
14. <p>Don't forget to follow me on Instagram at <a
href="<https://www.instagram.com/niihaaarrrr>">@niihaaarrrr</a>
.</p>
15.
16. Links (a):
 <a> tags are used to create hyperlinks to other web pages or resources.
17. <a href="<https://www.youtube.com/@niharrdg>">Subscribe to
Dodagatta Nihar</a>
18. <a href="<https://www.instagram.com/niihaaarrrr>">Follow me
on Instagram at @niihaaarrrr</a>
19.
20. Images (img):
 <img> is used to display images on a webpage.
21. <img
src="<https://res.cloudinary.com/nihars3/image/upload/v16845953
35/DP-modified_vhu4ws.png>" alt="Dodagatta Nihar">
22.
23. Divisions (div):
 <div> is a generic container used to group elements together for
styling or scripting purposes.
24. <div>
25. <p>Welcome to MassCoders</p>
26. <p>Subscribe to Dodagatta Nihar</p>
27. <p>Follow me on Instagram at @niihaaarrrr</p>
28. </div>
29.
30. Bold and Italic (b and i):
 <b> is used for bold text, and <i> is used for italic text.
31. <p>This is <b>bold</b> text and <i>italic</i> text.</p>
32.

HTML Tags without Closing Tags (Examples)

33. Line Break (br):


 <br> is used to create a line break within text.
34. <p>This text<br>has a line break.</p>
35.
36. Horizontal Rule (hr):
 <hr> is used to create a horizontal line or divider.
37. <p>Some content above<hr>and below the line.</p>
38.

Inka chaala HTML Tags untay mowa! Avasaranni batti mana Google
thalli ni adigi vaadukodame.

Attempt Quiz → Click Here

Assignment Question:

Create a webpage that incorporates the HTML topics you've learned so far. Highlight
specific HTML tags and create elements that link to my YouTube channel
(https://youtube.com/@niharrdg) and my Instagram page
(https://instagram.com/niihaaarrrr). Use creative design and make the best use of CSS
to enhance the visual appeal of your webpage.
Congrats Mowa Successful ga complete chesnav! Next session lo
kaluddam :)

 HTML Lists and Tables

Watch Tutorial → Click Here

Hellooooo mowa brooos! Eeroj manam HTML Lists and Tables pakkaki oka look
eseddam :)

HTML Lists

HTML lists are used to present information in a structured and organized manner.
There are three types of lists in HTML: ordered lists, unordered lists, and definition
lists. Each type of list has its own purpose and can be customized using CSS
properties.

0. Ordered Lists (<ol>): Ordered lists are used when the order of the items is
significant. Each list item is preceded by a number or another marker,
typically starting from 1 and incrementing sequentially.
1. <ol>
2. <li>Item 1</li>
3. <li>Item 2</li>
4. <li>Item 3</li>
5. </ol>
6.

Common list style properties for ordered lists:

 type: Specifies the numbering style. Default is "decimal," but you can
use "lower-alpha," "upper-alpha," "lower-roman," "upper-roman," etc.
 <ol type="I">
 <li>Item 1</li>
 <li>Item 2</li>
 <li>Item 3</li>
 </ol>

 start: Allows you to start the numbering from a specific value.
 <ol start="5">
 <li>Item 5</li>
 <li>Item 6</li>
 <li>Item 7</li>
 </ol>

7. Unordered Lists (<ul>): Unordered lists are used when the order of items
doesn't matter. Each list item is typically preceded by a bullet point or another
marker.
8. <ul>
9. <li>Item A</li>
10. <li>Item B</li>
11. <li>Item C</li>
12. </ul>
13.
Common list style properties for unordered lists:

 type: Specifies the marker style. Default is "disc," but you can use
"circle," "square," or define custom markers using CSS.
 <ul style="list-style-type: square;">
 <li>Item X</li>
 <li>Item Y</li>
 <li>Item Z</li>
 </ul>

14. Definition Lists (<dl>) (Idi ekkuva vaadam ankondi practical ga, ina
parle okasari look ithe eseyyandi): Definition lists are used to define terms
and their corresponding definitions. They consist of term (<dt>) and definition
(<dd>) pairs.
15. <dl>
16. <dt>Term 1</dt>
17. <dd>Definition 1</dd>
18. <dt>Term 2</dt>
19. <dd>Definition 2</dd>
20. </dl>
21.

Common list style properties for definition lists:

 compact: Specifies whether the list should be displayed with reduced


spacing. This is a Boolean attribute.
 <dl compact>
 <dt>Term A</dt>
 <dd>Definition A</dd>
 <dt>Term B</dt>
 <dd>Definition B</dd>
 </dl>

CSS Properties for List Styling: You can further style your lists using CSS. Here are
some common CSS properties for customizing lists:

22. list-style-type: Specifies the type of marker or numbering. Values include


"disc," "circle," "square," "decimal," "lower-roman," "upper-roman," "lower-
alpha," "upper-alpha," and more.
23. list-style-image: Allows you to use a custom image as a marker for list
items. For example:
24. ul {
25. list-style-image: url('bullet.png');
26. }
27.
28. list-style-position: Controls the position of the marker or numbering
relative to the list item. Values can be "inside" or "outside."
29. ul {
30. list-style-position: outside;
31. }
32.
These CSS properties provide flexibility in customizing the appearance of lists to
match your website's design.

HTML Tables

HTML tables are used to display data in a structured grid format, with rows and
columns. Tables consist of various components, including the table itself, rows,
headers, and data cells. Here's an explanation of HTML tables with code snippets:

Creating a Basic Table: To create a basic HTML table, you'll use the <table>
element to define the table structure. Within the table, you use <tr> elements to
define rows, <th> elements for table headers (optional), and <td> elements for data
cells.

<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Dodagatta Nihar</td>
<td>19</td>
</tr>
</table>

Table Headers (<th>): You can use <th> elements to define table headers. These
headers are typically bold and centered by default. They help describe the content of
the columns.

<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Peru teliyani Ammai</td>
<td>19</td>
</tr>
<!-- More rows... -->
</table>

Ee kinda unna examples ni meeru kuda VS Code lo try out chesi chudandi :)

Table Captions (<caption>): You can add a caption to your table using the
<caption> element. The caption is typically placed above the table.

<table>
<caption>Student Information</caption>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Emily</td>
<td>22</td>
</tr>
<!-- More rows... -->
</table>

Table Borders and Styling: You can use CSS to style tables, including adding borders,
changing fonts, and applying background colors. Here's an example of adding a
border to a table:

<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ccc;
padding: 8px;
text-align: left;
}
</style>

<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Michael</td>
<td>30</td>
</tr>
<!-- More rows... -->
</table>

Spanning Rows and Columns: You can use the rowspan and colspan attributes to
make cells span multiple rows or columns.

<table>
<tr>
<th>Name</th>
<th>Details</th>
</tr>
<tr>
<td rowspan="2">John</td>
<td>Age: 25</td>
</tr>
<tr>
<td>Country: USA</td>
</tr>
<!-- More rows... -->
</table>

HTML tables are versatile and allow you to present data in various formats, from
simple grids to complex data tables. You can further enhance their appearance and
functionality using CSS and JavaScript if needed.
Attempt Quiz → Click Here

Assignment Question:

Design elegant HTML lists and tables, enhancing their visual appeal with CSS
styling.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 HTML Forms

Watch Tutorial → Click Here

Andarki namaste! User nundi input collect cheskodaniki manam HTML Forms
vaadtam. Daaniki sambandinchi coding ithe manam eeroj session lo cheseddam.

HTML Forms

HTML forms are a fundamental part of web development, allowing users to input data
and interact with a web page. Forms are used for various purposes, such as user
registration, login, search, and data submission. Below, I'll explain the key
components of an HTML form with a simple example.

<!DOCTYPE html>
<html>
<head>
<title>Sample Form</title>
</head>
<body>
<h1>Welcome to MassCoders! Please enter your details.</h1>
<form action="process_form.php" method="POST">
<!-- Text Input -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>

<!-- Email Input -->


<label for="email">Email:</label>
<input type="email" id="email" name="email" required>

<!-- Radio Buttons -->


<p>Gender:</p>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>

<!-- Checkboxes -->


<p>Interests:</p>
<input type="checkbox" id="coding" name="interests[]"
value="coding">
<label for="coding">Coding</label>
<input type="checkbox" id="music" name="interests[]"
value="music">
<label for="music">Music</label>
<!-- Select Dropdown -->
<label for="country">Country:</label>
<select id="country" name="country">
<option value="us">India</option>
<option value="ca">Canada</option>
<option value="uk">United Kingdom</option>
</select>

<!-- Textarea -->


<label for="message">Message:</label>
<textarea id="message" name="message" rows="4"
cols="50"></textarea>

<!-- Submit Button -->


<input type="submit" value="Submit">
</form>
</body>
</html>

Explanation:

0. <!DOCTYPE html>: This declaration specifies that the document is an HTML5


document.
1. <html>: The root element of the HTML document.
2. <head>: Contains metadata about the document, such as the title that appears
in the browser tab.
3. <title>: Sets the title of the web page.
4. <body>: The main content of the web page goes within the body element.
5. <form>: The form element is used to create an HTML form. It has two
essential attributes:
 action: Specifies the URL to which the form data will be sent when
the user submits the form.
 method: Defines the HTTP method used to send the data, typically
POST or GET.
6. <label>: Labels are used to provide a text description for form elements.
They are associated with form controls using the for attribute.
7. <input>: This element is used for various types of input fields like text, email,
radio buttons, and checkboxes. The type attribute specifies the input field
type, and the name attribute is used to identify the field when the form is
submitted.
8. Radio buttons (type="radio") and checkboxes (type="checkbox") are used
for selecting one or multiple options, respectively.
9. <select>: The select element creates a dropdown list with options specified
using the <option> elements.
10. <textarea>: Textareas allow users to enter multiline text. You can set the
number of rows and columns with the rows and cols attributes.
11. <input type="submit">: This input element is a submit button. When
clicked, it triggers the form submission to the URL specified in the action
attribute.
This is a basic example of an HTML form. When a user fills out the form and clicks
the "Submit" button, the data is sent to the server for processing. The server-side
script specified in the action attribute (e.g., "process_form.php") would handle the
form data. Note: Ee php gurinchi ippude em thala chedupkokandi, ivanni yenakamala
jarige panulu, malli chuddam veeti gurinchi.

Attempt Quiz → Click Here

Assignment Question:

Your assignment is to construct an HTML registration form for students wishing to


enroll in the MassCoders community. Make certain that the form encompasses all the
subject matter addressed in this session and apply CSS to elevate its visual appeal.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Internal, External and Inline CSS

Watch Tutorial → Click Here

CSS (Cascading Style Sheets) is a styling language used to control the visual
presentation of web content. There are three main ways to include CSS in your web
pages: internal, external, and inline CSS. Here are notes and examples for each:

Internal CSS:

Internal CSS is defined within the <style> element in the HTML document's <head>
section. It applies styles to a single HTML page.

<!DOCTYPE html>
<html>
<head>
<style>
/* Internal CSS */
h1 {
color: blue;
}
p {
font-size: 16px;
}
</style>
</head>
<body>
<h1>Welcome to MassCoders</h1>
<p>Subscribe to my YouTube channel</p>
</body>
</html>

External CSS:
External CSS is defined in a separate .css file and then linked to the HTML
document using the <link> element. This allows you to apply the same styles across
multiple pages.

/* External CSS (style.css) */


h1 {
color: blue;
}
p {
font-size: 16px;
}

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Welcome to MassCoders</h1>
<p>Subscribe to my YouTube channel</p>
</body>
</html>

Inline CSS:

Inline CSS is defined directly within the HTML elements using the style attribute.
It's typically used for individual elements.

<!DOCTYPE html>
<html>
<body>
<h1 style="color: blue;">Welcome to MassCoders</h1>
<p style="font-size: 16px;">Subscribe to my YouTube channel</p>
</body>
</html>

In summary, the choice between internal, external, and inline CSS depends on the
scale and complexity of your project. Internal CSS is good for small-scale projects,
external CSS is ideal for larger projects with consistent styles, and inline CSS is
useful for quick and specific styling needs.

Attempt Quiz → Click Here

Assignment Question:

Create a basic web page that includes elements such as h1, p, div, and button tags, and
incorporate inline, internal, and external CSS to style the page.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 CSS Fonts
Watch Tutorial → Click Here

CSS Fonts:
CSS (Cascading Style Sheets) allows you to control the fonts used on your webpages.
You can define fonts for various HTML elements using CSS properties.

Font Properties:

0. font-family: Specifies the font for an element. You can specify multiple fonts
as a fallback, separated by commas. The browser will use the first available
font.
1. font-family: Arial, Helvetica, sans-serif;
2.
3. font-size: Sets the size of the font. You can use different units such as pixels
(px), ems (em), or percentages (%).
4. font-size: 16px;
5.
6. font-weight: Determines the thickness or boldness of the font. Common
values include normal, bold, bolder, and numeric values from 100 to 900.
7. font-weight: bold;
8.
9. font-style: Defines the style of the font, which can be normal, italic, or
oblique.
10. font-style: italic;
11.
12. text-transform: Changes the capitalization of the text. Options include
uppercase, lowercase, and capitalize.
13. text-transform: uppercase;
14.
15. text-decoration: Adds decorations to text, like underlines or strikethrough.
Options include underline, overline, line-through.
16. text-decoration: underline;
17.
18. line-height: Sets the vertical space between lines of text. It can be defined as a
number or a unit like em or px.
19. line-height: 1.5;
20.
21. letter-spacing: Adjusts the space between characters in the text.
22. letter-spacing: 2px;
23.
24. color: Specifies the text color using various formats like color names,
hexadecimal, or RGB values.
25. color: #333;
26.

Using Google Fonts:


Google Fonts is a service that provides a wide selection of web fonts for free. You can
easily incorporate these fonts into your web projects.

27. Visit Google Fonts: Go to the Google Fonts website.


28. Browse and Select Fonts: Browse through the font library, search for specific
fonts, and select the ones you want to use.
29. Add Fonts to Collection: Click the "+" button next to the fonts you want to
use to add them to your collection.
30. Customize: You can customize font weights and styles for each font in your
collection.
31. Get the Code: Click the "Embed" tab, and you'll find the HTML and CSS
code to include in your project.

For example:

<link rel="stylesheet"
href="<https://fonts.googleapis.com/css?family=Font+Name>">

And in your CSS:

body {
font-family: 'Font Name', sans-serif;
}

32. Apply Fonts: Use the defined font in your CSS as needed for different
elements.

Google Fonts is a convenient way to enhance the typography of your web projects
with a wide range of fonts, and it ensures that the fonts are available across various
browsers.

Attempt Quiz → Click Here

Assignment Question:

Create a webpage that utilizes the font properties explained in this session to style text
elements. Apply different font families, sizes, weights, styles, and text
transformations to enhance the typography on your webpage. Additionally,
experiment with text decorations, line spacing, letter spacing, and text colors to create
an aesthetically pleasing and well-designed webpage.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 CSS Box Model

Watch Tutorial → Click Here

CSS Box Model

The CSS Box Model is a fundamental concept in web design and layout. It defines
how elements are rendered on a web page by breaking down each element into four
parts: content, padding, border, and margin. These components affect the layout and
spacing of elements on a webpage. Let's explore each component with detailed
explanations and examples.

Content:

o The content area represents the actual content of the HTML element (e.g., text,
images, or other media).
o The width and height of an element are determined by its content area.

.box {
width: 200px;
height: 100px;
background-color: lightblue;
}

<div class="box">This is the content</div>

Padding:

o Padding is the space between the content and the element's border.
o You can set padding for individual sides (top, right, bottom, left) or all sides at
once.

.box {
padding: 20px;
background-color: lightblue;
}

<div class="box">This is the content</div>

Border:

o The border surrounds the padding and content of an element.


o You can specify the border width, style, and color.
o The border property can be shorthand or you can set border properties
individually.

.box {
padding: 20px;
border: 2px solid black;
background-color: lightblue;
}

<div class="box">This is the content</div>

Margin:

o The margin is the space outside the border and separates the element from
other elements on the page.
o You can set margins for individual sides or all sides at once.
o Margins can be used to control spacing between elements.

.box {
padding: 20px;
border: 2px solid black;
margin: 10px;
background-color: lightblue;
}

<div class="box">This is the content</div>

Here are some additional examples to demonstrate the box model:

o Adjusting padding on specific sides:

.box {
padding-top: 10px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 40px;
background-color: lightblue;
}

o Using margin to create spacing between elements:

.box1 {
margin: 10px;
background-color: lightblue;
}

.box2 {
margin: 10px;
background-color: lightcoral;
}

<div class="box1">Box 1</div>


<div class="box2">Box 2</div>

Border Properties

In CSS, there are several properties that allow you to control the appearance and
behavior of borders around HTML elements. These properties provide you with the
flexibility to style borders in various ways. Here are some of the most commonly used
border properties in CSS:

12. border-width:
 Specifies the width of the border.
 You can set the width individually for each side (top, right, bottom,
left) or use the shorthand property to set all sides at once.
13. .box {
14. border-width: 2px; /* All sides */
15. border-top-width: 1px; /* Top side */
16. }
17.
18. border-style:
 Defines the style of the border, such as solid, dashed, dotted, double,
etc.
19. .box {
20. border-style: solid;
21. }
22.
23. border-color:
 Sets the color of the border.
24. .box {
25. border-color: red;
26. }
27.
28. border (shorthand):
 Combines the border-width, border-style, and border-color
properties into a single property for convenience.
29. .box {
30. border: 2px solid red;
31. }
32.
33. border-radius:
 Defines rounded corners for an element's border.
 You can set the radius for each corner individually or as a single value
for all corners.
34. .box {
35. border-radius: 10px; /* All corners */
36. border-top-left-radius: 5px; /* Top-left corner */
37. }
38.
39. border-image:
 Allows you to use an image as a border, creating more complex border
styles.
 You can specify the image source, slice, width, outset, and repeat
values.
40. .box {
41. border-image: url(border.png) 10 10 round;
42. }
43.

CSS provides several properties to control the display and visibility of elements on a
web page. These properties allow you to show or hide elements and determine how
they are rendered within the document flow. Let's explore the display and
visibility properties with code examples.

Display Property:

The display property controls how an element is displayed in terms of its layout and
rendering. Common values include:

block: Elements are displayed as block-level elements, taking up the entire width of
their parent container.

.block {
display: block;
width: 200px;
height: 50px;
background-color: lightblue;
}

<div class="block">Block Element</div>

inline: Elements are displayed inline, taking up only as much width as necessary.

.inline {
display: inline;
background-color: lightcoral;
}

<span class="inline">Inline Element</span>

inline-block: Combines properties of both block and inline elements, allowing you
to set width, height, and maintain inline behavior.

.inline-block {
display: inline-block;
width: 100px;
height: 100px;
background-color: lightgreen;
}

<div class="inline-block">Inline Block Element</div>

none: The element is not displayed, and it doesn't occupy any space within the layout.

.none {
display: none;
}

<div class="none">This element is hidden.</div>

Display: Flex

The display: flex property is used to create flexible, one-dimensional layouts. It


allows you to distribute space within a container, align elements, and create
responsive designs. Here's an example:

<!DOCTYPE html>
<html>
<head>
<style>
.flex-container {
display: flex;
justify-content: space-between;
}

.flex-item {
width: 100px;
height: 100px;
background-color: lightblue;
}
</style>
</head>
<body>
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>
</body>
</html>

In this example, the display: flex property is applied to the .flex-container, and
justify-content: space-between is used to evenly distribute space between the
child elements.

Display: Grid

The display: grid property allows you to create two-dimensional grid layouts. You
can define rows and columns and place elements within the grid cells. Here's an
example:

<!DOCTYPE html>
<html>
<head>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 10px;
}

.grid-item {
width: 100px;
height: 100px;
background-color: lightgreen;
}
</style>
</head>
<body>
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
</div>
</body>
</html>
In this example, the display: grid property is applied to the .grid-container, and
grid-template-columns is used to define a 3-column grid. grid-gap specifies the
gap between grid items.

Both display: flex and display: grid provide powerful layout capabilities, and
choosing one depends on your specific design requirements. Flexbox is great for one-
dimensional layouts, while grid is ideal for creating two-dimensional grid structures.
You can also combine these layout models for even more advanced layouts.

Visibility Property:

The visibility property controls the visibility of an element while still preserving
its space in the layout. Common values include:

visible: The element is visible.

.visible {
visibility: visible;
background-color: lightblue;
}

<div class="visible">Visible Element</div>

hidden: The element is not visible but still occupies space.

.hidden {
visibility: hidden;
background-color: lightcoral;
}

<div class="hidden">Hidden Element</div>

Attempt Quiz → Click Here

Assignment Question:

Design a compact webpage showcasing your preferred theme using HTML and CSS,
highlighting the practical application of the CSS Box Model, as well as the utilization
of the Display and Visibility properties.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 CSS Positioning

Watch Tutorial → Click Here

CSS Positioning
CSS (Cascading Style Sheets) positioning allows you to control the placement of
HTML elements on a web page. There are several types of positioning in CSS,
including:

Static Positioning: This is the default positioning for all HTML elements. Elements
with static positioning are placed in the normal flow of the document. You don't need
to use any special CSS properties to create static positioning. Here's an example:

<!DOCTYPE html>
<html>
<head>
<style>
.static-box {
/* Default static positioning */
}
</style>
</head>
<body>
<div class="static-box">Static Positioning</div>
</body>
</html>

Relative Positioning: Elements with relative positioning are positioned relative to


their normal position in the document flow. You can use the position: relative
property to create relative positioning and adjust the element's position using top,
right, bottom, and left properties. Here's an example:

<!DOCTYPE html>
<html>
<head>
<style>
.relative-box {
position: relative;
top: 20px;
left: 30px;
}
</style>
</head>
<body>
<div class="relative-box">Relative Positioning</div>
</body>
</html>

Absolute Positioning: Elements with absolute positioning are removed from the
normal document flow and are positioned relative to their closest positioned ancestor.
You can use the position: absolute property and adjust the position using top,
right, bottom, and left. Here's an example:

<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
}
.absolute-box {
position: absolute;
top: 50px;
left: 50px;
}
</style>
</head>
<body>
<div class="container">
<div class="absolute-box">Absolute Positioning</div>
</div>
</body>
</html>

Fixed Positioning: Elements with fixed positioning are removed from the normal
document flow and are positioned relative to the viewport. You can use the
position: fixed property to create fixed positioning. Here's an example:

<!DOCTYPE html>
<html>
<head>
<style>
.fixed-box {
position: fixed;
top: 10px;
right: 10px;
}
</style>
</head>
<body>
<div class="fixed-box">Fixed Positioning</div>
</body>
</html>

Sticky Positioning: Elements with sticky positioning are initially positioned according
to the normal flow, but become fixed or relative to their containing block based on the
user's scroll position. You can use the position: sticky property. Here's an
example:

<!DOCTYPE html>
<html>
<head>
<style>
.sticky-box {
position: sticky;
top: 10px;
}
</style>
</head>
<body>
<div class="sticky-box">Sticky Positioning</div>
<!-- Content that causes scrolling -->
</body>
</html>
Attempt Quiz → Click Here

Assignment Question:

Create a simple webpage with the following elements positioned using CSS: A
navigation bar at the top, a main content area, and a footer at the bottom. The header
and footer should be fixed in position, while the navigation bar and main content
should be relatively positioned.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Build your Portfolio website

Watch Tutorial → Click Here

Check out the code below.

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="navbar">
<div class="navbar-left">
<img class="logo-image"
src="<https://res.cloudinary.com/nihars3/image/upload/v1695711604/oie
_4tJfBuZmsuYT_eafcem.png>" alt="logo">
</div>
<div class="navbar-right">
<a class="a-element">Home</a>
<a class="a-element">About</a>
<a class="a-element" href="#services">Services</a>
<a class="a-element">Contact</a>
</div>
</div>
<div class="home">
<div class="home-left">
<h1 class="home-h1">Dodagatta Nihar</h1>
<p class="home-p">Hello, I'm Nihar, a passionate
Bachelor's degree candidate in Artificial Intelligence at the
University of Visvesvaraya College of Engineering in Bengaluru. With
a strong background in web development and a robust portfolio of over
50 websites, I have honed my skills in creating dynamic and visually
appealing online experiences. Proficient in Python, I am adept at
leveraging its power for efficient and scalable solutions.</p>
</div>
<div class="home-right">
<img
src="<https://res.cloudinary.com/nihars3/image/upload/v1684595335/DP-
modified_vhu4ws.png>" alt="my logo">
</div>
</div>
<div class="services" id="services">
<h1 class="ser-h1">SERVICES WE OFFER</h1>
<div class="services-sub-cont">
<div class="services-card">
<h1 class="sc-h1">Web Designing</h1>
<p class="sc-p">Nenu manchi manchi websitelani design
chestha interest unte nanni sampradinchandi.</p>
</div>
<div class="services-card">
<h1 class="sc-h1">Video Editing</h1>
<p class="sc-p">Nenu manchi manchi Videos ni edit
chestha interest unte nanni sampradinchandi.</p>
</div>
<div class="services-card">
<h1 class="sc-h1">Photoshop</h1>
<p class="sc-p">Nenu manchi manchi photolani edit
chestha interest unte nanni sampradinchandi.</p>
</div>
</div>
</div>
<div class="services">
<h1 class="ser-h1">TESTIMONIALS</h1>
<div class="services-sub-cont">
<div class="services-card">
<h1 class="sc-h1">Google</h1>
<img src="<https://static-
00.iconduck.com/assets.00/google-icon-2048x2048-czn3g8x8.png>"
class="test-logo">
<p class="sc-p">Nihar manchi manchi websites naaku
design chesichadu. Pani twaraga chesthadu.</p>
</div>
<div class="services-card">
<h1 class="sc-h1">Facebook</h1>
<img src="<https://static-
00.iconduck.com/assets.00/facebook-icon-2048x2048-pth4zu2i.png>"
class="test-logo">
<p class="sc-p">Nenu manchi manchi Videos ni edit
chestha interest unte nanni sampradinchandi.</p>
</div>
<div class="services-card">
<h1 class="sc-h1">Instagram</h1>
<img src="<https://cdn-icons-
png.flaticon.com/512/1384/1384063.png>" class="test-logo">
<p class="sc-p">Nenu manchi manchi photolani edit
chestha interest unte nanni sampradinchandi.</p>
</div>
</div>
</div>
<div class="contact">
<h1 class="ser-h1">CONTACT US</h1>
<div class="contact-info">
<p>Dodagatta Nihar</p>
<p>+91 1234567890</p>
<p>[email protected]</p>
</div>
<div class="social-icons">
<div class="social-icon">
<a href="<https://www.instagram.com/niihaaarrrr/>">
<img
src="<https://upload.wikimedia.org/wikipedia/commons/thumb/5/58/Insta
gram-Icon.png/1024px-Instagram-Icon.png>" class="social-icon-img">
</a>
<a href="<https://www.youtube.com/@niharrdg>">
<img
src="<https://www.iconpacks.net/icons/2/free-youtube-logo-icon-2431-
thumb.png>" class="social-icon-img">
</a>
<a href="<https://www.linkedin.com/in/niharrdg>">
<img src="<https://cdn-icons-
png.flaticon.com/512/174/174857.png>" class="social-icon-img">
</a>
</div>
</div>
</div>
</body>
</html>

style.css:

@import
url('<https://fonts.googleapis.com/css2?family=Encode+Sans&family=Fir
a+Code&family=Fuggles&family=Montserrat:ital,wght@1,600&family=Mooli&
family=Ubuntu:ital,wght@1,500&display=swap>');@import
url('<https://fonts.googleapis.com/css2?family=Encode+Sans&family=Fir
a+Code&family=Fuggles&family=Montserrat:wght@200&family=Mooli&family=
Ubuntu:ital,wght@1,500&display=swap>');
body {
margin: 0;
background-color: black;
color: white;
}
.navbar {
display: flex;
flex-direction: row;
justify-content: space-between;
background-color: black;
}
.navbar-left {
padding-left: 50px;
}
.logo-image {
height: 100px;
}
.navbar-right {
padding-right: 20px;
display: flex;
flex-direction: row;
align-items:center;
}
.a-element {
padding: 10px;
margin: 10px;
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe
UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica
Neue', sans-serif;
font-size: 20px;
font-weight: bold;
}
.home {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
height: 85vh;
}
.home-left {
width: 50vw;
text-align: right;
padding-left: 200px;
}
.home-right {
width: 50vw;
padding-left: 100px;
}
.home-h1 {
font-family: 'Montserrat', sans-serif;
font-size: 25px;
}
.home-p {
font-family: 'Encode Sans', sans-serif;
font-size: 20px;
}
.services {
padding: 50px;
text-align: center;
}
.ser-h1 {
font-family: 'Ubuntu', sans-serif;
color: rgb(59, 211, 59);
letter-spacing: 3px;
font-size: 50px;
font-style: italic;
}
.services-sub-cont {
display: flex;
flex-direction: row;

}
.services-card {
border: 2px rgb(47, 168, 47) solid;
margin: 20px;
padding: 20px;
width: 400px;
}
.sc-h1 {
font-family: 'Montserrat', sans-serif;
font-size: 25px;
}
.sc-p {
font-family: 'Encode Sans', sans-serif;
font-size: 20px;
}
.contact {
text-align: center;
}
.contact-info {
font-family: 'Montserrat', sans-serif;
font-size: 25px;
}
.test-logo {
height: 50px;
}
.social-icon-img {
height: 50px;
padding: 20px;
}

Assignment Question:

Create a personal portfolio website incorporating the concepts we've covered so far,
and then share the screenshots or a screen recording of it with @mass_coders on
Instagram. I will review it personally and let you know what all improvements can be
made.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Introduction to Bootstrap

Watch Tutorial → Click Here

Introduction to Bootstrap

Bootstrap is a popular front-end framework for building responsive and visually


appealing web applications. It provides a set of pre-designed CSS styles, JavaScript
components, and a responsive grid system to help you create a well-designed website
or web application quickly. Here's an introduction to Bootstrap with code examples
covering topics like including Bootstrap in your code, creating a navbar, buttons, a
carousel, and cards.

Including Bootstrap in Your Code

To get started with Bootstrap, you need to include its CSS and JavaScript files in your
HTML document. You can either download the Bootstrap files and host them on your
server, or you can link to the Bootstrap CDN (Content Delivery Network) for a
quicker setup. Here's how to include Bootstrap via CDN:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<title>Bootstrap demo</title>
<link
href="<https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstra
p.min.css>" rel="stylesheet" integrity="sha384-
T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
crossorigin="anonymous">
</head>
<body>
<h1>Hello, world!</h1>
<script
src="<https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.
bundle.min.js>" integrity="sha384-
C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
</body>
</html>

Navbar

A Bootstrap navbar is a navigation bar that can be easily created using Bootstrap's
navigation components. Here's an example of a simple navbar:

<nav class="navbar navbar-expand-lg bg-body-tertiary">


<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-
toggle="collapse" data-bs-target="#navbarNav" aria-
controls="navbarNav" aria-expanded="false" aria-label="Toggle
navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page"
href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" aria-
disabled="true">Disabled</a>
</li>
</ul>
</div>
</div>
</nav>

Buttons

Bootstrap provides various button styles and sizes. Here's how to create different
types of buttons:

<button class="btn btn-primary">Primary Button</button>


<button class="btn btn-secondary">Secondary Button</button>
<button class="btn btn-success">Success Button</button>
<button class="btn btn-danger">Danger Button</button>
<button class="btn btn-warning">Warning Button</button>
<button class="btn btn-info">Info Button</button>
<button class="btn btn-light">Light Button</button>
<button class="btn btn-dark">Dark Button</button>

Carousel

A Bootstrap carousel is used to showcase a set of images or content in a sliding


manner. Here's a basic example of a Bootstrap carousel:

<div id="carouselExample" class="carousel slide">


<div class="carousel-inner">
<div class="carousel-item active">
<img src="..." class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="..." class="d-block w-100" alt="...">
</div>
<div class="carousel-item">
<img src="..." class="d-block w-100" alt="...">
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-
target="#carouselExample" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-
hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-
target="#carouselExample" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-
hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>

Cards

Bootstrap cards are versatile components for displaying various types of content.
Here's an example of a Bootstrap card:

<div class="card" style="width: 18rem;">


<img src="..." class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card
title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
</div>

These are just the basics of Bootstrap. Bootstrap offers a wide range of components
and utility classes to make your web development process faster and more responsive.
You can explore the Bootstrap documentation for more details and customization
options: https://getbootstrap.com/
Attempt Quiz → Click Here

Assignment Question:

Make a small website of your theme using the topics covered today.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Build your own website using Bootstrap

Refer to Bootstrap Documentation at: getbootstrap.com

Watch Tutorial → Click Here

Code: index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>MassCoders</title>
<link rel="stylesheet" href="./massstyle.css" type="text/css">
<link rel="icon"
href="<https://res.cloudinary.com/nihars3/image/upload/v1695711604/oi
e_4tJfBuZmsuYT_eafcem.png>" type="image/x-icon">
<link
href="<https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstra
p.min.css>" rel="stylesheet" integrity="sha384-
T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
crossorigin="anonymous">
<script
src="<https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.
min.js>" integrity="sha384-
BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+"
crossorigin="anonymous"></script>
<script
src="<https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.
bundle.min.js>" integrity="sha384-
C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
</head>
<body>
<div class="mass-body">
<div class="navbar-section">
<nav class="navbar navbar-expand-lg">
<div class="container-fluid mass-nav pl-5 pr-5">
<img
src="<https://res.cloudinary.com/nihars3/image/upload/v1695711604/oie
_4tJfBuZmsuYT_eafcem.png>" class="mass-logo">
<button class="navbar-toggler d-none" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-
controls="navbarNavAltMarkup" aria-expanded="false" aria-
label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse"
id="navbarNavAltMarkup">
<div class="navbar-nav anchor">
<a class="nav-link mass-anchor"
href="#about">About</a>
<a class="nav-link mass-anchor"
href="#courses">Courses</a>
<a class="nav-link mass-anchor"
href="#workshops">Workshops</a>
<a class="nav-link mass-anchor"
href="#contact">Contact</a>
</div>
</div>
</div>
</nav>
</div>
<div class="body-section">
<div class="container-fluid">
<div class="row d-flex flex-row justify-content-
center">
<!-- Left Half - Information About Me -->
<div class="col-12 order-1 order-md-1 col-md-6
left-body">
<h1 class="mass-nihar">DODAGATTA <span
style="color: rgb(57, 211, 57);">NIHAR</span></h1>
<p class="mass-nihar-para">I'm Nihar, a
versatile tech enthusiast with a strong commitment to knowledge
sharing and innovation. I wear multiple hats as a YouTuber and
Instagram tech influencer, where I focus on teaching coding, MERN
Stack development, and engaging in in-depth discussions about the
ever-evolving tech landscape. My genuine love for AI adds an extra
layer of excitement to my tech journey. I'm always eager to connect
with fellow tech enthusiasts, creators, and professionals who share
my passion for technology, learning, and growth.</p>
</div>
<!-- Right Half - My Photo -->
<div class="col-12 order-0 order-md-2 col-md-4">
<img
src="<https://res.cloudinary.com/nihars3/image/upload/v1698579978/tem
pImagewwyH9B-modified_kzi10d.png>" alt="Dodagatta Nihar" class="img-
fluid">
</div>
</div>
</div>
</div>
<div class="what-we-do pt-5" id="about">
<div class="container">
<h2 class="about-h1">about <span style="color:
rgb(57, 211, 57);">us</span></h2>
<p class="about-p">MassCoders, founded by Dodagatta
Nihar in July 2023, is a visionary community with a mission to
empower and inspire the youth to explore the world of coding. Our
motto, "Motivating youth to code," encapsulates our dedication to
making coding accessible and engaging for all, especially in native
languages such as Telugu and expanding to Kannada.
</p>
</div>
</div>
<div class="what-we-do" id="whatwedo">
<div class="container">
<h2 class="about-h1">what we <span style="color:
rgb(57, 211, 57);">do</span>?</h2>
<p class="about-p">We specialize in providing coding
tutorials in native languages, starting with Telugu, and extending
our reach to Kannada. At MassCoders, we believe that learning to code
should be inclusive and easy to understand, regardless of one's
linguistic background.
</p>
</div>
</div>
<div class="courses-offered" id="courses">
<div class="container">
<h2 class="text-center about-h1">courses <span
style="color: rgb(57, 211, 57);">offered</span></h2>
<div class="row">
<!-- Course 1 -->
<div class="col-12 col-md-6">
<div class="course-card">
<a
href="<https://youtu.be/Ywfuw4SUDv8?si=cAAYSrz3RX4ONouu>"
style="text-decoration: none;">
<div>
<img
src="<https://res.cloudinary.com/nihars3/image/upload/v1696239218/Web
_Development_with_MERN-2_wdcl1r.png>" alt="Course 1">
<h3 class="course-title">Web
development with <span style="color: rgb(57, 211,
57);">MERN</span></h3>
<p class="course-p">In my
specialized web development course, I offer comprehensive tutorials
in the Telugu language, focusing on the MERN (MongoDB, Express.js,
React, Node.js) stack. With a deep commitment to clarity, I provide
detailed explanations of every topic covered. You'll find in-depth
notes accompanying the tutorials, serving as a valuable resource for
your learning journey. To reinforce your understanding, I've included
quizzes and practice questions to help you apply your knowledge
effectively. Whether you're a beginner or an aspiring developer
looking to enhance your skills, this course is designed to empower
you with the tools and expertise you need for success in web
development.
</p>
</div>
</a>
</div>
</div>
<!-- Course 2 -->
<div class="col-12 col-md-6">
<div class="course-card">
<a
href="<https://www.instagram.com/p/CvM4jVBp8F3/>" style="text-
decoration: none;">
<div>
<img
src="<https://res.cloudinary.com/nihars3/image/upload/v1696239443/Cop
y_of_Web_Development_with_MERN_eclmlb.png>" alt="Course 2">
<h3 class="course-title">Python
on <span style="color: rgb(57, 211, 57);">IG Reels</span></h3>
<p class="course-p">In my
Instagram Reels Python course taught in Telugu, I'll help you learn
Python easily. I provide clear and concise notes that explain the
basics of Python step by step. To make sure you really understand, I
include lots of practice questions that will help you get better at
solving problems. Whether you're a beginner or someone who wants to
get better at Python, this course is designed to help you. You'll
gain practical skills that will make you confident in Python
programming.</p>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="workshops" id="workshops">
<div class="container">
<h2 class="text-center about-h1">access<span
style="color: rgb(57, 211, 57);"> notes</span></h2>
<a class="d-flex flex-row justify-content-center
link-span" target="_blank"
href="<https://masscoders.notion.site/masscoders/Web-Development-
with-MERN-eba16384715f473b95f25ab1ea050bc0>">
<div class="text-center">
<img class="course-logo" src="<https://cdn-
icons-png.flaticon.com/512/2210/2210184.png>">
</div>
<p class="pandaga-p text-center">Web
Development</p>
</a>
<a class="d-flex flex-row justify-content-center
link-span" target="_blank"
href="<https://masscoders.notion.site/Muppai-rojullo-Python-
2f54ed7ca67e4d21a52eb60a3927b9e4?pvs=4>"">
<div class="text-center">
<img class="course-logo"
src="<https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Pytho
n-logo-notext.svg/1869px-Python-logo-notext.svg.png>">
</div>
<p class="pandaga-p text-center">Python</p>
</a>
</div>
</div>
<div class="workshops" id="workshops">
<div class="container">
<h2 class="text-center about-h1">work<span
style="color: rgb(57, 211, 57);">shops</span></h2>
<h2 class="text-center" style="font-size:
30px;">coming<span style="color: rgb(57, 211, 57);">
sooooooooon!</span></h2>
</div>
</div>
<div class="contact pb-5" id="contact">
<div class="container text-center">
<h2 class="about-h1">contact<span style="color:
rgb(57, 211, 57);"> us</span></h2>
<p class="about-p">You can reach us via <span
style="color: rgb(57, 211, 57);">email</span> and follow us on <span
style="color: rgb(57, 211, 57);">social media</span>.</p>
<!-- Email -->
<p class="about-p"><strong>Email:</strong> <a
href="mailto:[email protected]" style="color: rgb(57, 211, 57);
text-decoration: none;">[email protected]</a></p>
<!-- Social Media Links -->
<ul class="list-inline">
<li class="list-inline-item">
<a
href="<https://www.instagram.com/niihaaarrrr/>" target="_blank"
rel="noopener noreferrer">
<img
src="<https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/Insta
gram_icon.png/600px-Instagram_icon.png?20200512141346>"
alt="Instagram" class="social-icon">
</a>
</li>
<li class="list-inline-item">
<a
href="<https://www.linkedin.com/in/niharrdg/>" target="_blank"
rel="noopener noreferrer">
<img src="<https://cdn-icons-
png.flaticon.com/512/174/174857.png>" alt="LinkedIn" class="social-
icon">
</a>
</li>
<li class="list-inline-item">
<a href="<https://t.me/masscoders>"
target="_blank" rel="noopener noreferrer">
<img src="<https://static-
00.iconduck.com/assets.00/telegram-icon-2048x2048-l6ni6sux.png>"
alt="Telegram" class="social-icon">
</a>
</li>
</ul>
</div>
</div>

<script
src="<https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/pop
per.min.js>" integrity="sha384-
I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r"
crossorigin="anonymous"></script>
</body>
</html>

massstyle.css:

/* Default styles for all screen sizes */


@import
url('<https://fonts.googleapis.com/css2?family=DM+Sans:[email protected]&fam
ily=Encode+Sans&family=Fira+Code&family=Fuggles&family=Gabarito&famil
y=Montserrat:ital,wght@1,600&family=Mooli&family=Pixelify+Sans:wght@5
00&family=Poppins:wght@300&family=Titillium+Web&family=Ubuntu:ital,wg
ht@1,500&display=swap>');

* {
color: white;
}

.anchor {
margin-left: auto;
}

.mass-logo {
height: 100px;
padding-left: 20px;
}

.mass-anchor {
color: white !important;
padding-right: 20px !important;
font-family: 'Poppins', sans-serif;
}

.mass-anchor:hover {
color: rgb(40, 214, 40) !important;
transform: scale(1.09);
}

.mass-nihar {
font-family: 'Encode Sans', sans-serif;
letter-spacing: 4px;
font-size: 50px;
}

.mass-nihar-para {
font-family: 'Gabarito', cursive;
font-size: 20px;
}

.mass-body {
background-image:
url('<https://res.cloudinary.com/nihars3/image/upload/v1696232927/pho
to-1619429858348-2d5ad1547e6c_nnvynb.jpg>');
background-size: cover;
height: auto;
}

.left-body {
padding-left: 100px !important;
color: white;
padding-top: 40px !important;
}

.body-section {
padding-top: 100px;
text-align: center;
height: 80vh;
}

.link-span {
text-decoration: none !important;
color: rgb(40, 214, 40) !important;
}

.what-we-do {
color: white;
text-align: center;
padding-bottom: 20px;
padding-left: 150px;
padding-right: 150px;
}
.about-h1 {
font-family: 'DM Sans', sans-serif;
font-size: 50px;
}

.about-title {
font-family: 'DM Sans', sans-serif;
font-size: 30px;
}

.course-title {
font-family: 'DM Sans', sans-serif;
font-size: 25px;
padding-top: 20px;
}

.about-p {
font-family: 'Montserrat', sans-serif;
font-size: 25px;
}
.pandaga-p {
font-family: 'Montserrat', sans-serif;
font-size: 25px;
}
.pandaga-p:hover {
color: rgb(40, 214, 40) !important;
}

.course-p {
font-family: 'Montserrat', sans-serif;
font-size: 18px;
max-width: 590px;
}

.course-card {
border: 1px solid #ccc;
transition: all 0.3s;
margin-bottom: 20px;
padding: 20px;
text-align: center;
min-height: 800px;
padding: 10px;
}

.course-card img {
max-width: 100%;
height: auto;
}

.course-card:hover {
border: 2px solid green;
transform: scale(1.05);
}
.course-logo{
height: 40px;
padding-right: 10px;
}

.social-icon {
height: 50px;
padding-right: 20px;
}

/* Responsive styles for mobile devices */


@media screen and (max-width: 768px) {
/* Adjust your styles for mobile devices here */
.mass-logo {
height: 80px;
padding-left: 10px;
}

.mass-anchor {
padding-right: 10px !important;
font-size: 14px;
}

.mass-nihar {
font-size: 40px;
text-align: center;
}

.mass-nihar-para {
font-size: 16px;
text-align: center;
}

.body-section {
padding-top: 50px;
}

.what-we-do {
padding-left: 20px;
padding-right: 20px;
}

.about-h1 {
font-size: 40px;
}

.about-title {
font-size: 24px;
}

.course-title {
font-size: 20px;
}

.about-p {
font-size: 20px;
}

.course-p {
font-size: 16px;
max-width: 100%;
}

.course-card {
min-height: auto;
padding: 10px;
}
.body-section {
height: auto;

}
.left-body {
padding-left: 0px !important;
padding: 20px !important;
}
}

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Git and GitHub

Watch Tutorial → Click Here

Git and GitHub are essential tools for version control and collaboration in software
development.

Git:
Git is a distributed version control system (DVCS) used for tracking changes in
source code during software development. It allows multiple developers to collaborate
on the same project efficiently.

1. Version Control:

o Git enables developers to track changes in their code over time, providing a
complete history of modifications.

2. Distributed:

o Git is a distributed version control system, meaning that each developer has a
full copy of the repository, allowing them to work offline and independently.

3. Branching and Merging:

o Developers can create branches to work on different features or fixes


independently. Merging allows combining these changes seamlessly.

4. Local Repository:

o Git operates locally on your machine, which means you can commit changes
and experiment without affecting the central repository until you choose to
push your changes.

5. Commit History:

o Git keeps a record of every change made to the codebase, making it easy to
trace back and understand the evolution of the project.
GitHub:
GitHub is a web-based platform that hosts Git repositories, providing a central
location for collaboration, code hosting, and project management.

1. Centralized Collaboration:

GitHub provides a central platform where developers can collaborate on projects by


hosting Git repositories.

2. Code Hosting:

Developers can store their code in GitHub repositories, making it accessible from
anywhere with an internet connection.

3. Issue Tracking:

GitHub's issue tracker allows teams to report, track, and manage tasks, bugs, and
feature requests in an organized manner.

4. Pull Requests:

Pull requests in GitHub facilitate code review and collaboration by proposing and
discussing changes before merging them into the main codebase.

5. Workflow Automation:

GitHub Actions enables automation of tasks like building, testing, and deploying
code, streamlining the development process.

6. Documentation:

GitHub offers wiki functionality for collaborative documentation, helping teams


create and maintain project documentation.

7. Project Management:

GitHub Projects allows for the organization and prioritization of work using
customizable boards, making it easier to manage tasks and milestones.

8. Public and Private Repositories:

GitHub provides both public and private repositories, allowing projects to be shared
openly or kept confidential, depending on the needs of the developers.

Notes:
o GitHub is not the only platform for hosting Git repositories. Alternatives
include GitLab and Bitbucket.
o Collaborators can work together on a project by forking a repository and
creating pull requests.
o GitHub offers free public repositories, but private repositories require a
subscription.

GitHub serves as a hub for developers, providing tools and features that enhance
collaboration, code management, and project organization, while Git itself underlies
version control and allows for efficient tracking of code changes. Together, Git and
GitHub support effective software development and project management.

Attempt Quiz → Click Here

Part-2 Watch Tutorial → Click Here

Installing Git:

Official Website: https://git-scm.com/downloads

1. Mac:

o Homebrew:
o /bin/bash -c "$(curl -fsSL
<https://raw.githubusercontent.com/Homebrew/install/HEAD/instal
l.sh>)"
o brew install git
o
o Xcode Command Line Tools:
o xcode-select --install
o

2. Linux (Ubuntu/Debian):
sudo apt update
sudo apt install git

3. Windows:

Download and install Git from the official website: Git for Windows

Initializing a Git Repository:

1. Create a New Local Repository:


git init

2. Configure User Information:


git config --global user.name "Your Name"
git config --global user.email "[email protected]"

Hosting on GitHub:

1. Create a New Repository on GitHub:

o Go to GitHub.
o Click on the "+" sign in the top right and choose "New repository".
o Follow the instructions to create a new repository.

2. Connect Local Repository to GitHub:

o Change into your local repository directory:


o cd /path/to/your/repo
o
o Link your local repository to the GitHub repository:
o git remote add origin <https://github.com/your-username/your-
repo.git>
o

3. Add, Commit, and Push to GitHub:

o Add files to the staging area:


o git add .
o
o Commit changes:
o git commit -m "Initial commit"
o
o Push changes to GitHub:
o git push -u origin master
o

4. Verify on GitHub:

Refresh your GitHub repository page, and you should see your files.

These instructions assume you are using HTTPS for simplicity. If you set up SSH
keys, you can use the SSH URL instead of the HTTPS URL when adding the remote.
Additionally, replace "your-username" and "your-repo" with your GitHub username
and the name of your repository.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Introduction to JavaScript

Watch Tutorial → Click Here

Introduction to JavaScript
1. What is JavaScript?

o JavaScript is a high-level, versatile, and dynamic programming language


primarily used for building interactive web pages and web applications.
o It's often referred to as the "language of the web" because it's the most
common scripting language used in web development.

2. History of JavaScript:

o Developed by Netscape Communications Corporation, led by Brendan Eich in


1995.
o Initially named "LiveScript" but later renamed JavaScript for marketing
purposes.
o Standardized as ECMAScript.

3. JavaScript in Web Development:

o JavaScript is primarily used to enhance the functionality of web pages by


adding interactivity and dynamic behaviour.
o It can be embedded within HTML code and executed by web browsers.

4. Features of JavaScript:

o High-level language: JavaScript abstracts many of the low-level details,


making it easier to write and understand code.
o Interpreted: It's executed by the web browser without the need for
compilation.
o Dynamic and loosely typed: Variables can change types, and you don't need
to specify types explicitly.
o Object-oriented: JavaScript is centered around objects and supports object-
oriented programming.
o Cross-platform: Runs on all major web browsers and platforms.

5. Basic JavaScript Syntax:

o JavaScript code is written in script tags <script></script> within an HTML


document.
o Common statements and constructs include variables, data types, operators,
conditional statements (if, else), loops (for, while), and functions.
o Example:
o // Variables and data types
o var name = "Dodagatta Nihar";
o var age = 19;
o var isStudent = true;
o
o // Functions
o function greet(person) {
o return "Hello, " + person;
o }
o

6. DOM Manipulation:
o JavaScript is used to manipulate the Document Object Model (DOM) of a web
page.
o It can change HTML elements, attributes, and styles dynamically, making web
pages interactive.

7. Events and Event Handling:

o JavaScript allows you to respond to user actions (clicks, keypresses, etc.) by


defining event handlers.
o Event-driven programming is a key concept in JavaScript.

8. Libraries and Frameworks:

o JavaScript has a vast ecosystem of libraries and frameworks like jQuery,


React, Angular, and Vue.js to simplify web development.

9. Modern JavaScript (ECMAScript):

o ES6 (ECMAScript 2015) introduced new features like arrow functions,


classes, template literals, and more to make JavaScript development more
efficient and maintainable.

10. Debugging and Development Tools:

o Browsers have built-in developer tools for debugging and inspecting


JavaScript code.

11. Server-Side JavaScript:

o Node.js allows developers to use JavaScript on the server-side, opening up


opportunities for building full-stack applications.

12. Security Considerations:

o JavaScript can potentially introduce security vulnerabilities, so developers


need to be aware of best practices for securing their applications.

In summary, JavaScript is a fundamental language for web development, enabling the


creation of interactive and dynamic web applications. Its versatility, along with the
support of modern libraries and frameworks, has made it a powerful tool for web
developers.

Attempt Quiz → Click Here

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Variables and Data types


Watch Tutorial → Click Here

Variables in JavaScript:

Variables in JavaScript are used to store data values. You can think of them as
containers that hold different types of information. To declare a variable in JavaScript,
you can use the var, let, or const keywords.

0. var :
 var was traditionally used for variable declaration, but it has some
scope issues and is less commonly used now.
1. var age = 19; // Declaring a variable 'age' and assigning it a
value of 19
2. age = 20; // You can change the value of a 'var' variable
3.
4. let:
 let allows you to declare block-scoped variables, which means they
are only accessible within the block (e.g., inside a function or loop)
where they are defined.
5. let name = "Dodagatta Nihar";
6. let age = 19;
7.
8. const:
 const is used to declare constants. Once a value is assigned to a
const, it cannot be changed.
9. const pi = 3.14159;
10.

Data Types in JavaScript:

JavaScript has several data types to represent different kinds of values. These data
types include:

11. Primitive Data Types:

a. String:

 Represents textual data and is enclosed in single or double quotes.

let name = "Dodagatta Nihar";

b. Number:

 Represents both integer and floating-point numbers.

let age = 19;


let price = 19.69;

c. Boolean:
 Represents true or false values.

let isStudent = true;


let isAdmin = false;

d. Undefined:

 Represents a variable that has been declared but hasn't been assigned a
value.

let x;
console.log(x); // This will output 'undefined'

e. Null:

 Represents the intentional absence of any object value.

let emptyValue = null;

12. Reference Data Types:

a. Object:

 Used to store collections of key-value pairs. Objects are created using


curly braces {}.

let person = {
name: "Bob",
age: 30,
};

b. Array:

 Used to store ordered collections of values. Arrays are created using


square brackets [].

let colors = ["red", "green", "blue"];

c. Function:

 Functions are objects and can be assigned to variables, passed as


arguments, and returned from other functions.

function greet(name) {
return `Hello, ${name}!`;
}
These are the fundamental concepts of variables and data types in JavaScript.
Understanding these concepts is essential for writing effective and flexible JavaScript
code.

Attempt Quiz → Click Here

Assignment Questions:

13. Variable Declaration:


 Question: Declare a variable called myNumber and assign it the value
5. Output the value using console.log().
14. Boolean Variable:
 Question: Declare a variable called isSunny and assign it the value
true. Output the value using console.log().
15. String Concatenation:
 Question: Declare two variables, firstName and lastName, and
assign them your first and last name, respectively. Concatenate them to
form a full name and output the result.
16. Array Declaration:
 Question: Declare an array called myArray with three elements: 1, 2,
and 3. Output the array using console.log().
17. Object Declaration:
 Question: Create an object called myObject with a property color set
to "blue" and another property number set to 42. Output the object
using console.log().

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Arithmetic and Comparison Operators

Watch Tutorial → Click Here

Arithmetic Operators:

Arithmetic operators in JavaScript allow you to perform mathematical calculations on


numeric values. Here are the most common arithmetic operators:

0. Addition (+): Adds two numbers together.


1. let sum = 5 + 3; // sum will be 8
2.
3. Subtraction (-): Subtracts the right operand from the left operand.
4. let difference = 10 - 4; // difference will be 6
5.
6. Multiplication (*): Multiplies two numbers.
7. let product = 6 * 7; // product will be 42
8.
9. Division (/): Divides the left operand by the right operand.
10. let quotient = 20 / 4; // quotient will be 5
11.
12. Modulus (%): Returns the remainder of the division of the left operand by the
right operand.
13. let remainder = 17 % 5; // remainder will be 2
14.
15. Increment (++) and Decrement (--): These operators increase or decrease a
variable by 1.
16. let count = 5;
17. count++; // Increment by 1, count is now 6
18. count--; // Decrement by 1, count is now 5
19.

Comparison Operators:

Comparison operators in JavaScript are used to compare values and return Boolean
results (true or false). Here are some common comparison operators:

20. Equal (==): Checks if two values are equal, but it doesn't consider data types
(type coercion).
21. 5 == "5"; // true (values are equal, type coercion)
22.
23. Not Equal (!=): Checks if two values are not equal, with type coercion.
24. 5 != "3"; // true (values are not equal, type coercion)
25.
26. Strict Equal (===): Checks if two values are equal and have the same data
type (no type coercion).
27. 5 === 5; // true (values and data types are equal)
28.
29. Strict Not Equal (!==): Checks if two values are not equal or have different
data types.
30. 5 !== "5"; // true (values are not equal or have different
data types)
31.
32. Greater Than (>): Checks if the left value is greater than the right value.
33. 10 > 5; // true
34.
35. Less Than (<): Checks if the left value is less than the right value.
36. 3 < 7; // true
37.
38. Greater Than or Equal (>=): Checks if the left value is greater than or equal
to the right value.
39. 10 >= 10; // true
40.
41. Less Than or Equal (<=): Checks if the left value is less than or equal to the
right value.
42. 3 <= 3; // true
43.

These operators are crucial for performing comparisons and making decisions in your
JavaScript code. Understanding how to use them effectively is fundamental for
writing robust programs.

Attempt Quiz → Click Here

Assignment Questions:
44. Code a statement that adds 5 and 7. Assign the result to a variable called sum.
45. Write a line of code that subtracts 3 from 10. Store the result in a variable
named difference.
46. Use JavaScript to multiply 4 by 6. Save the product in a variable called
product.
47. Create a line of code that divides 15 by 3. Save the quotient in a variable
named quotient.
48. Write a statement that checks if 8 is equal to "8". Store the result in a variable
named isEqual.
49. Code a line that verifies if 10 is greater than 5. Save the result in a variable
named isGreaterThan.
50. Implement a statement that checks if 6 is not equal to 6. Store the result in a
variable named isNotEqual.
 Logical Operators

Watch Tutorial → Click Here

Logical Operators

Logical operators in JavaScript are used to combine or manipulate Boolean values.


They allow you to make more complex decisions by evaluating multiple conditions.
There are three main logical operators in JavaScript: && (AND), || (OR), and !
(NOT). Let's explore these operators with examples:

1. Logical AND (&&):

The && operator returns true if both of its operands are true. If at least one of the
operands is false, it returns false.

let isTrue = true;


let isFalse = false;

let result1 = isTrue && isTrue; // true (both operands are true)
let result2 = isTrue && isFalse; // false (one operand is false)
let result3 = isFalse && isFalse; // false (both operands are false)

2. Logical OR (||):

The || operator returns true if at least one of its operands is true. If both operands
are false, it returns false.

let isTrue = true;


let isFalse = false;

let result1 = isTrue || isTrue; // true (both operands are true)


let result2 = isTrue || isFalse; // true (one operand is true)
let result3 = isFalse || isFalse; // false (both operands are false)

3. Logical NOT (!):


The ! operator is a unary operator that negates a Boolean value. It returns true if the
operand is false, and false if the operand is true.

let isTrue = true;


let isFalse = false;

let result1 = !isTrue; // false (negating true)


let result2 = !isFalse; // true (negating false)

Combining Logical Operators:

You can combine logical operators to create more complex conditions. Parentheses
are often used to control the order of evaluation.

let x = 5;
let y = 10;

let isGreater = (x > y) && (x !== 0); // false (both conditions must
be true)
let isEither = (x < y) || (y === 10); // true (at least one condition
must be true)
let isNotZero = !(x === 0); // true (negating a false condition)

Attempt Quiz → Click Here

Assignment Questions:

0. Write a program that checks whether a given number is between 10 and 20


(inclusive). Use the logical AND operator (&&) for this task.
1. Create a program that determines whether a given year is a leap year. A leap
year is either divisible by 4 but not by 100 unless it is divisible by 400. Use the
logical OR operator (||) in your solution.
2. Write a program that takes a boolean parameter and returns the opposite value.
Use the logical NOT operator (!) to achieve this.
3. Create a program that asks the user for their age and whether they have a valid
driver's license. Allow them to proceed only if they are 18 or older and have a
valid driver's license. Use a combination of logical operators.
4. Write a program that determines if a given number is positive and even.

Note: use prompt() function to get user input

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Conditional Statements

Watch Tutorial → Click Here

Conditional Statements
Conditional statements in JavaScript allow you to control the flow of your program
based on certain conditions. They enable you to make decisions and execute different
blocks of code depending on whether a condition is true or false. There are three
primary conditional statements in JavaScript: if, else if, and else. Let's explore
them with examples:

1. The if Statement:

The if statement is used to execute a block of code if a condition is true.

let temperature = 25;

if (temperature > 30) {


console.log("It's a hot day!"); // This code block will not execute
}

if (temperature <= 30) {


console.log("It's a pleasant day!"); // This code block will
execute
}

2. The if...else Statement:

The if...else statement is used when you want to execute one block of code if a
condition is true, and another block if it's false.

let age = 18;

if (age >= 18) {


console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

3. The else if Statement:

The else if statement allows you to specify multiple conditions to check. It's often
used in conjunction with if...else statements.

let hour = 14;

if (hour < 12) {


console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}

Nesting Conditional Statements:


You can also nest conditional statements within each other to create more complex
logic.

let isWeekend = true;


let time = 14;

if (isWeekend) {
if (time < 12) {
console.log("Good morning on the weekend!");
} else {
console.log("Good afternoon on the weekend!");
}
} else {
if (time < 12) {
console.log("Good morning on a weekday!");
} else {
console.log("Good afternoon on a weekday!");
}
}

Ternary Operator:

JavaScript also provides a concise way to write simple conditional statements using
the ternary operator (? :).

let isRaining = true;


let weatherMessage = isRaining ? "Bring an umbrella." : "No need for
an umbrella.";
console.log(weatherMessage);

Conditional statements are fundamental for writing dynamic and responsive


programs, allowing you to control the logic of your code based on different conditions
and scenarios.

Attempt Quiz → Click Here

Assignment Questions:

0. Write an if...else statement that assigns "It's hot" to a variable weather if


the temperature is over 80 degrees, and "It's nice" if the temperature is 80
degrees or cooler. Log the weather variable to the console.
1. Write a ternary statement that checks if a variable age is 18 or over. If so,
assign the variable canVote to true, otherwise assign it to false. Log the
canVote variable.
2. Write nested conditional statements that check if a variable day is Saturday or
Sunday, and if a variable time is before 11am. If both conditions are true, log
"Sleep in!", else log "Wake up!".
3. Write a series of if, else if, and else statements that check if a variable
temp is below 32 (freezing), between 32 and 50 (cold), between 50 and 70
(pleasant), or above 70 (hot). Log an appropriate message for each
temperature range.
4. Write conditional statements to implement a simple calculator. Have the user
input two numbers and an operation ("+","-","*","/"). Based on the operation,
perform the mathematical operation on the numbers and log the result. Handle
division by zero gracefully without errors.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Loops in JavaScript

Watch Tutorial → Click Here

Loops

In JavaScript, loops are used to execute a block of code repeatedly. There are several
types of loops in JavaScript, but the most common ones are for loops, while loops,
and do...while loops. Let's explore these loops with examples:

1. for Loop:

The for loop is used when you know how many times you want to repeat a block of
code. It consists of three parts: initialization, condition, and increment/decrement.

for (let i = 0; i < 5; i++) {


console.log("Iteration number: " + i);
}

This loop will execute the code block five times, starting from i = 0, incrementing i
by 1 with each iteration until the condition (i < 5) is no longer true.

2. while Loop:

The while loop is used when you don't know in advance how many times you want to
repeat a block of code. It continues as long as a specified condition is true.

let count = 0;

while (count < 5) {


console.log("Count is: " + count);
count++;
}

This loop will execute the code block as long as the condition count < 5 remains
true.

3. do...while Loop:

The do...while loop is similar to the while loop, but it always executes the code
block at least once before checking the condition.
let x = 0;

do {
console.log("x is: " + x);
x++;
} while (x < 5);

This loop first executes the code block and then checks the condition x < 5. If it's
true, the loop continues; otherwise, it stops.

Loop Control Statements:

JavaScript provides loop control statements that allow you to control the flow of
loops:

o break: Terminates the loop.


o continue: Skips the current iteration and continues to the next one.

Example with break:

for (let i = 0; i < 10; i++) {


if (i === 5) {
break; // Stop the loop when i is 5
}
console.log("i is: " + i);
}

Example with continue:

for (let i = 0; i < 10; i++) {


if (i === 5) {
continue; // Skip the iteration when i is 5
}
console.log("i is: " + i);
}

Loops are essential for iterating over arrays, processing data, and performing
repetitive tasks in your JavaScript programs. Understanding how to use loops
effectively is a fundamental skill for any JavaScript developer.

Attempt Quiz → Click Here

Assignment Questions:

2. Write a for loop that prints all even numbers from 0 to 10.
3. Initialize an array of 5 fruits. Use a for loop to print all the elements.
4. Take an array of numbers as input. Use a do-while loop to compute their sum
by iterating over the array (hint: arrayname.length).
5. Write a loop that iterates from 7 to 77 and prints only those numbers which are
multiples of 7. (use the modulus operator %)
6. Use nested for loops to print the following pattern:

*
* *
* * *
* * * *
* * * * *

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Arrays in JavaScript

Watch Tutorial → Click Here

Arrays

Arrays in JavaScript are a data structure used to store collections of values in a single
variable. You can access the elements in an array by their index, and arrays are very
versatile and widely used in JavaScript for a variety of tasks.

Declaration and Initialization:

To declare and initialize an array in JavaScript, you can use square brackets to enclose
the array elements. Here's an example:

// Declaration and initialization of an array


let fruits = ['apple', 'banana', 'cherry', 'date'];

// Accessing elements by index


console.log(fruits[0]); // Output: 'apple'

Array Methods

0. Push Method:

The push method adds one or more elements to the end of an array and returns
the new length of the array.

fruits.push('elderberry');
console.log(fruits); // Output: ['apple', 'banana', 'cherry',
'date', 'elderberry']

1. Pop Method:

The pop method removes the last element from an array and returns that
element.

let removedFruit = fruits.pop();


console.log(removedFruit); // Output: 'elderberry'
console.log(fruits); // Output: ['apple', 'banana', 'cherry',
'date']

2. Shift Method:

The shift method removes the first element from an array and returns that
element.

let removedFruit = fruits.shift();


console.log(removedFruit); // Output: 'apple'
console.log(fruits); // Output: ['banana', 'cherry', 'date']

3. Unshift Method:

The unshift method adds one or more elements to the beginning of an array
and returns the new length of the array.

fruits.unshift('apricot', 'fig');
console.log(fruits); // Output: ['apricot', 'fig', 'banana',
'cherry', 'date']

Attempt Quiz → Click Here

Assignment Questions:

4. Create an array called "fruits" and add 3 fruits to it using the push() method.
Then remove the last fruit using the pop() method and display the updated
array.
5. Create an array called "vegetables" with 5 items. Remove the first item using
shift() and add a new item to the beginning using unshift(). Display the
updated array.
6. Create an array called "nums" with numbers 1-5. Using a loop, remove all
existing items and add numbers 6-10 using the push() method. Display the
final array.
7. Create an array called "strings" with 5 string values. Using push() and
unshift(), add 2 items to beginning and end. Using pop() and shift(), remove 2
items from beginning and end. Display array after each operation.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Few more Array Methods

Watch Tutorial → Click Here

Few more Array Methods


concat Method:

The concat method is used to merge two or more arrays and returns a new array.

let fruits = ['apple', 'banana'];


let vegetables = ['carrot', 'broccoli'];
let combined = fruits.concat(vegetables);

slice Method:

The slice method extracts a section of an array and returns it as a new array.

let subArray = combined.slice(2, 4); // Extract elements at indices 2


an

splice Method:

The splice method can be used to add, remove, or replace elements within an array.

combined.splice(2, 2, 'grape', 'kiwi'); // Remove 2 elements from


index 2 and insert 'grape' and 'ki

indexOf Method:

The indexOf method returns the first index at which a given element is found in the
array, or -1 if it is not present.

let index = combined.indexOf('kiwi');

filter Method:

The filter method creates a new array with all elements that pass a test implemented
by a provided function.

let filtered = combined.filter(item => item.length > 5);

forEach Method:

The forEach method allows you to iterate over the elements of an array and execute a
function for each element.

let numbers = [1, 2, 3, 4, 5];


numbers.forEach(function(number) {
console.log(number * 2);
});
// Output: 2, 4, 6, 8, 10

map Method:
The map method creates a new array by applying a function to each element of the
original array.

let squared = numbers.map(function(number) {


return number * number;
});
console.log(squared); // Output: [1, 4, 9, 16, 25]

find Method:

The find method returns the first element in an array that satisfies a provided testing
function.

let even = numbers.find(function(number) {


return number % 2 === 0;
});
console.log(even); // Output: 2 (the first even number)

sort Method:

The sort method is used to sort the elements of an array in place and return the sorted
array.

let fruits = ['banana', 'cherry', 'apple', 'date'];


fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'cherry', 'date']

Attempt Quiz → Click Here

Assignment Questions:

0. Create an array of 5 student names. Take a new input student name from the
user and add it to the existing array using concat(). Display the final array.
1. Create an array of length 10 with random numbers between 1-100. Take a
slice of this array to select only last 5 elements. Display the sliced array.
2. Create an array of 6 fruits with "apple" as one of them. Use indexOf() to find
position of "apple". Display the index or display "apple not found".
3. Create an array of even numbers from 2 to 20. Using filter(), create new array
with only numbers greater than 10. Display filtered array.
4. Create an array to store 5 random country names. Sort the array in ascending
alphabetical order using sort() method. Display final array.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Functions Part-1

Watch Tutorial → Click Here


Functions Part 1: Function Basics and Declaration

0. Function Declaration:

In JavaScript, you can declare a function using the function keyword. A


function is a block of reusable code that performs a specific task.

function greet(name) {
console.log(`Hello, ${name}!`);
}

greet('John'); // Output: Hello, John!

1. Function Parameters:

Functions can take parameters (inputs) and use them within the function's
body.

function add(a, b) {
return a + b;
}

let result = add(3, 5);


console.log(result); // Output: 8

2. Function Expression:

Functions can also be defined as expressions and assigned to variables. This is


useful for creating anonymous functions or passing functions as arguments.

const multiply = function(a, b) {


return a * b;
};

let product = multiply(4, 6);


console.log(product); // Output: 24

3. Arrow Functions:

Arrow functions provide a concise syntax for defining functions, especially for
one-liners.

const square = (x) => x * x;

let squaredValue = square(7);


console.log(squaredValue); // Output: 49

4. Return Statement:
Functions can return values using the return statement. If a function doesn't
explicitly return a value, it returns undefined.

function sayHello() {
return 'Hello!';
}

let greeting = sayHello();


console.log(greeting); // Output: Hello!

Attempt Quiz → Click Here

Assignment Questions:

5. Write a function addNumbers that takes two numbers as arguments and returns
their sum. Call the function to find sum of any two numbers and display the
result.
6. Write an arrow function square that takes a number and returns its square.
Call this function to find square of any number and display the result.
7. Write a function expression called randomNumber that returns a random whole
number between 1 and 10. Assign this function to a variable and display
output of that variable to see random numbers.
8. Write a function stringConcat that takes two string arguments and returns
concatenated string. Call this function to concatenate your first and last name
into a full name. Display the returned full name.
9. Write a function greetUser that takes username as input parameter and
returns a greeting text for that user. Call the function for at least 3 different
users and display their customized greetings.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Functions Part-2

Watch Tutorial → Click Here

Functions Part 2: Function Scope, Closures, and Callbacks

0. Function Scope:

Variables declared inside a function are scoped to that function and not
accessible from outside.

function outerFunction() {
let message = 'I am inside the function';
console.log(message);
}

outerFunction();
console.log(message); // Error: message is not defined
1. Closures:

A closure is a function that "remembers" its lexical scope, even when called
outside that scope.

function outer() {
let message = 'Hello';

function inner() {
console.log(message);
}

return inner;
}

let closure = outer();


closure(); // Output: Hello

2. Callbacks:

Functions can be passed as arguments to other functions, commonly used in


asynchronous operations.

function fetchData(callback) {
// Simulate an asynchronous operation
setTimeout(function() {
let data = 'This is the data';
callback(data);
}, 2000);
}

function displayData(data) {
console.log(data);
}

fetchData(displayData); // Output: This is the data (after a 2-


second delay)

3. Named and Anonymous Functions:

Functions can be named or anonymous. Named functions have a name, and


anonymous functions do not.

// Named function
function namedFunction() {
console.log('I am named');
}

// Anonymous function assigned to a variable


const anonymousFunction = function() {
console.log('I am anonymous');
};

namedFunction(); // Output: I am named


anonymousFunction(); // Output: I am anonymous
4. Function Hoisting:

In JavaScript, function declarations are hoisted to the top of their containing


scope, which means you can use a function before it's declared.

hoistedFunction(); // Output: I am hoisted

function hoistedFunction() {
console.log('I am hoisted');
}

Functions are a fundamental concept in JavaScript and play a crucial role in


structuring and organizing code. They can be used for a wide range of tasks, from
simple calculations to complex program logic and asynchronous operations.
Understanding how to create, use, and pass functions is essential for JavaScript
development.

Attempt Quiz → Click Here

Assignment Questions:

5. Write a function that uses a closure to create a counter. The function should
return a new function that when invoked increments and returns a counter
variable.
6. Write a function outer which returns an anonymous inner function that
changes a variable message when called. Call the inner function and display
the changed message outside outer.
7. Write an asynchronous function fakeFetch that accepts a callback. Use
setTimeout inside fakeFetch to simulate a 2 second asynchronous operation
before calling the callback function.
8. Write both a named and an anonymous function to print your name. Store
them in variables and call both functions.
9. Write a program with a function called hoisted and call that function before
declaring it to see hoisting in action.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 OOP Part-1

Watch Tutorial → Click Here

Object-Oriented Programming (OOP):

Object-Oriented Programming (OOP) is a programming paradigm that revolves


around the concept of objects. It provides a way to structure and design software by
modeling real-world entities and their interactions. OOP is widely used in software
development and is based on several fundamental concepts:

1. Objects: Objects are the basic building blocks of OOP. They represent real-world
entities, combining data (attributes) and behavior (methods or functions) into a single
unit. Objects are instances of classes.

2. Classes: A class is a blueprint or template for creating objects. It defines the


structure and behavior of objects of that type. In other words, a class specifies what
attributes an object will have and what methods it can execute.

3. Encapsulation: Encapsulation is the concept of bundling data (attributes) and


methods that operate on that data into a single unit, a class. Encapsulation restricts
access to some of an object's components, preventing the accidental modification of
data and ensuring data integrity.

4. Inheritance: Inheritance is a mechanism that allows you to create a new class


based on an existing class, inheriting its attributes and methods. This promotes code
reusability and the creation of more specialized classes. The existing class is known as
the base or parent class, and the new class is the derived or child class.

5. Polymorphism: Polymorphism means that different objects can respond to the


same method or function call in a way that is appropriate for their specific class. This
allows you to write code that can work with objects of different classes through a
common interface. Polymorphism is often achieved through method overriding or
interface implementations.

Sure, let's illustrate some of the basic Object-Oriented Programming (OOP) concepts
with a simple example in JavaScript:

// Define a class called "Person"


class Person {
// Constructor method to initialize object properties
constructor(name, age) {
this.name = name;
this.age = age;
}

// Method to greet
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age}
years old.`);
}
}

// Create objects (instances) of the "Person" class


const person1 = new Person("Nihar", 20);
const person2 = new Person("Akshay", 23);

// Access object properties and call methods


console.log(person1.name); // Output: "Nihar"
console.log(person2.age); // Output: 23
person1.greet(); // Output: "Hello, my name is Nihar and I am 20
years old."
person2.greet(); // Output: "Hello, my name is Akshay and I am 23
years old."

In this example:

0. We define a class called Person with a constructor that initializes name and
age properties.
1. The greet method is a function associated with the Person class.
2. We create two objects, person1 and person2, each with their own set of
properties.
3. We access object properties and call the greet method to display a message
specific to each object.

This example demonstrates key OOP concepts, such as classes, objects, properties,
and methods. The Person class acts as a blueprint for creating objects, and objects
have their own data (properties) and behavior (methods). It's a simple illustration of
how OOP promotes code organization and the modeling of real-world entities in your
code.

“this” operator:

In JavaScript, the this operator is typically used in the constructor of a class to refer
to the current instance of the object being created. It's used to initialize and assign
values to the object's properties. While it's common and standard practice to use this
in constructors, it is not strictly necessary to do so, especially if you are not using
object-oriented programming principles.

However, when you are using the class syntax in JavaScript to define constructors and
methods, it is recommended and standard to use this to reference the instance's
properties. This ensures clarity and consistency in your code, making it easier to
understand and maintain.

If you decide not to use this in the constructor, you would have to come up with an
alternative approach to initialize and assign values to the object's properties, which
can make your code less conventional and less readable.

Here's an example of a constructor without using this, though it's not a common
practice:

class Person {
constructor(name, age) {
const person = {};

person.name = name;
person.age = age;

return person;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age}
years old.`);
}
}

const person1 = new Person("Nihar", 20);


console.log(person1.name); // Output: "Nihar"

In this example, the constructor creates a new object (person) and returns it, which is
a less common and less conventional approach. It's typically recommended to use
this in the constructor for better code organization and maintainability.

OOP promotes modularity, reusability, and the organization of code. It helps


developers manage complex systems by breaking them down into smaller, more
manageable components. OOP is widely used in programming languages such as
Java, C++, Python, and C#, and it plays a crucial role in modern software
development.

Attempt Quiz → Click Here

Assignment Question:

Create a class called 'BankAccount' with attributes accountNumber, name, balance.


Write a constructor, deposit() and withdraw() methods to add/subtract money from
balance. Create 2 accounts, make some deposits and withdrawals, and print updated
balances.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 OOP Part-2

Watch Tutorial → Click Here

1. Objects:

In JavaScript, objects are collections of key-value pairs. They are used to represent
and organize data. Objects can contain various data types, including other objects,
functions, and primitive values. Here's how you can create an object:

let person = {
firstName: "Nihar",
lastName: "Dodagatta",
age: 20
};

2. Properties:
Properties are the key-value pairs within an object. They define the characteristics or
attributes of the object. You can access object properties using dot notation or bracket
notation:

console.log(person.firstName); // Using dot notation


console.log(person["lastName"]); // Using bracket notation

You can also add, modify, or delete properties of an object:

person.gender = "Male"; // Adding a property


person.age = 31; // Modifying a property
delete person.age; // Deleting a property

3. Methods:

Methods are functions defined as properties of an object. They allow you to perform
actions or operations on the object's data. Here's how you can define and use a method
within an object:

let calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
}
};

console.log(calculator.add(5, 3)); // Calling the add method


console.log(calculator.subtract(10, 2)); // Calling the subtract
method

4. Object Properties and Methods:

In addition to user-defined objects, JavaScript has several built-in objects and


methods that are part of the core language or provided by the JavaScript runtime
environment. For example, the Math object contains various mathematical methods,
and the Date object allows working with date and time values.

let circle = {
radius: 5,
area() {
return Math.PI * this.radius * this.radius;
}
};

console.log(circle.area()); // Output: 78.53981633974483

5. Object Constructors:

You can create multiple objects with the same structure and methods by using
constructor functions or classes. Constructor functions are functions that are used to
create objects with similar properties and methods. Here's an example of an object
created using a constructor function:

class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}

const nihar = new Person("Nihar", "Dodagatta");


console.log(nihar.getFullName()); // Output: "Nihar Dodagatta"

Attempt Quiz → Click Here

Assignment Question:

Create a JavaScript object called Rectangle with the following properties:

o length
o width

And the following methods:

o area() - Calculates and returns the area of the rectangle


o perimeter() - Calculates and returns the perimeter of the rectangle

Then create a Rectangle object to represent a rectangle with length = 5 and width = 3.

Call the area() and perimeter() methods on the rectangle object and log the results to
display the area and perimeter of the rectangle.

The key things to demonstrate:

o Creating an object
o Using properties
o Defining and calling methods
o Using this keyword

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Document Object Model

Watch Tutorial → Click Here

Document Object Model:


The Document Object Model, commonly referred to as the DOM, is a fundamental
concept in web development. It is a programming interface for web documents,
providing a structured representation of the web page's content. The DOM represents
the page so that programs (typically written in JavaScript) can interact with the web
page's content dynamically, allowing you to read, manipulate, and change the content,
structure, and style of a webpage.

Here's a more detailed introduction to the Document Object Model:

1. Structured Representation: The DOM represents the elements of an HTML or


XML document as a structured tree-like model, where each HTML element, attribute,
and piece of text is represented as an object or node in the tree.

2. Hierarchical Structure: The DOM is organized hierarchically, with the top-level


node called the "document" object. The document object serves as the entry point to
the DOM tree and contains all other elements as its children. Elements are organized
in a parent-child relationship, forming a tree structure.

3. Programmable Interface: The DOM provides a programmatic interface for


scripting languages like JavaScript to access and manipulate the elements within a
web page. It allows developers to interact with web content, create dynamic web
applications, and respond to user actions.

4. Properties and Methods: Every node in the DOM tree has properties and methods
that can be accessed and called using scripting languages. These properties allow you
to access attributes and content, while methods enable you to modify or interact with
the content.

5. Real-Time Interaction: The DOM is not a static representation of a webpage but


rather a dynamic one. It reflects any changes made to the web page in real time. For
example, if you change the text of a paragraph element using JavaScript, the DOM is
updated immediately to reflect that change.

6. Browser Independence: The DOM is implemented by web browsers, and it


provides a consistent way for developers to access and manipulate web content
regardless of the browser being used. This standardization makes it easier to write
cross-browser-compatible code.

7. Use Cases: The DOM is used for various purposes in web development, such as:

o Accessing Elements: You can locate and access HTML elements in a


document to retrieve or change their attributes, content, or styles.
o Manipulating Content: You can add, remove, or modify elements and their
content on the fly.
o Handling Events: You can attach event handlers to respond to user actions,
such as clicks or keyboard inputs.
o Creating Dynamic Interfaces: The DOM allows you to build interactive and
dynamic user interfaces by manipulating elements based on user interactions
or changing data.
In summary, the Document Object Model (DOM) is a structured representation of a
web page's content, allowing developers to access and manipulate web content in a
dynamic and programmatic manner. It is a foundational concept for web development
and is heavily used in combination with JavaScript to create interactive and
responsive web applications.

Selecting and manipulating HTML elements with JavaScript is a fundamental skill in


web development. JavaScript provides various methods to select elements from the
Document Object Model (DOM) and perform actions like changing content, styles,
and attributes. Here's an overview of how to select and manipulate HTML elements:

Selecting HTML Elements:

4. getElementById: Select an element by its unique ID attribute.


5. const element = document.getElementById("myElementId");
6.
7. getElementsByClassName: Select elements by their class name.
8. const elements = document.getElementsByClassName("myClass");
9.
10. getElementsByTagName: Select elements by their tag name.
11. const elements = document.getElementsByTagName("p");
12.
13. querySelector: Select the first element that matches a CSS selector.
14. const element = document.querySelector(".myClass");
15.
16. querySelectorAll: Select all elements that match a CSS selector.
17. const elements = document.querySelectorAll("p.myClass");
18.

Manipulating HTML Elements:

Once you've selected an element, you can manipulate it in various ways.

19. Changing Content:


 innerHTML: Change the HTML content of an element.
 element.innerHTML = "New content";

 textContent: Change the text content of an element.
 element.textContent = "New text content";

20. Changing Attributes:
 setAttribute: Set or change an attribute.
 element.setAttribute("href",
"<https://www.example.com>");

 getAttribute: Get the value of an attribute.
 const hrefValue = element.getAttribute("href");

21. Styling Elements:
 style: Change CSS styles of an element.
 element.style.color = "blue";
 element.style.fontSize = "20px";

22. Adding/Removing Classes:
 classList: Add or remove CSS classes from an element.
 element.classList.add("newClass");
 element.classList.remove("oldClass");

23. Creating New Elements:
 createElement: Create a new HTML element.
 const newElement = document.createElement("div");

 appendChild: Add the new element to the DOM.
 parentElement.appendChild(newElement);

These are the basics of selecting and manipulating HTML elements with JavaScript.
The combination of selecting the right element and using the appropriate methods
allows you to create dynamic and interactive web pages. It's essential to understand
the DOM and how JavaScript interacts with it to build effective and responsive web
applications.

Attempt Quiz → Click Here

Assignment Question:

Create an HTML page with the following elements:

o A heading (h1) with id "main-heading"


o A paragraph (p) with class "content"
o An image (img) with src pointing to an image file
o A button with id "change-button"

Write a JavaScript code that does the following when the button is clicked:

28. Change the text content of the heading to "Updated Heading"


29. Change the alt text of the image to "Updated Image"
30. Change the text content of the paragraph to a sample text of your choice
31. Change the background color of the button to red

Use the following DOM methods:

o getElementById()
o querySelector()
o textContent
o setAttribute()
o style

Key things to demonstrate in your code:

o Selecting elements using DOM methods


o Manipulating content, attribute, style using properties and methods
o Adding interactivity using click listener and callback function
Congrats Mowa Successful ga complete chesnav! Next session lo
kaluddam :)

 Working with DOM

Watch Tutorial → Click Here

1. Accessing Elements:

You can access HTML elements in a document by using methods like


getElementById, getElementsByClassName, or getElementsByTagName. Here's an
example of accessing an element by its ID:

<!DOCTYPE html>
<html>
<body>
<h1 id="myHeading">Hello, DOM!</h1>
<p>This is a simple example.</p>

<script>
// Accessing an element by its ID
const heading = document.getElementById("myHeading");
console.log(heading.innerHTML); // Output: "Hello, DOM!"
</script>
</body>
</html>

2. Manipulating Content:

You can change the content and attributes of HTML elements dynamically. Here's an
example of changing the text of a paragraph element:

<!DOCTYPE html>
<html>
<body>
<p id="myParagraph">This is a paragraph.</p>

<script>
// Changing the text of a paragraph element
const paragraph = document.getElementById("myParagraph");
paragraph.innerHTML = "This is a new paragraph text.";
</script>
</body>
</html>

3. Handling Events:

You can attach event handlers to HTML elements to respond to user interactions.
Here's an example of adding a click event handler to a button:

<!DOCTYPE html>
<html>
<body>
<button id="myButton">Click me</button>

<script>
// Adding a click event handler
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
</script>
</body>
</html>

4. Creating Dynamic Interfaces:

The DOM allows you to create dynamic user interfaces. Here's an example of a
simple counter that increments when a button is clicked:

<!DOCTYPE html>
<html>
<body>
<p>Counter: <span id="counter">0</span></p>
<button id="incrementButton">Increment</button>

<script>
// Creating a dynamic interface
const counter = document.getElementById("counter");
const incrementButton =
document.getElementById("incrementButton");
let count = 0;

incrementButton.addEventListener("click", function() {
count++;
counter.innerHTML = count;
});
</script>
</body>
</html>

These examples demonstrate how the DOM can be used to access elements,
manipulate content, handle events, and create dynamic web interfaces in web
development. JavaScript, in conjunction with the DOM, provides the tools for making
web pages interactive and responsive to user interactions.

Attempt Quiz → Click Here

Assignment Question:

Create an HTML page with the following elements:

o An empty unordered list element (ul) with id "myList"


o An input text field with id "itemInput"
o A button with id "addButton"

Write a JavaScript code that does the following:


3. When the add button is clicked, get the text entered in the input field
4. Create a new li element and set its text as the input text
5. Append the newly created li element to the unordered list

This will allow users to add list items by entering text and clicking the add button.

Key things to demonstrate:

o Get input value on button click


o Create DOM elements dynamically (createElement)
o Add event listener for click event
o Append child element to parent element

Include necessary DOM methods like:

o document.getElementById()
o .value
o document.createElement()
o .appendChild()
o addEventListener()

Test your code by adding a few list items and ensuring they get appended to the
unordered list on button click.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Event Handling

Watch Tutorial → Click Here

Event Handling

Event handling in JavaScript is a fundamental concept that allows you to respond to


user interactions, such as clicks, keyboard input, mouse movements, and more. Events
are actions or occurrences that can be detected by your web page, and event handling
is the process of defining and executing code in response to these events. Here's a
comprehensive overview of event handling in JavaScript:

1. Event Types:

JavaScript supports a wide range of events that can occur in a web page. Some
common event types include:

o Mouse Events: Such as click, hover, mouseover, and mouseout.


o Keyboard Events: Including keydown, keyup, and keypress.
o Form Events: Such as submit, reset, focus, and blur.
o Window Events: Including load, resize, and scroll.
o Touch Events: For touchscreen devices, including touchstart and touchend.
o Custom Events: You can also create custom events when needed.

2. Event Listeners:

Event listeners are used to "listen" for specific events on HTML elements and trigger
a specified function (the event handler) when the event occurs. You can add event
listeners using the addEventListener method.

const button = document.getElementById("myButton");

button.addEventListener("click", function(event) {
// Event handling code
});

3. Event Object:

When an event occurs, an event object is automatically passed to the event handler as
a parameter. This object contains information about the event, such as the target
element, event type, mouse position, and more.

element.addEventListener("click", function(event) {
console.log("Event type: " + event.type);
console.log("Target element: " + event.target);
console.log("Mouse X: " + event.clientX);
console.log("Mouse Y: " + event.clientY);
});

4. Removing Event Listeners:

You can also remove event listeners if they are no longer needed using the
removeEventListener method.

element.removeEventListener("click", eventHandler);

5. Event Propagation:

Events in the DOM can propagate in two phases: capturing phase and bubbling phase.
The default behavior is the bubbling phase, where the event starts at the target
element and bubbles up the DOM tree to the root. You can control the event
propagation using the stopPropagation method.

6. Event Delegation:

Event delegation is a technique where you attach a single event listener to a common
ancestor of multiple elements. This is particularly useful for handling events on
dynamically generated elements or a large number of elements efficiently.

document.getElementById("parentElement").addEventListener("click",
function(event) {
if (event.target.classList.contains("dynamicElement")) {
// Event handling for dynamically generated elements
}
});

7. Event Handlers and Best Practices:

o Keep event handlers simple and focused on a single task.


o Use separate functions for event handlers to improve code readability.
o Ensure your event handlers are properly removed when no longer needed to
avoid memory leaks.
o Avoid using inline event attributes (e.g., <button
onclick="myFunction()">) for better separation of concerns.

Here is a simple example demonstrating event handling in HTML and JavaScript:

<!DOCTYPE html>
<html>
<body>
<button id="myButton">Click Me</button>
<script>
const button = document.getElementById("myButton");

function handleClick(event) {
console.log("Button clicked!");
// Access event properties, e.g., event.target, event.type
}

button.addEventListener("click", handleClick);
</script>
</body>
</html>

This example adds a click event listener to a button, which calls the handleClick
function when the button is clicked. Understanding event handling is crucial for
creating interactive and responsive web applications.

Attempt Quiz → Click Here

Assignment Question:

10. Create an HTML file with a button element with the id "myButton" and text
"Click Me."
11. In the same HTML file, add a script tag to write JavaScript code.
12. Use JavaScript to add an event listener to the button so that when it's clicked, a
function called handleButtonClick is executed.
13. In the handleButtonClick function, log the message "Button clicked!" to the
console.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)
 JS Promises

Watch Tutorial → Click Here

What is a Promise?

In JavaScript, a Promise is an object that represents the eventual completion or failure


of an asynchronous operation and its resulting value. It's a way to handle
asynchronous code in a more structured and readable manner.

Basic Structure of a Promise:

A Promise has three states:

0. Pending: Initial state, before the Promise is resolved or rejected.


1. Fulfilled (Resolved): The operation completed successfully, and the Promise
has a resulting value.
2. Rejected: The operation failed, and the Promise has a reason for the failure.

Creating a Promise:
// Example of a Promise
let myPromise = new Promise((resolve, reject) => {
// Asynchronous operation (e.g., fetching data, reading a file)
let operationSuccessful = true; // Set to false for demonstration
purposes

if (operationSuccessful) {
// If successful, call 'resolve' with the result
resolve("Operation completed successfully!");
} else {
// If failed, call 'reject' with the reason
reject("Operation failed!");
}
});

Handling a Promise:
// Handling the Promise
myPromise
.then((result) => {
// This block is executed if the Promise is resolved
console.log("Success:", result);
})
.catch((reason) => {
// This block is executed if the Promise is rejected
console.error("Error:", reason);
});

Chaining Promises:
// Chaining Promises
let anotherPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Second operation completed successfully!");
}, 2000);
});

myPromise
.then((result) => {
console.log("First Promise:", result);
return anotherPromise; // Returning a new Promise for chaining
})
.then((result) => {
console.log("Second Promise:", result);
})
.catch((reason) => {
console.error("Error:", reason);
});

Explanation:

3. Promise Creation: You create a Promise using the new Promise syntax.
Inside the Promise constructor, you perform some asynchronous operation,
and based on its result, you call either resolve (if successful) or reject (if
there's an error).
4. Promise Handling: You handle the result of a Promise using the .then()
method. If the Promise is resolved, the code inside the then block is executed.
If there's an error (Promise rejected), the code inside the .catch() block is
executed.
5. Chaining Promises: You can chain multiple Promises using the .then()
method. This is useful when you have sequential asynchronous operations.

Remember, the primary benefit of Promises is to simplify the handling of


asynchronous code, making it more readable and manageable. Promises are
fundamental in modern JavaScript, especially when dealing with tasks like fetching
data from a server or reading files.

Attempt Quiz → Click Here

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Async/Await

Watch Tutorial → Click Here

Basic Example without async/await:

Let's first look at a simple asynchronous code example without using async/await:

// Asynchronous function without async/await


function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = "Async data fetched!";
resolve(data);
}, 2000);
});
}

// Using the asynchronous function


fetchData()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
});

The Same Example with async/await:

Now, let's rewrite the same example using async/await:

// Asynchronous function with async/await


async function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
const data = "Async data fetched!";
resolve(data);
}, 2000);
});
}

// Using the asynchronous function with async/await


async function fetchDataAndLog() {
try {
const result = await fetchData();
console.log(result);
} catch (error) {
console.error(error);
}
}

// Call the function


fetchDataAndLog();

Explanation:

0. async Function:
 The async keyword is used before a function declaration to indicate
that the function will work with promises and will implicitly return a
promise.
1. await Keyword:
 Inside an async function, the await keyword is used to pause the
execution of the function until the promise is resolved. It's like saying,
"Wait for this promise to settle, and then continue."
2. Error Handling with try and catch:

We use try and catch to handle errors. If a promise is rejected, it will
throw an error, and we can catch and handle it in the catch block.
3. Simplified Code:
 Using async/await makes the code more straightforward and
resembles synchronous code, making it easier to understand, especially
when dealing with multiple asynchronous operations.

Using async/await is particularly helpful when dealing with more complex


asynchronous workflows, such as making multiple asynchronous calls sequentially.

In summary, async/await is a syntactic sugar that simplifies the handling of


promises, making asynchronous code more readable and concise.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Weather Website

Watch Tutorial → Click Here

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Air Quality Checker</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
background-color: #87CEEB; /* Sky Blue */
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-
serif;
}

h1 {
text-align: center;
color: #fff; /* White */
margin-bottom: 20px;
}

#input-container {
text-align: center;
margin-top: 20px;
}

label {
display: block;
margin-bottom: 5px;
color: #fff; /* White */
}

input {
padding: 10px;
margin-bottom: 15px;
width: 200px;
border: 1px solid #fff; /* White */
border-radius: 5px;
font-size: 16px;
box-sizing: border-box;
}

button {
padding: 12px 20px;
background-color: #4CAF50; /* Green */
color: #fff; /* White */
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}

button:hover {
background-color: #45a049;
}
.info {
text-align: center;
background-color: #fff; /* White */
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* Soft Box
Shadow */
margin-top: 20px;
display: none;
flex-direction: column;
}

.info-title {
color: #333; /* Dark Gray */
margin-bottom: 20px;
}

.info-data {
margin: 8px 0;
color: #555; /* Medium Gray */
font-size: 20px;
}
</style>
</head>
<body>

<h1>Air Quality Checker</h1>

<div id="input-container">
<form id="form">
<label for="latitude">Latitude:</label>
<input type="text" id="latitude" placeholder="Enter
Latitude">

<label for="longitude">Longitude:</label>
<input type="text" id="longitude" placeholder="Enter
Longitude">
<br>

<button type="submit">Check Air Quality</button>


</form>
<div class="info" id="result">
<h1 class="info-title">AIR QUALITY</h1>
<p class="info-data">AQI: <span id="aqi"></span></p>
<p class="info-data">CO: <span id="co"></span></p>
<p class="info-data">NO2: <span id="no2"></span></p>
<p class="info-data">O3: <span id="o3"></span></p>
<p class="info-data">PM2.5: <span id="pm2"></span></p>
<p class="info-data">PM10: <span id="pm10"></span></p>
<p class="info-data">SO2: <span id="so2"></span></p>
</div>
</div>
</div>

<script src="index.js">
</script>

</body>
</html>

index.js:

const form = document.getElementById("form");


const latitudeInput = document.getElementById("latitude");
const longitudeInput = document.getElementById("longitude");
const resultContainer = document.getElementById("result");
const aqiResult = document.getElementById("aqi");
const coResult = document.getElementById("co");
const no2Result = document.getElementById("no2");
const o3Result = document.getElementById("o3");
const pm2Result = document.getElementById("pm2");
const pm10Result = document.getElementById("pm10");
const so2Result = document.getElementById("so2");

form.addEventListener("submit",(event)=>{
event.preventDefault();
const latitude = latitudeInput.value;
const longitude = longitudeInput.value;
const url = `https://air-
quality.p.rapidapi.com/history/airquality?lon=${longitude}&lat=${lati
tude}`;
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': 'Key here',
'X-RapidAPI-Host': 'Host here'
}
};
fetch(url,options)
.then(response=>response.json())
.then(result=>{
let readings = result.data[0];
console.log(readings);
aqiResult.textContent=readings.aqi;
coResult.textContent=readings.co;
no2Result.textContent=readings.no2;
pm2Result.textContent=readings.pm2;
o3Result.textContent=readings.o3;
pm10Result.textContent=readings.pm10;
so2Result.textContent=readings.so2;
resultContainer.style.display = 'flex';
})
});

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 NodeJS Introduction

Watch Tutorial → Click Here

Node.js:

Node.js is a JavaScript runtime built on the V8 JavaScript engine. It allows you to run
JavaScript on the server side, enabling the development of scalable and high-
performance web applications. Node.js comes with a package manager called npm
(Node Package Manager) that allows you to easily install and manage third-party
libraries.

Node.js is designed to execute JavaScript code outside of a browser environment. It


allows developers to build server-side applications using JavaScript. It provides a set
of APIs for interacting with the file system, networking, and other system-level
functionality.

Node.js Installation:

0. Visit the Official Node.js Website:


 Go to Node.js official website.
1. Download Node.js:
 On the homepage, you'll see two versions: "LTS" (Long Term
Support) and "Current." For most users, it's recommended to download
the LTS version.
 Click on the "LTS" button or the version you prefer.
2. Windows:
 For Windows, the installer is an MSI package.
 Download the installer, and double-click to run it.
 Follow the installation wizard, ensuring that the "npm package
manager" option is selected.
 Complete the installation.
3. macOS:
 For macOS, you can download a macOS Installer (.pkg).
 Download the installer and double-click to run it.
 Follow the installation instructions.
4. Linux (Debian/Ubuntu):
 For Linux, download the "Linux Binaries" (tar.gz) from the website.
 Open a terminal and navigate to the directory where the tarball was
downloaded.
 Extract the tarball with the following command:
 tar -xvf node-<version>-linux-x64.tar.gz

 Move the extracted files to the appropriate directory:
 sudo cp -r node-<version>-linux-x64/* /usr/local/

 Verify the installation with:
 node -v
 npm -v

5. Other Linux Distributions:
 For other Linux distributions, you can use the package manager.
 Follow the specific instructions for your distribution on the
NodeSource distribution page.
6. Verification:
 After installation, open a terminal (or command prompt on Windows)
and run the following commands to verify Node.js and npm
installation:
 node -v
 npm -v

 You should see version numbers for Node.js and npm, indicating a
successful installation.

Now, you have Node.js and npm installed on your system, and you can start
developing JavaScript applications. If you encounter any issues during installation,
refer to the official documentation or community forums for assistance.

Node REPL (Read-Eval-Print Loop):

The Node REPL is an interactive shell that allows you to run JavaScript code line by
line. It's a great tool for testing code snippets and exploring JavaScript features.

To launch the Node REPL, open your terminal and type node. You'll see a prompt (>)
where you can enter JavaScript code.

// Node REPL
> let greeting = 'Hello, Node.js!';
undefined

> console.log(greeting);
Hello, Node.js!
undefined

Node CLI (Command Line Interface):

Node.js also provides a command-line interface that allows you to run JavaScript files
from the terminal. You can create and execute JavaScript files using the node
command.
Basic Code Snippet (in a file, e.g., app.js):
// app.js
const greeting = 'Hello, Node.js!';
console.log(greeting);

To run the file from the terminal:

$ node app.js
Hello, Node.js!

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Exploring NodeJS

Watch Tutorial → Click Here

Built-in Node.js Modules:

Node.js comes with a set of built-in modules that provide various functionalities. Here
are explanations for a few of them with code snippets:

1. fs Module (File System):

o The fs module provides an API for interacting with the file system.

const fs = require('fs');

// Reading a file asynchronously


fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});

// Writing to a file asynchronously


fs.writeFile('newFile.txt', 'Hello, Node.js!', (err) => {
if (err) {
console.error(err);
return;
}
console.log('File written successfully.');
});

2. http Module (HTTP Server):

o The http module allows you to create HTTP servers and make HTTP
requests.
const http = require('http');

const server = http.createServer((req, res) => {


res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Node.js!');
});

const port = 3000;


server.listen(port, () => {
console.log(`Server running at <http://localhost>:${port}/`);
});

3. path Module (Path Operations):

o The path module provides utilities for working with file and directory paths.

const path = require('path');

const filePath = '/path/to/some/file.txt';

// Extracting the directory name


const dirname = path.dirname(filePath);
console.log('Directory:', dirname);

// Extracting the file name


const basename = path.basename(filePath);
console.log('File Name:', basename);

// Joining paths
const fullPath = path.join(__dirname, 'files', 'example.txt');
console.log('Full Path:', fullPath);

Node Package Manager (npm):

npm is the package manager for Node.js. It allows you to easily manage and install
third-party libraries and tools for your Node.js projects.

npm Commands and Code Snippets:

1. Initializing a Project:

o To initialize a new Node.js project and create a package.json file:

npm init

2. Installing Packages:

o To install a package and save it as a dependency:

npm install package-name

o To install a package and save it as a development dependency:


npm install package-name --save-dev

3. Listing Installed Packages:

o To list the installed packages in your project:

npm ls

4. Running Scripts:

o Add scripts to the scripts section in package.json and run them:

"scripts": {
"start": "node app.js",
"test": "mocha"
}

Run scripts using:

npm run start

5. Updating Packages:

o To update a package to its latest version:

npm update package-name

6. Uninstalling Packages:

o To uninstall a package:

npm uninstall package-name

These are just a few examples, and there are many more npm commands and use
cases. npm is a powerful tool for managing dependencies and scripts in your Node.js
projects. For more details, refer to the official npm documentation.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 date-fns Package

Watch Tutorial → Click Here

date-fns:
date-fns is a popular JavaScript library for working with dates. It provides a set of
functions that are designed to be simple and consistent for parsing, formatting, and
manipulating dates. Here's an overview of some of the key features of date-fns
along with code examples:

Installation:

First, you need to install the date-fns package. You can do this using npm:

npm install date-fns

Basic Usage:

1. Parsing and Formatting Dates:


// Importing the necessary functions
const { format, parseISO } = require('date-fns');

// Parsing a date string


const parsedDate = parseISO('2023-11-11T12:30:00');

// Formatting the parsed date


const formattedDate = format(parsedDate, 'yyyy-MM-dd HH:mm:ss');
console.log(formattedDate);

2. Adding and Subtracting Time:


const { addDays, subMonths } = require('date-fns');

const currentDate = new Date();

// Adding 5 days to the current date


const futureDate = addDays(currentDate, 5);

// Subtracting 2 months from the current date


const pastDate = subMonths(currentDate, 2);

console.log('Future Date:', futureDate);


console.log('Past Date:', pastDate);

3. Difference between Dates:


const { differenceInDays, differenceInHours } = require('date-fns');

const startDate = new Date('2023-11-01');


const endDate = new Date('2023-11-11T12:30:00');

// Difference in days between two dates


const daysDifference = differenceInDays(endDate, startDate);

// Difference in hours between two dates


const hoursDifference = differenceInHours(endDate, startDate);
console.log('Days Difference:', daysDifference);
console.log('Hours Difference:', hoursDifference);

Note:

o date-fns uses a functional approach and provides pure functions that do not
modify the original date objects.
o The library is modular, so you can import only the functions you need to keep
the bundle size smaller.
o It works both in the browser and in Node.js environments.

This is just a brief introduction to some of the features of date-fns. The library offers
a wide range of functions for various date-related operations. For detailed information
and additional functions, refer to the official documentation: date-fns Documentation.

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 ExpressJS Introduction

Watch Tutorial → Click Here

Express.js Introduction:

Express.js is a minimal and flexible Node.js web application framework that provides
a robust set of features to develop web and mobile applications. It simplifies the
process of building scalable and maintainable web applications by providing a fast,
unopinionated, and minimalist framework.

Key features of Express.js include:

0. Routing: Easily define routes to handle HTTP methods and URLs.


1. Middleware: Use middleware functions to perform tasks before or after the
request is handled.
2. Templating Engines: Support for various templating engines, or you can use
front-end frameworks.
3. HTTP Utility Methods and Middleware: Simplifies handling HTTP
requests and responses.
4. Database Integration: Works well with databases such as MongoDB,
MySQL, and more.
5. Error Handling: Built-in error handling and support for custom error
handling.

Installation:

Before using Express.js, you need to have Node.js installed on your system. Once
Node.js is installed, you can create a new project and install Express using npm (Node
Package Manager):
mkdir my-express-app
cd my-express-app
npm init -y
npm install express

Basic Example:

Let's create a simple Express.js application that responds with "Hello, Express!" when
you access the root URL.

Create a file named app.js:

// Import the Express module


const express = require('express');

// Create an instance of the Express application


const app = express();

// Define a route handler for the root URL


app.get('/', (req, res) => {
res.send('Hello, Express!');
});

// Set the server to listen on port 3000


const port = 3000;
app.listen(port, () => {
console.log(`Server is running on <http://localhost>:${port}`);
});

Save the file and run the application:

node app.js

Visit http://localhost:3000 in your browser, and you should see "Hello, Express!".

This is a basic introduction to Express.js. As you delve deeper into building


applications, you'll discover more advanced features and practices that make
Express.js a powerful framework for web development.

Nodemon:

nodemon is a utility for Node.js that monitors for changes in your source code and
automatically restarts your server when changes are detected. This is particularly
useful during development, as it saves you from manually stopping and restarting
your server every time you make changes to your code.

Here are some key points and usage notes for nodemon:

6. Installation: You can install nodemon globally using npm:


7. npm install -g nodemon
8.
9. Usage: After installation, you can use nodemon in place of node to run your
scripts. Instead of running:
10. node your_script.js
11.

You can run:

nodemon your_script.js

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 Handling HTTP Requests

Watch Tutorial → Click Here

Express.js simplifies handling HTTP requests in Node.js by providing a clean and


organized way to define routes and middleware. It supports various HTTP methods
(GET, POST, PUT, DELETE, etc.) and allows you to handle parameters, query
strings, request bodies, and more. Let's explore HTTP requests in Express with code
examples.

Curl:

Client URL (cURL) lets you exchange data between your device and a server
through a command-line interface (CLI).

Handling GET Requests:

Handling a GET request involves defining a route using app.get().

const express = require('express');


const app = express();
const port = 3000;

// Handling a GET request for the root URL


app.get('/', (req, res) => {
res.send('Hello, GET request!');
});

// Handling a GET request for /about


app.get('/about', (req, res) => {
res.send('About Us');
});

app.listen(port, () => {
console.log(`Server is running on <http://localhost>:${port}`);
});

Handling POST Requests:


To handle a POST request, use app.post().

const express = require('express');


const bodyParser = require('body-parser');
const app = express();
const port = 3000;

// Parse incoming JSON requests


app.use(bodyParser.json());

// Handling a POST request for /submit


app.post('/submit', (req, res) => {
const data = req.body;
res.json({ message: 'Data received successfully', data });
});

app.listen(port, () => {
console.log(`Server is running on <http://localhost>:${port}`);
});

In this example, the body-parser middleware is used to parse JSON requests. The
data sent in the POST request is accessible through req.body.

Test Code:

curl -X POST -H "Content-Type: application/json" -d '{"key":


"value"}' <http://localhost:3000/submit>

Handling URL Parameters:

You can extract parameters from the URL using :paramName in the route definition.

const express = require('express');


const app = express();
const port = 3000;

// Handling a GET request with a URL parameter


app.get('/users/:userId', (req, res) => {
const userId = req.params.userId;
res.send(`User ID: ${userId}`);
});

app.listen(port, () => {
console.log(`Server is running on <http://localhost>:${port}`);
});

A request to /users/123 will set req.params.userId to '123'.

Test Code:

curl <http://localhost:3000/users/123>

Handling Query Parameters:


Query parameters can be accessed using req.query.

const express = require('express');


const app = express();
const port = 3000;

// Handling a GET request with query parameters


app.get('/search', (req, res) => {
const searchTerm = req.query.q;
res.send(`Search Query: ${searchTerm}`);
});

app.listen(port, () => {
console.log(`Server is running on <http://localhost>:${port}`);
});

A request to /search?q=node will set req.query.q to 'node'.

Test Code:

curl "<http://localhost:3000/search?q=your_search_term>"

Redirects and Status Codes:

You can perform redirects and set specific HTTP status codes in your route handlers.

const express = require('express');


const app = express();
const port = 3000;

// Redirecting to another URL


app.get('/redirect', (req, res) => {
res.redirect('<https://www.example.com>');
});

// Setting a custom status code


app.get('/notfound', (req, res) => {
res.status(404).send('Not Found');
});

app.listen(port, () => {
console.log(`Server is running on <http://localhost>:${port}`);
});

Express provides a robust and flexible framework for handling various aspects of
HTTP requests. As your application grows, you may explore more advanced features
like route parameters, query parameters, and middleware to build powerful and
scalable APIs or web applications.

Test Code:

curl -L <http://localhost:3000/redirect>
curl -I <http://localhost:3000/notfound>
Congrats Mowa Successful ga complete chesnav! Next session lo
kaluddam :)

 Middleware and Authentication using ExpressJS

Watch Tutorial → Click Here

Middleware:
const express = require('express');
const app = express();

// Middleware function 1
app.use((req, res, next) => {
console.log('Middleware 1 executed');
// Modify the request or response objects if needed
req.customProperty = 'Hello from middleware 1';
next(); // Pass control to the next middleware
});

// Middleware function 2
app.use((req, res, next) => {
console.log('Middleware 2 executed');
// Access the modified request object from previous middleware
console.log(req.customProperty);
next(); // Pass control to the next middleware
});

// Route handler
app.get('/', (req, res) => {
res.send('Hello, Express!');
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});

Authentication:
const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

const app = express();


const PORT = 3000;

app.use(bodyParser.urlencoded({ extended: true }));


app.use(bodyParser.json());

// Dummy database (for demo purposes, replace with a real database)


const users = [];
const secretKey = 'your-secret-key';

// Routes
app.get('/', (req, res) => {
res.send('Welcome to the authentication app!');
});
app.post('/login', (req, res) => {
const { username, password } = req.body;

// Find user by username (replace with database query)


const user = users.find((user) => user.username === username);

if (user && bcrypt.compareSync(password, user.password)) {


// Generate a JWT token
const token = jwt.sign({ username: user.username }, secretKey, {
expiresIn: '1h' });

res.json({ token });


} else {
res.status(401).json({ message: 'Invalid username or password.'
});
}
});

app.post('/register', (req, res) => {


const { username, password } = req.body;

// Check if username already exists (replace with database query)


const existingUser = users.find((user) => user.username ===
username);

if (existingUser) {
res.status(400).json({ message: 'Username already exists. Choose
another one.' });
} else {
// Hash the password before storing (using bcrypt)
const hashedPassword = bcrypt.hashSync(password, 10);

// Store the user (replace with database insert)


users.push({ username, password: hashedPassword });

res.json({ message: 'Registration successful!' });


}
});

// Protected route
app.get('/protected', verifyToken, (req, res) => {
res.json({ message: 'You have access to this protected route!' });
});

// Middleware to verify JWT token


function verifyToken(req, res, next) {
const token = req.headers['authorization'];

if (!token) {
return res.status(403).json({ message: 'No token provided.' });
}

jwt.verify(token, secretKey, (err, decoded) => {


if (err) {
return res.status(401).json({ message: 'Failed to authenticate
token.' });
}

req.user = decoded;
next();
});
}

app.listen(PORT, () => {
console.log(`Server is running on <http://localhost>:${PORT}`);
});

Congrats Mowa Successful ga complete chesnav! Next session lo


kaluddam :)

 ReactJS in 46 Min

Watch Tutorial → Click Here

Introduction to React JS

o JavaScript library for building user interfaces: React is a powerful tool for
creating dynamic and interactive web applications. It focuses on building
reusable components that manage their own state and render efficiently.
o Declarative approach: You describe the desired UI state, and React handles
the updates efficiently, making it easier to reason about and maintain your
code.
o JSX syntax: React uses a syntax extension for JavaScript called JSX, which
allows you to write HTML-like structures within your JavaScript code.
o Virtual DOM: React maintains a virtual representation of the UI in
memory, which it compares to the previous version to determine the minimal
changes needed for updates. This makes updates fast and efficient.

Basic Concepts:

o Components: The building blocks of React applications. They are reusable


pieces of UI that can be composed together to create complex interfaces.
o Props: Data passed from parent components to child components to configure
their appearance and behavior.
o State: Internal data managed by a component that can change over
time, triggering re-renders to reflect updates in the UI.

Hello World in React:

1. Create an HTML file (index.html):

<!DOCTYPE html>
<html>
<head>
<title>Hello React</title>
<script
src="<https://unpkg.com/react@18/umd/react.development.js>"
crossorigin></script><script
src="<https://unpkg.com/react-dom@18/umd/react-dom.development.js>"
crossorigin></script></head><body><div
id="root"></div><script
src="script.js"></script></body></html>
2. Create a JavaScript file (script.js):

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<h1>Hello, world!</h1>);

Explanation:

o Import React and ReactDOM: These libraries are necessary for working
with React.
o Create a root element: The createRoot method attaches React to a DOM
element (#root).
o Render a component: The root.render method renders a React
component, in this case, an <h1> element with the text "Hello, world!".

Notes:

o JSX syntax: Note the use of JSX to write HTML-like code within JavaScript.
o Development vs. production: The included script URLs are for development
purposes. For production, use optimized builds.
o Setting up React projects: For larger projects, consider using tools like
Create React App to streamline setup and development.

Key Points:

o React excels at building complex and interactive user interfaces efficiently.


o Components, props, and state are core concepts to grasp for effective React
development.
o The Hello World example demonstrates the basic structure of a React
application.
o Explore further to learn about state management, event handling, lifecycle
methods, and other essential React features.

Installing React and Basic Folder Structure

1. Prerequisites:

o Node.js (version 14 or later) and npm (or yarn) installed on your system.

2. Installing React:

o Using Create React App (recommended):


o npx create-react-app my-app
o cd my-app
o npm start
o

This sets up a pre-configured development environment with tools for building


and testing.

o Manual Setup (for specific needs):


o npm install react react-dom
o

Requires manual configuration of tools and build processes.

3. Basic Folder Structure (Create React App):

o public: Contains static assets like images, favicons, and the index.html file.
o src: Holds the source code of your React application.
 App.js: The main component, usually the entry point.
 index.js: Renders App component into the root DOM element.
 components: Stores reusable React components.
 styles: Houses CSS or stylesheet files.
 assets: Holds additional static assets (images, fonts, etc.).
o package.json: Lists project dependencies and scripts for development and
building.

Create React App Benefits:

o Streamlines setup and configuration.


o Offers hot reloading for fast development feedback.
o Handles build and optimization for production.
o Provides testing setup (Jest and React Testing Library).

JSX (JavaScript XML)

o Syntax extension for JavaScript that allows writing HTML-like structures


within JavaScript code.
o Not a separate language: Transforms into plain JavaScript objects during
compilation.
o Purpose: Streamlines UI creation in React, making it more intuitive and
readable.

Key Concepts:

36. Basic Structure:


37. return <h1>Hello, World!</h1>;
38.
39. Attributes:
40. <h1 className="header" style={{ color: "red" }}>Red
Heading</h1>
41.
42. Embedding Expressions and Variables:
43. const name = "John";
44. const age = 30;
45. return (
46. <p>Hello, {name}! You are {age} years old.</p>
47. );
48.
49. Nesting and Self-Closing Elements:
50. return (
51. <div>
52. <h1>My List</h1>
53. <ul>
54. <li>Item 1</li>
55. <li>Item 2</li>
56. </ul>
57. </div>
58. <img src="logo.jpg" alt="Logo" />
59. );
60.
61. Loops:
62. const items = ["apple", "banana", "orange"];
63. return (
64. <ul>
65. {items.map((item) => (
66. <li key={item}>{item}</li>
67. ))}
68. </ul>
69. );

Components

Building Blocks of React Apps:

o Reusable UI elements that encapsulate their own logic and rendering.


o Promote modularity, maintainability, and code organization.
o Can be nested to create complex UIs from smaller, simpler parts.

Types:

o Functional Components: Simple JavaScript functions that take props and


return JSX.
o Class Components: More complex, with state and lifecycle methods.

Example (Functional Component):

function Greeting({ name }) {


return <h1>Hello, {name}!</h1>;
}

import React from 'react';


import Greeting from './Greeting'; // Assuming Greeting is in a
separate file

function App() {
const userName = 'John';

return (
<div>
<Greeting name={userName} />
</div>
);
}

export default App;

Example (Class Component):


class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}

handleClick = () => {
this.setState({ count: this.state.count + 1 });
};

render() {
return (
<div><p>You clicked {this.state.count} times</p><button
onClick={this.handleClick}>Click me</button></div>
);
}
}

Props

Passing Data to Components:

o Customizable properties that allow parent components to pass data to child


components.
o Data flows in one direction, from parent to child.
o Ensures consistent data flow and decoupling of components.

Key Points:

o Defined as attributes on the component tag.


o Can be of any data type (strings, numbers, objects, arrays, functions).
o Dynamically change the behavior and appearance of components.

Example:

function WelcomeMessage({ title, message }) {


return (
<div>
<h1>{title}</h1>
<p>{message}</p>
</div>
);
}

// Usage:
<WelcomeMessage title="Welcome to React" message="Let's get started!"
/>

Additional Notes:

o Use defaultProps to set default values for props when not provided.
o Use PropTypes for type checking and validation of props.
o Props are immutable within child components; use state for internal data
management.

Conditional Rendering

1. Using an If...Else Statement:


import React, { Component } from 'react';

class IfElseExample extends Component {


constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
};
}

render() {
if (this.state.isLoggedIn) {
return (
<div>
<p>Welcome, User!</p>
</div>
);
} else {
return (
<div>
<p>Please log in</p>
</div>
);
}
}
}

export default IfElseExample;

2. Using Element Variables:


import React, { Component } from 'react';

class ElementVariablesExample extends Component {


constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
};
}

render() {
let content;
if (this.state.isLoggedIn) {
content = <p>Welcome, User!</p>;
} else {
content = <p>Please log in</p>;
}

return <div>{content}</div>;
}
}

export default ElementVariablesExample;

3. Using Ternary Operators:


import React, { Component } from 'react';

class TernaryOperatorExample extends Component {


constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
};
}

render() {
return (
<div>
{this.state.isLoggedIn ? (
<p>Welcome, User!</p>
) : (
<p>Please log in</p>
)}
</div>
);
}
}

export default TernaryOperatorExample;

4. Using Logical && Operator:


import React, { Component } from 'react';

class LogicalAndOperatorExample extends Component {


constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
};
}

render() {
return (
<div>
{this.state.isLoggedIn && <p>Welcome, User!</p>}
{!this.state.isLoggedIn && <p>Please log in</p>}
</div>
);
}
}

export default LogicalAndOperatorExample;


Example:

import React, { Component } from 'react';

class ConditionalRenderingExample extends Component {


constructor(props) {
super(props);
this.state = {
isLoggedIn: false, // Initial state for login status
};
}

// Function to toggle login status


toggleLoginStatus = () => {
this.setState((prevState) => ({
isLoggedIn: !prevState.isLoggedIn,
}));
};

render() {
return (
<div>
<h1>Conditional Rendering Example</h1>
{this.state.isLoggedIn ? (
<div>
<p>Welcome, User!</p>
<button onClick={this.toggleLoginStatus}>Logout</button>
</div>
) : (
<div>
<p>Please log in</p>
<button onClick={this.toggleLoginStatus}>Login</button>
</div>
)}
</div>
);
}
}

export default ConditionalRenderingExample;

In this example:

o The component has a state variable isLoggedIn to track whether the user is
logged in or not.
o The toggleLoginStatus function is responsible for toggling the isLoggedIn
state.
o The render method contains conditional statements that check the
isLoggedIn state. Depending on the state, it renders different content.

The buttons allow the user to toggle the login status, triggering a re-render with the
updated state and, consequently, conditional rendering.

State and Life Cycle Methods → Refer Here

Handling Events → Refer Here


Styled Components

Styled Components is a popular library for styling React components using tagged
template literals. It allows you to write CSS in JavaScript, keeping styles encapsulated
within your components. Here's a brief explanation with example code snippets:

87. Installation: First, install the Styled Components library in your React
project:
88. npm install styled-components
89.
90. Usage: Import styled from the styled-components library, and use it to
create styled components.
91. // ExampleComponent.js
92.
93. import styled from 'styled-components';
94.
95. // Create a styled component
96. const StyledDiv = styled.div`
97. background-color: lightblue;
98. padding: 10px;
99. margin: 10px;
100. `;
101.
102. // Use the styled component in your React component
103. const ExampleComponent = () => {
104. return (
105. <StyledDiv>
106. <h1>Hello, Styled Components!</h1>
107. </StyledDiv>
108. );
109. };
110.
111. export default ExampleComponent;
112.

In this example, we created a StyledDiv component with specified CSS


styles. Then, we used it within the ExampleComponent.

113. Dynamic Styles: Styled Components allows dynamic styles using


JavaScript expressions within template literals.
114. // DynamicStyledComponent.js
115.
116. import styled from 'styled-components';
117.
118. // Create a styled component with dynamic styles
119. const DynamicStyledDiv = styled.div`
120. background-color: ${(props) => (props.isPrimary ?
'lightblue' : 'lightgreen')};
121. padding: 10px;
122. margin: 10px;
123. `;
124.
125. // Use the styled component with dynamic styles
126. const DynamicComponent = ({ isPrimary }) => {
127. return (
128. <DynamicStyledDiv isPrimary={isPrimary}>
129. <h1>Hello, Dynamic Styled Components!</h1>
130. </DynamicStyledDiv>
131. );
132. };
133.
134. export default DynamicComponent;
135.

Here, the DynamicStyledDiv component takes a prop isPrimary and changes


its background color dynamically based on the prop value.

136. Global Styles: Styled Components also allows you to define global
styles using the createGlobalStyle utility.
137. // GlobalStyles.js
138.
139. import { createGlobalStyle } from 'styled-components';
140.
141. // Define global styles
142. const GlobalStyles = createGlobalStyle`
143. body {
144. font-family: 'Arial', sans-serif;
145. background-color: #f0f0f0;
146. }
147. `;
148.
149. export default GlobalStyles;
150.

Import the GlobalStyles component in your main file (e.g., App.js) to apply
global styles to your entire application.

// App.js

import React from 'react';


import GlobalStyles from './GlobalStyles';
import ExampleComponent from './ExampleComponent';
import DynamicComponent from './DynamicStyledComponent';

const App = () => {


return (
<>
<GlobalStyles />
<ExampleComponent />
<DynamicComponent isPrimary={true} />
</>
);
};

export default App;

In this example, the GlobalStyles component sets global styles for the body
element.

Styled Components is a powerful tool for styling React components in a more


maintainable and encapsulated way.
Congrats Mowa Successful ga complete chesnav! Next session lo
kaluddam :)

 MongoDB

Watch Tutorial → Click Here

Introduction to MongoDB:

MongoDB is a popular open-source, document-oriented NoSQL database system. It is


designed to store and manage large volumes of data in a highly flexible and scalable
manner. MongoDB stores data in flexible, JSON-like documents, making it easy to
work with for developers. MongoDB uses a flexible schema, which allows for easy
evolution of data models over time.

Types of Databases:

0. Relational Databases: Traditional relational databases organize data into


tables with rows and columns, enforcing a strict schema. Examples include
MySQL, PostgreSQL, and Oracle.
1. Non-Relational Databases (NoSQL): NoSQL databases come in various
forms, including document-oriented, key-value stores, column-family stores,
and graph databases. These databases are designed to handle large volumes of
unstructured or semi-structured data and provide more flexibility than
relational databases. Examples include MongoDB, Cassandra, Redis, and
Neo4j.

Non-Relational Databases:

Non-relational databases, also known as NoSQL databases, are a category of


databases that do not follow the traditional relational database model. Instead, they
provide mechanisms for storage and retrieval of data that are less constrained than the
tabular relations used in relational databases.

Some key characteristics of non-relational databases include:

o Schema flexibility: Non-relational databases often allow for dynamic and


flexible schemas, making it easier to adapt to changing data structures.
o Scalability: NoSQL databases are often designed to scale horizontally,
allowing them to handle large volumes of data and high levels of traffic more
efficiently.
o Performance: Non-relational databases can offer improved performance for
certain use cases, especially those involving large-scale data processing and
distributed systems.
o Distributed architecture: Many NoSQL databases are designed with
distributed architectures that enable them to run across multiple nodes and
data centers, providing resilience and fault tolerance.

Why MongoDB:
MongoDB offers several advantages that make it a popular choice for developers and
organizations:

6. Flexible Schema: MongoDB's flexible document-based data model allows for


easy schema evolution, making it well-suited for agile development practices.
7. Scalability: MongoDB can scale horizontally across multiple servers,
allowing it to handle large volumes of data and high levels of traffic.
8. High Performance: MongoDB's architecture is optimized for high
performance, with features such as in-memory caching and support for
sharding.
9. Rich Query Language: MongoDB supports a powerful query language that
allows for complex queries, including ad-hoc queries, range queries, and
geospatial queries.
10. Rich Ecosystem: MongoDB has a large and active community, along with
extensive documentation, tutorials, and support resources.

Differences Between Relational Databases and MongoDB:

11. Data Model:


 Relational databases use a tabular data model with predefined schemas,
while MongoDB uses a flexible document-based data model.
12. Schema:
 Relational databases enforce a rigid schema where data must fit into
predefined tables and columns, while MongoDB allows for dynamic
and evolving schemas.
13. Transactions:
 Relational databases typically support ACID (Atomicity, Consistency,
Isolation, Durability) transactions, while MongoDB supports atomic
operations on a single document but does not provide multi-document
transactions in a single operation (although multi-document
transactions are supported across multiple operations in recent
versions).
14. Scaling:
 Relational databases often scale vertically by adding more resources to
a single server, while MongoDB scales horizontally by distributing
data across multiple servers.
15. Query Language:
 Relational databases use SQL (Structured Query Language) for
querying data, while MongoDB uses a JSON-like query language.
16. Joins:
 Relational databases rely heavily on joins to combine data from
multiple tables, while MongoDB encourages denormalization and
embedding data within documents to reduce the need for joins.
17. Complexity:
 Relational databases tend to have a higher initial setup and
maintenance complexity due to rigid schemas and complex SQL
queries, while MongoDB's flexible schema and simpler query language
can reduce development and maintenance overhead.

Installation (Windows):

Prerequisites:

o A Windows operating system (10 or 11 recommended)


o Administrator privileges on your machine

Installation Steps:

20. Download the MongoDB Shell Installer:


 Visit the official MongoDB download page: [download mongodb shell
ON mongodb.com]
 Select your desired version (it's generally recommended to choose the
latest stable version).
 Under "Platform," choose "Windows."
 Click the "Download" button.
21. Run the Installer:
 Locate the downloaded installer file (usually named mongosh-*.msi)
in your Downloads folder or wherever you saved it.
 Double-click the installer to launch it.
 Follow the on-screen instructions during the installation process. You
can typically accept the default settings.
22. Optional: Add mongosh to PATH (for command-line access from
anywhere):
 This step is optional but highly recommended for convenient use
of mongosh from any command prompt window.
 Press the Windows key + R to open the Run dialog.
 Type sysdm.cpl and press Enter to open the System Properties
window.
 Click on the "Advanced" tab.
 Click on the "Environment Variables" button.
 Under "System variables," find the variable named "Path."
 Click "Edit."
 If the path to your mongosh.exe file (usually C:\\Program
Files\\MongoDB\\Shell\\bin\\mongosh.exe) is not already listed,
click "New" and add it.
 Click "OK" on all open windows to confirm the changes.

Verification:

o Open a new command prompt window (search for "cmd" in the Start menu).
o Type mongosh and press Enter.

If the installation was successful, you should see the mongosh shell prompt:
connecting to mongodb://127.0.0.1:27017/test Welcome to the MongoDB
shell MongoDB shell version v<version> ...

Additional Notes:

o If you encounter any issues during installation, refer to the official MongoDB
documentation for troubleshooting
steps: https://www.mongodb.com/docs/mongodb-shell/install/
o You can now use mongosh to connect to your local MongoDB instance (if
installed) or connect to remote MongoDB deployments.

Installation (macOS):

Recommended Method: Using Homebrew

Homebrew is a popular package manager for macOS that simplifies installing and
managing software.

27. Install Homebrew (if you haven't already):


 Follow the official instructions for Homebrew
installation: https://brew.sh/
28. Update Homebrew (recommended):
 Open a terminal window (search for "Terminal" in Spotlight).
 Run the following command to update Homebrew's package list:

Bash

brew update

29. Install MongoDB Community Edition:


 Add the MongoDB Homebrew tap to download the official formula:

Bash

brew tap mongodb/brew

 Install MongoDB:

Bash

brew install mongodb-community@<version> # Replace


<version> with desired version (e.g., 7.0)

30. Start MongoDB as a Service (optional):


 To run MongoDB in the background as a service, use:

Bash

brew services start mongodb-community@<version> # Replace


<version> with desired version
Verification:

o Open a new terminal window.


o Type mongosh and press Enter.

If successful, you'll see the mongosh shell prompt:

connecting to mongodb://127.0.0.1:27017/test Welcome to the MongoDB


shell MongoDB shell version v<version> ...

Alternative Method: Manual Installation

33. Download the MongoDB package:


 Visit the official MongoDB download page: [download mongodb shell
ON mongodb.com]
 Choose your desired version (latest stable is recommended).
 Under "Platform," select "macOS."
 Click "Download" and save the archive file (usually .tgz).
34. Extract the archive:
 Use an archive utility like tar to extract the contents:

Bash

tar -zxvf mongodb-osx-<version>-x86_64.tgz # Replace


<version> with downloaded version

35. Set Environment Variable (optional):


 To use mongosh from any directory, add the path to mongosh in your
shell's PATH environment variable. This step is optional but
convenient. Refer to macOS documentation for adding environment
variables.

Additional Notes:

o Consider using the Homebrew method for easier updates and management.
o The official MongoDB documentation provides more
details: https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-
os-x/

Installation (Ubuntu):

Prerequisites:

o An Ubuntu system (preferably 20.04 or later)


o Internet access

Installation Steps:

40. Import the MongoDB Public Key:


 This key is used to verify the authenticity of MongoDB packages
during installation.
 Run the following command in your terminal:

Bash

sudo apt-key adv --keyserver


hkp://keyserver.mongodb.org:80 --recv
9E1E16F5SEDCDEA08CB6EBA27346D2D0F0EAF659

41. Create a List File:


 This file specifies the repositories containing the MongoDB packages.
 Run the following command to create the list file:

Bash

echo 'deb [arch=amd64]


<https://repo.mongodb.org/apt/ubuntu> focal/mongodb-
org/7.0 focal main' | sudo tee
/etc/apt/sources.list.d/mongodb-org.list

 Replace focal with your Ubuntu version's codename if it's different


(e.g., jammy for 22.04). You can find your version using lsb_release
-cs.
 Replace 7.0 with the desired MongoDB version number if you prefer a
specific version.
42. Update Package Lists:
 Ensure your package lists are up-to-date before installation:

Bash

sudo apt update

43. Install MongoDB Shell:


 Finally, install the mongodb-org-shell package using:

Bash

sudo apt install mongodb-org-shell

Verification:

o Open a new terminal window.


o Type mongosh and press Enter.

If successful, you should see the mongosh shell prompt:

connecting to mongodb://127.0.0.1:27017/test Welcome to the MongoDB


shell MongoDB shell version v<version> ...

Additional Notes:
o This guide installs the shell only. To install the full MongoDB server for local
database management, follow the official MongoDB documentation for
Ubuntu: https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-
ubuntu/
o Consider using a version control system like apt to manage package updates
for security and stability.

CRUD Operations in MongoDB:

1. Create (Insert):

o Insert One Document:


o db.collection.insertOne({ name: "Nihar", age: 30, city: "New
York" });
o
o Insert Multiple Documents:
o db.collection.insertMany([
o { name: "Yuktha", age: 25, city: "London" },
o { name: "Maheshwar", age: 35, city: "Paris" },
o { name: "Shreya", age: 28, city: "Berlin" }
o ]);
o

2. Read (Query):

o Find Documents:
o db.collection.find({ age: { $gt: 25 } }); // Find documents
where age is greater than 25
o
o Projection:
o db.collection.find({}, { name: 1, age: 1 }); // Include only
name and age fields
o

3. Update:

o Update One Document:


o db.collection.updateOne({ name: "John" }, { $set: { age: 31 }
});
o
o Update Multiple Documents:
o db.collection.updateMany({ city: "London" }, { $set: { city:
"Paris" } });
o

4. Delete:

o Delete One Document:


o db.collection.deleteOne({ name: "John" });
o
o Delete Multiple Documents:
o db.collection.deleteMany({ age: { $gte: 30 } }); // Delete
documents where age is greater than or equal to 30
o
These CRUD operations allow developers to efficiently manage data stored in
MongoDB databases. They form the basis for interacting with collections and
documents, enabling the creation, retrieval, updating, and deletion of data according
to application requirements.

Conditional Operators:

MongoDB supports a variety of conditional operators for querying documents based


on specific criteria. These operators allow for filtering documents based on
conditions.

o Comparison Operators: These operators compare the values of fields in


documents.
 $eq: Matches values that are equal to a specified value.
 $ne: Matches values that are not equal to a specified value.
 $gt: Matches values that are greater than a specified value.
 $gte: Matches values that are greater than or equal to a specified
value.
 $lt: Matches values that are less than a specified value.
 $lte: Matches values that are less than or equal to a specified value.

Example:

db.collection.find({ age: { $gte: 25, $lte: 40 } });

o Logical Operators: These operators combine multiple conditions.


 $and: Joins query clauses with a logical AND and returns all
documents that match the conditions.
 $or: Joins query clauses with a logical OR and returns all documents
that match any of the conditions.
 $not: Inverts the effect of a query expression and returns documents
that do not match the query expression.

Example:

db.collection.find({ $or: [{ age: { $lt: 25 } }, { age: { $gt: 40 }


}] });

Ordering Results:

MongoDB allows sorting query results based on one or more fields in ascending or
descending order.

o Ascending Order (1) and Descending Order (-1):

db.collection.find().sort({ age: 1 }); // Sorts by age in ascending


order
db.collection.find().sort({ name: -1 }); // Sorts by name in
descending order
Pagination:

Pagination in MongoDB involves limiting the number of documents returned by a


query to only a subset, enabling efficient handling of large result sets.

o Limit(): Limits the number of documents returned by a query.

Example:

db.collection.find().limit(10); // Limits the result to 10 documents

o Skip(): Skips a specified number of documents and returns the rest.

Example:

db.collection.find().skip(10); // Skips the first 10 documents

Logical Operators:

MongoDB supports logical operators to combine multiple conditions in a query.

o $and:

db.collection.find({ $and: [{ age: { $gte: 25 } }, { age: { $lte: 40


} }] });

o $or:

db.collection.find({ $or: [{ age: { $lt: 25 } }, { age: { $gt: 40 }


}] });

o $not:

db.collection.find({ age: { $not: { $gt: 40 } } });

Aggregation:

In MongoDB, the aggregation framework provides powerful tools for performing data
transformations and computations on the documents within a collection. It allows you
to process and analyze data, including grouping, filtering, sorting, and performing
various calculations. Let's delve into the details:

Aggregation Stages:
The aggregation framework consists of various stages, each performing a specific
operation on the input documents and passing the results to the next stage. Some
common stages include:

84. $match: Filters documents based on specified criteria.


85. $group: Groups documents by a specified expression and applies accumulator
expressions to calculate computed values for each group.
86. $project: Reshapes documents, includes, excludes, or transforms fields, and
calculates new expressions.
87. $sort: Orders the documents.
88. $limit: Limits the number of documents passed to the next stage.
89. $skip: Skips a specified number of documents.
90. $unwind: Deconstructs an array field from input documents and outputs a
document for each element in the array.

Aggregation Operators:

MongoDB provides a variety of aggregation operators to perform computations


within the aggregation pipeline. Some common aggregation operators include:

o $sum: Calculates the sum of numeric values.


o $avg: Calculates the average of numeric values.
o $min: Finds the minimum value.
o $max: Finds the maximum value.
o $push: Appends values to an array.
o $addToSet: Adds unique values to an array.
o $project: Reshapes documents by including, excluding, or transforming
fields.
o $group: Groups documents by a specified expression and applies accumulator
expressions to calculate computed values for each group.

Aggregation Example:
[
{ "name": "Nihar", "score": 85, "grade": "3rd year", "course":
"Artificial Intelligence and Machine Learning" },
{ "name": "Yuktha", "score": 78, "grade": "2nd year", "course":
"Artificial Intelligence and Machine Learning" },
{ "name": "Maheshwar", "score": 92, "grade": "2nd year", "course":
"Chemistry" },
{ "name": "Vignesh", "score": 88, "grade": "2nd year", "course":
"Biology" },
{ "name": "Naman", "score": 79, "grade": "1st year", "course":
"Computer Science" },
{ "name": "Varun", "score": 90, "grade": "2nd year", "course":
"English" },
{ "name": "Shreya", "score": 84, "grade": "1st year", "course":
"History" },
{ "name": "Naveen", "score": 86, "grade": "1st year", "course":
"Economics" }
]
$match: Filters documents to pass only the documents that match the specified
condition.

db.aggregation.aggregate([
{ $match: { grade: "1st year" } }
])

This query will return only the documents where the grade is "1st year".

$group: Groups documents by a specified expression and applies accumulator


expressions.

db.aggregation.aggregate([
{ $group: { _id: "$grade", averageScore: { $avg: "$score" } } }
])

This query will group documents by the "grade" field and calculate the average score
for each group.

$sort: Orders the documents based on a specified field.

db.aggregation.aggregate([
{ $sort: { score: -1 } }
])

This query will sort the documents in descending order based on the "score" field.

$project: Reshapes each document in the stream by including, excluding, or


renaming fields.

db.aggregation.aggregate([
{ $project: { name: 1, grade: 1, course: 1 } }
])

This query will include only the "name", "grade", and "course" fields in the output.

$count: Returns a count of the number of documents at this stage of the aggregation
pipeline.

db.aggregation.aggregate([
{ $count: "totalStudents" }
])

This query will return the total count of documents in the collection.

These are just a few examples of aggregate functions in MongoDB. They allow for
powerful data manipulation and analysis within the database itself.
Congrats Mowa Successful ga complete chesnav! Next session lo
kaluddam :)

We’ll be building actual websites very soon by making use of the concepts
learnt till now. Stay tuned :)

You might also like