0% found this document useful (0 votes)
3 views278 pages

Beginner's Guide to HTML Basics

HTML (HyperText Markup Language) is the standard language for creating and structuring webpages, essential for building websites before adding CSS or JavaScript. It consists of elements defined by tags, attributes for additional information, and follows a basic structure with a doctype, html, head, and body sections. Key components include headings, paragraphs, links, images, lists, tables, and forms, each serving specific purposes in web development.

Uploaded by

vanshthapa1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views278 pages

Beginner's Guide to HTML Basics

HTML (HyperText Markup Language) is the standard language for creating and structuring webpages, essential for building websites before adding CSS or JavaScript. It consists of elements defined by tags, attributes for additional information, and follows a basic structure with a doctype, html, head, and body sections. Key components include headings, paragraphs, links, images, lists, tables, and forms, each serving specific purposes in web development.

Uploaded by

vanshthapa1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction to HTML

What is HTML?

HTML stands for HyperText Markup Language.


It is the standard language used to create and structure webpages.

Web browsers (like Chrome, Firefox, Safari) read HTML code and display it as
websites.

Why Learn HTML?

• It’s the foundation of all websites.


• You need HTML to build pages before adding CSS (styling) or JavaScript
(functionality).
C

• Knowing HTML helps you understand how websites work behind the scenes.
od
eW

Basic Terminology
ith

• Element: A piece of content in a webpage (like a paragraph, heading, or


image).
H

• Tag: Special keywords inside angle brackets like <p> or <h1> that define
ar

elements.
ry

• Attribute: Extra information added to tags, like href in links or src in


images.
Basic Example

<!DOCTYPE html>
<html>

<head>
<title>My First Page</title>
</head>
<body>
<h1>Hello, world!</h1>
<p>This is my first HTML page.</p>
</body>
</html>

Explanation:
• <!DOCTYPE html> tells the browser this is an HTML5 document.
• <html> is the root of the HTML page.
• <head> contains information about the page (not shown on screen).
• <title> sets the title seen on the browser tab.
C

• <body> contains everything visible on the webpage.


od
eW

Key Points

• HTML is made up of tags.


ith

• Tags usually come in pairs: an opening tag <p> and a closing tag </p> .
H

• The content goes between the tags.


ar

• Indentation helps make code easier to read, but it’s not required.
ry
Basic HTML Structure

What is the Basic Structure of an HTML Page?

Every HTML document follows a basic structure. This structure tells the browser
how to read and display the content.

Template of a Basic HTML Page

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
C

<body>
od

<!-- Your content goes here -->


</body>

</html>
eW
ith

Explanation of Each Part


H
ar

1. <!DOCTYPE html>
ry

• Declares that this is an HTML5 document.


• Must be the first line in the file.
2. <html>...</html>

• The root element of the page.


• Wraps all the content of your HTML document.

3. <head>...</head>

• Contains meta-information about the page.

• This can include:

• The page <title>


• Links to CSS files
• Meta tags (like keywords, description, etc.)

4. <title>...</title>

• Sets the name shown on the browser tab.

5. <body>...</body>

• Contains everything visible on the page.


C

• You’ll place text, images, links, forms, etc. here.


od
eW

Example
ith

<!DOCTYPE html>
H

<html>
ar

<head>
<title>My First Web Page</title>
ry

</head>
<body>
<h1>Welcome!</h1>
<p>This is a simple HTML page with basic structure.</p>
</body>
</html>
Tips

• Always start with <!DOCTYPE html> .


• Make sure <html> , <head> , and <body> are properly opened and closed.
• Use indentation to keep your code clean and readable.
C
od
eW
ith
H
ar
ry
Headings and Paragraphs

Headings in HTML

Headings help you organize content into sections.


HTML provides 6 levels of headings:

• <h1> – Main heading (biggest)


• <h2> – Subheading
• <h3> – Smaller subheading
• <h4> , <h5> , <h6> – Even smaller headings

Example of Headings
C

<h1>This is a Heading 1</h1>


od

<h2>This is a Heading 2</h2>


<h3>This is a Heading 3</h3>
eW

<h4>This is a Heading 4</h4>


<h5>This is a Heading 5</h5>
<h6>This is a Heading 6</h6>
ith
H

📌 Tip:
ar

• Use only one <h1> per page (usually for the page title).
ry

• Use headings to structure your content, not to make text look big (that’s
CSS’s job).
Paragraphs in HTML

Paragraphs are written using the <p> tag.

Example:

<p>This is a paragraph. It can contain multiple sentences of text.</p>

Notes:
• Browsers automatically add space before and after each paragraph.
• You don’t need to press Enter manually for new lines. Use a new <p> tag
instead.

Line Breaks

If you want to break a line without starting a new paragraph, use the <br> tag.
C

Example:
od

<p>This is line one.<br>This is line two.</p>


eW

<br> is a self-closing tag, which means it doesn’t need a closing </br> .


ith
H

Complete Example
ar
ry

<!DOCTYPE html>
<html>
<head>
<title>Headings and Paragraphs</title>
</head>
<body>
<h1>My Blog</h1>
<h2>Introduction</h2>

<p>Welcome to my first HTML blog post!</p>

<h2>Why I Love Coding</h2>


<p>Coding lets you build websites, apps, and games.<br>It’s fun and creative!</
p>
</body>
</html>
C
od
eW
ith
H
ar
ry
Formatting Text in HTML
HTML allows you to format your text using different tags. These tags help make
your content easier to read and visually appealing.

Bold Text

Use the <b> or <strong> tag to make text bold.

<p>This is <b>bold</b> text.</p>


<p>This is <strong>important</strong> text.</p>

• <strong> also means the text is important (for screen readers and SEO).
C
od

Italic Text
eW

Use the <i> or <em> tag to italicize text.


ith

<p>This is <i>italic</i> text.</p>


<p>This is <em>emphasized</em> text.</p>
H

• <em> gives extra emphasis and has meaning, especially for accessibility.
ar
ry

Underlined Text

Use the <u> tag to underline text.


<p>This is <u>underlined</u> text.</p>

Strikethrough Text

Use the <s> or <del> tag to show deleted or crossed-out text.

<p>This is <s>wrong</s> text.</p>


<p>Old price: <del>$100</del> New price: $80</p>

Superscript and Subscript

Use <sup> for superscript (above line), <sub> for subscript (below line).

<p>Water is H<sub>2</sub>O.</p>
C

<p>E = mc<sup>2</sup></p>
od
eW

Combining Formats
ith

You can combine formatting tags.


H

<p>This is <b><i>bold and italic</i></b> text.</p>


ar
ry
Summary of Formatting Tags

Tag Purpose

<b> Bold (no meaning)

<strong> Bold (important)

<i> Italic (no meaning)

<em> Italic (emphasis)

<u> Underline

<s> Strikethrough

<del> Deleted text

<sub> Subscript

<sup> Superscript
C
od
eW
ith
H
ar
ry
Comments and Whitespace in HTML

HTML Comments

Comments are notes in your HTML code that are ignored by the browser.
They are useful for explaining code or leaving reminders.

Syntax:

<!-- This is a comment -->


<p>This is visible content.</p>
<!-- <p>This line will not show on the webpage.</p> -->

Comments do not appear on the webpage. They’re only visible in the source code.
C
od

Whitespace in HTML
eW

Whitespace includes spaces, tabs, and newlines (Enter key). HTML treats multiple
spaces as a single space.
ith

Example:
H
ar

<p>This is spaced.</p>
ry

This will be displayed as:

This is spaced.
If you want to preserve spaces and line breaks, use the <pre> tag.

Example:

<pre>
This is preformatted
text.
</pre>

Tip

• Use comments to explain your HTML when needed.


• Use proper indentation (whitespace) to make your code readable, even though
HTML doesn’t require it.
C
od
eW
ith
H
ar
ry
Links and Anchor Tags

Creating Links in HTML

HTML uses the <a> tag to create links.


The href attribute tells the browser where the link should go.

Basic Syntax:

<a href="[Link] Example</a>

This creates a clickable link that takes you to the specified URL.
C

Opening Links in a New Tab


od

Use the target="_blank" attribute to open the link in a new tab.


eW

<a href="[Link] target="_blank">Open Google</a>


ith
H
ar

Linking to Other Pages (Internal Links)


ry

You can also link to other pages of your own website.

<a href="[Link]">About Us</a>


Link to a Section on the Same Page

Use the id attribute and a hash ( # ) to jump to a section.

<a href="#contact">Go to Contact</a>

...

<h2 id="contact">Contact Section</h2>

Email and Phone Links

• Email Link:

<a href="[Link] Email</a>

• Phone Link:
C
od

<a href="[Link] Us</a>


eW

Styling Links (Default Behavior)


ith

• Normal: Blue and underlined


H

• Visited: Purple
ar

• Hover: Changes color when mouse is over it


ry

• Active: Red while clicking

These styles can be changed with CSS later.


Images in HTML

Adding Images

Use the <img> tag to display images in HTML.


It is a self-closing tag, meaning it doesn’t need a closing </img> .

Basic Syntax:

<img src="[Link]" alt="Description of image">

• src (source): The path or URL to the image file.


• alt (alternative text): Text shown if the image doesn’t load, also used by
screen readers.
C
od

Example with Local Image


eW

<img src="[Link]" alt="My Photo">


ith
H

(Assumes [Link] is in the same folder as your HTML file)


ar
ry

Example with Online Image

<img src="[Link] alt="Online Image">


Image Size: Width and Height

You can set the size of the image using width and height attributes.

<img src="[Link]" alt="Sample" width="200" height="150">

You can also use CSS later for better control.

Tip

• Always include the alt text for accessibility.


• Use proper image sizes to improve page loading speed.
• Avoid stretching images using incorrect width/height ratios.
C
od
eW
ith
H
ar
ry
Lists in HTML

Types of Lists

HTML supports three main types of lists:

1. Unordered List – Bulleted list


2. Ordered List – Numbered list
3. Description List – List of terms and their descriptions

Unordered List

Use the <ul> tag for unordered lists. Each item goes inside an <li> tag.
C
od

<ul>
<li>Apples</li>
eW

<li>Bananas</li>
<li>Oranges</li>
</ul>
ith

This will display:


H

• Apples
ar

• Bananas
ry

• Oranges
Ordered List

Use the <ol> tag for ordered lists.

<ol>
<li>Wake up</li>
<li>Brush teeth</li>
<li>Go to work</li>
</ol>

This will display:

1. Wake up
2. Brush teeth
3. Go to work

Description List
C

Use the <dl> tag for description lists. Terms go inside <dt> , and descriptions go
inside <dd> .
od
eW

<dl>
<dt>HTML</dt>
<dd>A markup language for creating web pages.</dd>
ith

<dt>CSS</dt>
H

<dd>Used for styling HTML pages.</dd>


</dl>
ar
ry

Nesting Lists

You can put one list inside another.


<ul>

<li>Fruits
<ul>
<li>Apple</li>
<li>Mango</li>
</ul>
</li>
<li>Vegetables</li>
</ul>

Tip

• Use unordered lists for things without order (like a shopping list).
• Use ordered lists when the sequence matters.
• Use description lists for definitions or Q&A-style content.
C
od
eW
ith
H
ar
ry
Tables in HTML

Creating Tables

Use the <table> tag to create tables. Inside a table, use:

• <tr> for table rows


• <td> for table data (cells)
• <th> for table headers

Basic Table Example


C

<table>
od

<tr>
<th>Name</th>
<th>Age</th>
eW

</tr>
<tr>
<td>Alice</td>
ith

<td>24</td>
</tr>
H

<tr>
ar

<td>Bob</td>
<td>30</td>
ry

</tr>
</table>

This will display:


Name Age

Alice 24

Bob 30

Adding Borders

By default, tables have no border. Use the border attribute to add one.

<table border="1">
...
</table>

Table Headings vs Data

• <th> is usually bold and centered.


C

• <td> is regular table data.


od
eW

Spanning Columns and Rows


ith

Use colspan and rowspan to merge cells.


H

Column Span Example:


ar
ry

<tr>
<th colspan="2">Employee Details</th>
</tr>
Row Span Example:

<tr>
<td rowspan="2">John</td>
<td>Manager</td>
</tr>
<tr>
<td>IT Department</td>
</tr>

Tip

• Keep your tables organized and easy to read.


• Use headers ( <th> ) for important rows or columns.
• Avoid very complex tables for layout—use CSS for page design.
C
od
eW
ith
H
ar
ry
HTML Forms: Inputs, Labels, and
Buttons

What is a Form?

Forms allow users to input data and send it to a server.


Use the <form> tag to create a form.

<form>
<!-- form elements go here -->

</form>
C

Text Input Field


od

Use <input type="text"> to get a single line of text from the user.
eW

<form>
ith

<label for="name">Name:</label>

<input type="text" id="name" name="name">


H

</form>
ar

• <label> is used to describe the input.


ry

• The for attribute should match the input’s id .


Password Field

<label for="password">Password:</label>
<input type="password" id="password" name="password">

This hides the characters as you type.

Submit Button

Use type="submit" to create a button that submits the form.

<input type="submit" value="Submit">

Placeholder Text
C

You can show a hint inside the input using the placeholder attribute.
od

<input type="text" placeholder="Enter your name">


eW
ith

Complete Example
H
ar

<form>
<label for="email">Email:</label>
ry

<input type="email" id="email" name="email"


placeholder="you@[Link]"><br><br>

<label for="pass">Password:</label>
<input type="password" id="pass" name="pass"><br><br>
<input type="submit" value="Login">
</form>

Tip

• Always label your inputs for better accessibility.


• Use name attributes if the form is going to submit data.
• You’ll learn more input types in the next lesson.
C
od
eW
ith
H
ar
ry
Form Elements: Radio, Checkbox, Select,
Textarea

Radio Buttons

Use radio buttons when users need to select only one option from a group.

<p>Choose your gender:</p>


<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>

<input type="radio" id="female" name="gender" value="female">


<label for="female">Female</label>
C

• All radio buttons in a group should have the same name .


od

• Only one option can be selected.


eW

Checkboxes
ith

Use checkboxes when users can select multiple options.


H
ar

<p>Select your hobbies:</p>


<input type="checkbox" id="reading" name="hobby" value="reading">
ry

<label for="reading">Reading</label><br>

<input type="checkbox" id="sports" name="hobby" value="sports">


<label for="sports">Sports</label><br>
<input type="checkbox" id="music" name="hobby" value="music">
<label for="music">Music</label>

Dropdown List (Select Menu)

Use the <select> tag with <option> to let users pick one option from a
dropdown.

<label for="city">Choose a city:</label>


<select id="city" name="city">
<option value="delhi">Delhi</option>
<option value="mumbai">Mumbai</option>
<option value="bangalore">Bangalore</option>
</select>

Textarea (Multiline Input)


C
od

Use the <textarea> tag to let users type multiple lines of text.
eW

<label for="message">Your Message:</label><br>


<textarea id="message" name="message" rows="4" cols="30"></textarea>
ith
H

Tip
ar
ry

• Use radio buttons for single choice questions.


• Use checkboxes for multiple selections.
• Use select for compact dropdowns.
• Use textarea for longer user input like comments or messages.
HTML5 Semantic Tags

Inline vs Block Elements in HTML

In HTML, elements are broadly categorized as inline or block based on how they
behave in the document flow.

Block Elements
• Start on a new line.
• Take up the full width available.
• Can contain other block and inline elements.

Common Block Elements:

• <div>
• <p>
C

• <h1> to <h6>
od

• <section>
eW

• <article>
• <ul> , <ol> , <li>
ith

Example:
H

<div>
ar

<h2>This is a heading</h2>
<p>This is a paragraph inside a div.</p>
ry

</div>

Inline Elements
• Do not start on a new line.
• Only take up as much width as necessary.
• Usually used to style small portions of content within block elements.

Common Inline Elements:

• <span>
• <a>
• <strong> , <em>
• <img>
• <code>

Example:

<p>This is a <strong>bold</strong> word and <a href="#">this is a link</a>.</p>

Summary

Feature Block Elements Inline Elements


C

New Line Yes No


od

Width Full width Width of content only

Nesting Can contain any elements Only other inline elements


eW
ith

What Are Semantic Tags?


H

Semantic tags clearly describe the meaning of the content they contain.
ar

They help both developers and browsers understand the structure of the page.
ry

Example:
- <div> says nothing about its content.
- <header> clearly means it’s a page or section header.
Common Semantic Tags

Tag Purpose

<header> Top section of a page or section

<nav> Navigation links

<main> Main content of the page

<section> A standalone section

<article> Self-contained content like a blog

<aside> Sidebar or extra info

<footer> Bottom section of a page or section

Example Usage

<!DOCTYPE html>
C

<html>
od

<head>
<title>Semantic Page</title>
eW

</head>
<body>
ith

<header>
<h1>My Website</h1>
H

</header>
ar

<nav>
ry

<a href="#">Home</a> |
<a href="#">About</a> |
<a href="#">Contact</a>
</nav>

<main>
<section>
<h2>Welcome</h2>
<p>This is the welcome section.</p>

</section>

<article>
<h2>Blog Post</h2>
<p>This is a blog post inside an article tag.</p>
</article>
</main>

<aside>
<p>This is a sidebar with related links.</p>
</aside>

<footer>
<p>Copyright © 2025</p>
</footer>

</body>
</html>
C
od

Tip
eW

• Semantic tags improve accessibility and SEO.


• Use them instead of generic <div> and <span> wherever possible.
ith
H
ar
ry
HTML Entities and Special Characters

What Are HTML Entities?

Some characters have special meaning in HTML (like < , > , & ).
To display these characters on a webpage, you need to use HTML entities.

An entity starts with & and ends with ; .

Common HTML Entities

Character Entity Code Description

Less than
C

< &lt;
od

> &gt; Greater than

& &amp; Ampersand


eW

" &quot; Double quote


ith

' &apos; Single quote

© &copy; Copyright symbol


H

Registered symbol
ar

® &reg;

Indian Rupee sign


ry

₹ &#8377;

→ &rarr; Right arrow


Example

<p>5 &lt; 10</p>


<p>Use &amp; to join strings</p>

<p>Price: &#8377;499</p>

This will display as:

5 < 10 Use & to join strings Price: ₹499

Non-Breaking Space

Use &nbsp; to add extra space that the browser won’t collapse.

<p>Hello&nbsp;&nbsp;&nbsp;World</p>
C

Tip
od

• Use entities when you want to show special characters as text.


eW

• HTML automatically converts most symbols when needed, but using entities
ensures correct display.
ith
H
ar
ry
Audio and Video Embedding in HTML

Embedding Audio

Use the <audio> tag to add sound or music to your webpage.

Basic Example:

<audio controls>
<source src="audio.mp3" type="audio/mpeg">
Your browser does not support the audio element.

</audio>

• controls adds play, pause, and volume controls.


C

• The <source> tag specifies the audio file and type.


od
eW

Audio Formats
ith

Format MIME Type

MP3 audio/mpeg
H

OGG
ar

audio/ogg

WAV
ry

audio/wav

To support all browsers, you can include multiple sources:

<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="[Link]" type="audio/ogg">
</audio>

Embedding Video

Use the <video> tag to add videos to your page.

Basic Example:

<video width="320" height="240" controls>


<source src="video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

• width and height control the video size.


• controls adds playback controls.
C
od

Video Formats
eW

Format MIME Type

MP4 video/mp4
ith

WebM video/webm
H

OGG video/ogg
ar

You can include multiple sources to ensure browser compatibility:


ry

<video controls>
<source src="movie.mp4" type="video/mp4">
<source src="[Link]" type="video/ogg">
</video>
Tip

• Always provide controls so users can interact with media.


• Use multiple formats for broader browser support.
• Include fallback text for unsupported browsers.
C
od
eW
ith
H
ar
ry
IFrames and Embedding Content

What is an IFrame?

An <iframe> (inline frame) is used to embed another webpage or external


content inside your HTML page.

Basic Syntax

<iframe src="[Link] width="600" height="400"></iframe>

• src specifies the URL of the page to embed.


C

• width and height set the size of the frame.


od
eW

Example: Embed a Website


ith

<iframe src="[Link] width="800" height="500"></iframe>


H
ar
ry

Example: Embed a YouTube Video

YouTube provides embed code for each video.

<iframe width="560" height="315"


src="[Link]
frameborder="0"
allowfullscreen>

</iframe>

Attributes

Attribute Description

src URL of the page or content

width , height Size of the iframe

frameborder Border of the frame (0 = none)

allowfullscreen Allows video to go full screen

loading="lazy" Delays loading until iframe is visible


C

Security Note
od

Some websites may block iframe embedding for security reasons using headers
like X-Frame-Options .
eW
ith

Tip
H

• Use <iframe> to embed maps, videos, forms, and external tools.


ar

• Always set appropriate width and height for better layout control.
ry
Using Meta Tags and SEO Basics

What Are Meta Tags?

Meta tags provide information about the webpage to browsers and search
engines.
They go inside the <head> section and do not appear on the page itself.

Common Meta Tags

1. Charset
C

<meta charset="UTF-8">
od

• Defines the character encoding.


eW

• UTF-8 covers most characters in all languages.


ith

2. Viewport (Mobile Responsiveness)


H

<meta name="viewport" content="width=device-width, initial-scale=1.0">


ar
ry

• Makes your website mobile-friendly.


• Tells the browser to match the screen’s width.
3. Page Description

<meta name="description" content="Learn HTML from scratch with simple examples.">

• Summarizes the page content.


• Often shown in search engine results.

4. Keywords (Less important today)

<meta name="keywords" content="HTML, web development, coding">

• List of keywords related to your page.


• Not heavily used by modern search engines.

5. Author

<meta name="author" content="Your Name">


C
od

• Specifies the name of the content creator.


eW

6. Refresh / Redirect (Optional)


ith

<meta http-equiv="refresh" content="5; url=[Link]


H
ar

• Redirects the page after 5 seconds.


ry

SEO Basics

• Use meaningful page titles with the <title> tag.


• Include a clear meta description.
• Structure content using headings ( <h1> , <h2> , etc.).
• Use semantic tags to describe content.
• Make sure the page loads fast and works well on mobile.

Example Head Section

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Simple HTML tutorial for beginners.">
<meta name="author" content="John Doe">
<title>Learn HTML</title>
</head>

Tip
C
od

• Good meta tags improve search visibility and user experience.


• Always include the viewport meta tag for mobile responsiveness.
eW
ith
H
ar
ry
Internal vs External Links

Internal Links

Internal links connect one page of your website to another.


They help users navigate within your site.

Example:

<a href="[Link]">About Us</a>

This opens the [Link] page located in the same folder.


C

Linking to a Section on the Same Page


od

Use #id to jump to a specific section.


eW

<a href="#contact">Go to Contact Section</a>


ith

...
H

<h2 id="contact">Contact Us</h2>


ar
ry

External Links

External links take the user to a different website.


Example:

<a href="[Link] Google</a>

Open External Links in a New Tab

Use the target="_blank" attribute.

<a href="[Link] target="_blank">Open Example</a>

Adding rel="noopener noreferrer" for Security

When using target="_blank" , it’s recommended to add rel="noopener


noreferrer" to prevent security risks.
C

<a href="[Link] target="_blank" rel="noopener noreferrer">


od

Visit External Site


</a>
eW
ith

Summary
H

Link Type Example


ar

Internal Link href="[Link]"


ry

Section Jump href="#section-id"

External Link href="[Link]

New Tab + Safe target="_blank" rel="noopener"


Tip

• Use internal links to connect your content and improve navigation.


• Use external links to reference useful outside resources.
C
od
eW
ith
H
ar
ry
Best Practices for Writing Clean HTML

1. Use Proper Indentation

Indent nested elements for better readability.

<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>

2. Always Close Your Tags


C

Even if some tags are optional, it’s best to close them properly.
od
eW

<p>This is correct.</p>
ith

3. Use Meaningful Tag Structure


H
ar

Use semantic tags like <header> , <main> , <footer> instead of relying only on
<div> .
ry
4. Include alt Text for Images

This improves accessibility and helps screen readers understand image content.

<img src="[Link]" alt="A smiling person">

5. Use Lowercase for Tags and Attributes

HTML is not case-sensitive, but using lowercase is the standard.

<!-- Good -->


<input type="text">

<!-- Avoid -->

<INPUT TYPE="TEXT">
C

6. Organize Your Code


od

Keep your HTML structured by grouping related elements together. Use comments
eW

to separate sections.
ith

<!-- Navigation -->


<nav>...</nav>
H
ar

<!-- Main Content -->


<main>...</main>
ry

7. Don’t Use Inline Styles (if possible)

Avoid putting CSS styles directly into HTML tags. Use external CSS files instead.
<!-- Avoid -->

<p style="color: red;">Red text</p>

<!-- Prefer -->


<p class="red-text">Red text</p>

8. Validate Your HTML

Use tools like W3C HTML Validator to check for errors in your code.

9. Keep File Names Simple and Clear

Use lowercase letters, dashes instead of spaces, and meaningful names.

✔ [Link]
✘ About Us!.html
C
od
eW

10. Comment Your Code (When Needed)


ith

Use comments to explain complex sections or to label page areas.


H

<!-- Contact Form -->


ar

<form>...</form>
ry

Tip

Clean HTML is easier to read, debug, maintain, and scale as your website grows.
Introduction to CSS
CSS (Cascading Style Sheets) is used to style and layout web pages — including
colors, fonts, spacing, and positioning of elements. While HTML gives structure to a
web page, CSS makes it look beautiful and usable.

Why CSS?

Without CSS, all websites would look plain, like unstyled documents. CSS helps
you:

• Change colors and fonts


• Add spacing and layout
• Make responsive designs for mobile
• Animate and transition between states
• Separation of concerns: HTML for structure, CSS for style
C
od

How CSS Works with HTML


eW

CSS can be applied to HTML in three main ways:

1. Inline CSS
ith

CSS written inside an HTML tag using the style attribute.


H
ar

<p style="color: blue; font-size: 18px;">This is a blue paragraph.</p>


ry

2. Internal CSS
CSS written inside a <style> tag within the <head> section of the HTML.
<!DOCTYPE html>

<html>
<head>
<style>
p {
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<p>This is a green bold paragraph.</p>
</body>
</html>

3. External CSS (Best Practice)


CSS written in a separate file and linked to the HTML file. This is the most
recommended method for real-world projects.

[Link]
C
od

h1 {
color: darkred;
eW

text-align: center;
}
ith

[Link]
H
ar

<!DOCTYPE html>
<html>
ry

<head>
<link rel="stylesheet" href="[Link]">
</head>
<body>
<h1>Welcome to CSS</h1>
</body>
</html>

The “Cascading” in CSS

If there are multiple rules targeting the same element, CSS uses the cascade to
decide which rule to apply. This depends on:

• Specificity (How specific the selector is)


• Order of appearance
• Importance ( !important )

Example:

<p style="color: red;">This will be red because inline CSS wins.</p>

Anatomy of a CSS Rule


C

selector {
od

property: value;
}
eW

Example:
ith

p {
color: black;
H

font-size: 16px;
ar

}
ry

• p → Selector (targets all <p> elements)


• color , font-size → Properties
• black , 16px → Values
What You’ll Learn in CSS

As we move forward, you’ll learn how to:

• Style text, backgrounds, and borders


• Control layout with Flexbox and Grid
• Make your website responsive and mobile-friendly
• Animate elements and transitions
• Write modern, maintainable CSS
C
od
eW
ith
H
ar
ry
CSS Syntax and Selectors
To apply styles to HTML elements, you need to understand the basic syntax of CSS
and how to select elements on the page.

CSS Syntax

Every CSS rule consists of a selector and a declaration block.

selector {
property: value;

Example:
C

h1 {
od

color: navy;
font-size: 32px;
eW

• h1 is the selector
ith

• color and font-size are properties


H

• navy and 32px are the values


ar

• The curly braces {} contain the declaration block


• Each declaration ends with a semicolon ;
ry
Types of Selectors

1. Element Selector
Selects all elements of a specific type.

p {
color: gray;
}

This targets all <p> elements.

2. Class Selector
Selects elements with a specific class.

HTML:

<p class="highlight">This is important.</p>


C
od

CSS:
eW

.highlight {
background-color: yellow;
ith

}
H

Use a period . before the class name.


ar
ry

3. ID Selector
Selects a single element with a unique ID.

HTML:
<h1 id="main-heading">Welcome</h1>

CSS:

#main-heading {
font-family: Arial, sans-serif;

Use a hash # before the ID name.

4. Universal Selector
Applies styles to all elements on the page.

* {
margin: 0;
padding: 0;
}
C
od

This is commonly used for resetting default styles.


eW

5. Grouping Selectors
ith

Apply the same styles to multiple selectors at once.


H

h1, h2, h3 {
ar

color: darkblue;
ry

This avoids repetition.


6. Descendant Selector
Targets elements nested inside other elements.

HTML:

<div>
<p>This is a paragraph inside a div.</p>
</div>

CSS:

div p {
font-style: italic;
}

Only <p> tags inside <div> will be affected.

7. Combining Class and Element Selectors


C

You can be more specific by combining them.


od
eW

[Link] {
color: teal;
}
ith

This targets only <p> elements with the class note .


H
ar

Summary
ry

• CSS selectors help you choose which HTML elements to style.


• Use . for classes, # for IDs, and tag names for element selectors.
• Combine and group selectors for powerful control.
Colors in CSS
Colors play a major role in the visual appearance of a website. In CSS, you can
apply colors to text, backgrounds, borders, and other elements using different
formats.

Ways to Define Colors

CSS supports several formats for defining colors:

1. Named Colors
CSS has a set of predefined color names like red , blue , green , black , etc.
C

h1 {
od

color: red;
}
eW
ith

2. HEX Codes
H

A hexadecimal value represents a color using a six-digit code.


ar

body {
ry

background-color: #f0f0f0;
}

• #000000 → black
• #ffffff → white
• #ff0000 → red

You can also use shorthand if all pairs are the same:

#fff /* same as #ffffff */

3. RGB (Red, Green, Blue)


You can define a color using the RGB color model.

p {
color: rgb(255, 0, 0);
}

• Values range from 0 to 255


• rgb(0, 0, 0) → black
• rgb(255, 255, 255) → white
C
od

4. RGBA (RGB + Alpha)


eW

Adds opacity to RGB using the alpha channel (0 = fully transparent, 1 = fully
opaque).
ith

div {
background-color: rgba(0, 0, 0, 0.5);
H

}
ar

This creates a semi-transparent black background.


ry
5. HSL (Hue, Saturation, Lightness)
Another way to define colors using:

• Hue (color angle on the color wheel)


• Saturation (intensity of the color)
• Lightness (brightness)

h2 {
color: hsl(240, 100%, 50%);
}

6. HSLA (HSL + Alpha)


Same as HSL, but with transparency.

section {
background-color: hsla(120, 60%, 70%, 0.3);
}
C
od
eW

Applying Colors in CSS

You can use color properties in many different places:


ith
H

h1 {
color: navy; /* Text color */
ar

background-color: #e0e0e0; /* Background color */


ry

border: 2px solid #333; /* Border color */


}
Transparent and CurrentColor

• transparent → Makes an element’s color fully transparent.


• currentColor → Inherits the current value of the color property.

button {
color: blue;
border: 2px solid currentColor;
}

Summary

• Use color to enhance readability, structure, and aesthetics.


• Choose the format (HEX, RGB, HSL) that suits your workflow.
• Learn to use rgba or hsla for transparency effects.
C
od
eW
ith
H
ar
ry
The CSS Box Model
Every HTML element on a page is a rectangular box in the browser, and the Box
Model defines how that box behaves. It’s the foundation of spacing, layout, and
sizing in CSS.

What is the Box Model?

The box model consists of four layers, from innermost to outermost:

|---------------------------|
| Margin |
| |---------------------| |
| | Border | |
| | |---------------| | |
C

| | | Padding | | |
od

| | | |---------| | | |
| | | | Content | | | |

| | | |---------| | | |
eW

| | |---------------| | |
| |---------------------| |
|---------------------------|
ith
H
ar

The Four Parts


ry

1. Content
The actual text, image, or element inside the box.
width: 200px;

height: 100px;

2. Padding
Space inside the box, between content and border.

padding: 20px;

It pushes the content inward, increasing the total box size.

3. Border
The border around the padding and content.

border: 2px solid black;


C
od

You can control its width, style, and color.


eW

4. Margin
ith

Space outside the border. Used to create distance between elements.


H

margin: 30px;
ar
ry

Margins do not have a background color and are completely transparent.


Example

.box {
width: 300px;

height: 150px;
padding: 20px;
border: 5px solid gray;
margin: 40px;
}

The actual space this element occupies:

• Width: 300 + 2*20 (padding) + 2*5 (border) = 350px


• Height: 150 + 2*20 (padding) + 2*5 (border) = 200px

Margin is outside of this box, adding extra space between elements.

Box Sizing: content-box vs border-box


C

By default, CSS uses content-box , where width and height apply only to the
od

content, not padding or border.


eW

To include padding and border inside the specified dimensions, use:

* {
ith

box-sizing: border-box;
}
H
ar

With border-box , the total width stays fixed, and padding/border are adjusted
inside the box.
ry
Visual Example

.card {
width: 400px;

padding: 20px;
border: 10px solid black;
box-sizing: border-box;
}

In this case, the total width remains 400px, including padding and border.

Summary

• The box model controls how elements take up space.


• Understand how content, padding, border, and margin interact.
• Use box-sizing: border-box to make layout calculations easier.
C
od
eW
ith
H
ar
ry
Units in CSS
CSS units define the size, spacing, and positioning of elements on a web page.
Understanding units is essential for building layouts that are consistent, responsive,
and easy to manage.

Two Categories of Units

1. Absolute Units
These do not change based on screen size or parent element. Use them for fixed-
size elements (use cautiously in responsive designs).

Unit Description

Pixels (most common absolute unit)


C

px
od

pt Points (1/72 of an inch)

cm Centimeters
eW

mm Millimeters
ith

in Inches
H

Example:
ar

h1 {
ry

font-size: 24px;
}
2. Relative Units
These are responsive and scale based on parent elements, root font size, or
viewport size.

Unit Description

% Relative to parent element

em Relative to parent’s font size

rem Relative to root font size (usually <html> )

vw 1% of viewport width

vh 1% of viewport height

vmin 1% of smaller viewport dimension

vmax 1% of larger viewport dimension

Commonly Used Units


C
od

px (Pixels)
eW

p {
margin: 10px;
ith

}
H

Fixed spacing that does not scale with screen size.


ar
ry

% (Percentage)

div {
width: 80%;
}
Useful for making widths or heights relative to parent elements.

em vs rem

em : Relative to the font size of the parent.

div {
font-size: 2em; /* 2 times the parent's font size */
}

rem : Relative to the font size of the root ( html ) element.

html {
font-size: 16px;
}

h1 {
font-size: 2rem; /* 32px */
}
C
od

Use rem for consistency in modern responsive design.


eW

vw and vh
ith

.container {
H

width: 100vw; /* Full width of the viewport */


height: 100vh; /* Full height of the viewport */
ar

}
ry

These units are powerful for creating fullscreen layouts.


calc() Function

Combine different units using calc() :

section {
width: calc(100% - 200px);
}

Best Practices

• Use rem for typography for consistency and scalability.


• Use % , vw , vh for responsive layouts.
• Avoid overusing px in responsive designs.

Summary
C

CSS units help control the size and spacing of elements. Choosing the right unit is
od

key to making layouts flexible, scalable, and consistent across devices.


eW
ith
H
ar
ry
Typography in CSS
Typography is how text appears on a web page — its font, size, spacing,
alignment, weight, and overall readability. Good typography improves user
experience and design quality.

Basic Text Properties

1. font-family

Sets the typeface for your text.

body {
font-family: Arial, sans-serif;
}
C
od

• You can specify a list of fallback fonts.


• Always end with a generic family like sans-serif , serif , or monospace .
eW

Common font stacks:


ith

font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;


H

font-family: Georgia, 'Times New Roman', serif;


font-family: 'Courier New', Courier, monospace;
ar
ry

2. font-size

Controls the size of the text.


h1 {

font-size: 36px;
}

You can use units like px , em , rem , % .

p {
font-size: 1.2rem;
}

3. font-weight

Defines the boldness of text.

strong {
font-weight: bold;
}
C

You can use keywords like normal , bold , or numeric values like 100 , 400 ,
od

700 , 900 .
eW

4. font-style
ith

Sets text to normal, italic, or oblique.


H
ar

em {
font-style: italic;
ry

}
5. text-align

Aligns text horizontally.

h2 {
text-align: center;
}

Values: left , right , center , justify

6. line-height

Controls the space between lines of text.

p {
line-height: 1.6;
}

This improves readability, especially for paragraphs.


C
od

7. letter-spacing
eW

Controls space between characters.


ith

h1 {
H

letter-spacing: 2px;
}
ar
ry

8. word-spacing

Controls space between words.


p {

word-spacing: 5px;
}

9. text-transform

Changes the case of text.

.upper {

text-transform: uppercase;
}

.lower {
text-transform: lowercase;
}

.capitalize {
text-transform: capitalize;
C

}
od
eW

10. text-decoration

Controls underlining, overlining, and line-through.


ith
H

a {
text-decoration: none;
ar

}
ry

Using Google Fonts

To use custom fonts, you can load them from Google Fonts.
HTML

<link href="[Link] rel="styl


esheet">

CSS

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

Summary

Typography affects the readability and tone of your website. Key things to
remember:

• Use rem for font sizing to keep things scalable.


• Set appropriate line-height and font-family for comfortable reading.
C

• Align and style text to match your design’s personality.


od
eW
ith
H
ar
ry
Backgrounds and Borders in CSS
CSS allows you to customize how elements look and feel by adding backgrounds
and borders. You can apply colors, images, gradients, and control borders precisely
around elements.

Background Properties

1. background-color

Sets a solid color behind an element.

div {
background-color: lightblue;
}
C
od
eW

2. background-image

Adds an image as the background.


ith

body {
H

background-image: url('[Link]');
ar

}
ry

You can use local images or remote URLs.


3. background-repeat

Controls if the background image repeats.

background-repeat: repeat; /* Default */


background-repeat: no-repeat;
background-repeat: repeat-x; /* Only horizontally */

background-repeat: repeat-y; /* Only vertically */

4. background-size

Sets the size of the background image.

background-size: cover; /* Fill container and crop */


background-size: contain; /* Fit image without cropping */

background-size: 100px 200px; /* Custom dimensions */


C

5. background-position
od

Positions the background image within the element.


eW

background-position: center;
background-position: top right;
ith

background-position: 50% 50%;


H
ar

6. background-attachment
ry

Controls scroll behavior.

background-attachment: scroll; /* Default */


background-attachment: fixed; /* Stays in place during scroll */
7. Shorthand Property: background

You can combine all background properties in one line.

div {
background: url('[Link]') no-repeat center center / cover;

Border Properties

1. border-width

Sets the thickness of the border.

div {
border-width: 3px;
C

}
od
eW

2. border-style

Defines the style of the border.


ith
H

border-style: solid; /* Common */


border-style: dashed;
ar

border-style: dotted;
border-style: double;
ry

border-style: none;
3. border-color

Sets the color of the border.

border-color: darkgray;

4. Shorthand: border

You can combine width, style, and color.

div {
border: 2px solid #333;
}

5. Individual Sides
C

border-top: 1px solid black;


border-right: 2px dashed red;
od

border-bottom: none;
border-left: 3px dotted green;
eW
ith

6. border-radius
H

Rounds the corners of an element.


ar
ry

button {
border-radius: 10px;
}

You can also use percentages to make circular shapes:


img {

border-radius: 50%; /* Perfect circle for square images */


}

Summary

• Use background properties to add color, images, and gradients.


• Borders help separate and define content.
• Use border-radius to soften corners and create modern designs.
C
od
eW
ith
H
ar
ry
Margin and Padding in CSS
Margin and Padding are two of the most commonly used properties in CSS to
control spacing around elements. They are part of the CSS Box Model and play a
crucial role in layout and visual structure.

Padding vs Margin

Property Affects Where the space appears

padding Inside the element Between the content and the border

margin Outside the element Between the element and others


C

Padding
od

Apply space inside the border, around the content.


eW

.box {
ith

padding: 20px;
}
H

This adds 20px space inside all four sides of the .box .
ar
ry

Individual sides

padding-top: 10px;
padding-right: 15px;
padding-bottom: 10px;
padding-left: 15px;

Shorthand

padding: 10px 15px 10px 15px; /* top right bottom left */


padding: 10px 15px; /* top-bottom | right-left */
padding: 10px; /* all sides */

Margin

Adds space outside the border of an element.

.card {
margin: 30px;
}
C
od

This separates the .card from nearby elements.


eW

Individual sides
ith

margin-top: 20px;
H

margin-right: 0;
ar

margin-bottom: 20px;
margin-left: auto;
ry
Shorthand

margin: 20px 40px 20px 40px; /* top right bottom left */


margin: 20px 40px; /* top-bottom | right-left */
margin: 0 auto; /* top-bottom: 0, left-right: auto (used for
centering) */

Auto Margin (Horizontal Centering)

.container {
width: 500px;
margin: 0 auto;
}

This centers the container horizontally if a fixed width is set.

Margin Collapse
C
od

When two vertical margins meet (e.g., margin-bottom of one element and margin-
top of the next), the larger one wins, not their sum.
eW

h1 {
ith

margin-bottom: 30px;
}
H

p {
ar

margin-top: 20px;
}
ry

The space between them will be 30px, not 50px.


Summary

• Padding pushes content inward.


• Margin pushes the element outward.
• Use shorthand to simplify your CSS.
• Be aware of margin collapsing in vertical spacing.
C
od
eW
ith
H
ar
ry
The Display Property in CSS
The display property controls how an element is rendered on the page —
whether it takes up a full line, shares space with others, behaves like a container, or
is completely hidden.

Understanding how display works is critical to mastering layout in CSS.

Common Display Values

1. block

• The element takes up the full width of its container.


• Starts on a new line.

Examples of block elements: <div> , <p> , <h1> – <h6> , <section> , <article>


C
od

div {
eW

display: block;
}
ith
H

2. inline
ar

• The element takes up only as much width as its content.


ry

• Can appear next to other inline elements.


• Cannot set width, height, margin-top/bottom, or padding-top/bottom
effectively.

Examples: <span> , <a> , <strong> , <em>


span {

display: inline;
}

3. inline-block

• Behaves like inline but allows width, height, margin, and padding to be
set.
• Does not force a line break.

button {
display: inline-block;
width: 150px;
height: 40px;

}
C

4. none
od

• Completely hides the element from the page.


eW

• The element is not rendered, and does not take up any space.

.alert {
ith

display: none;
}
H
ar

Useful for toggling visibility dynamically (e.g., with JavaScript).


ry
5. flex and grid (Coming Soon)

These are modern layout tools you’ll learn in upcoming lessons:

• flex enables 1D flexible layouts.


• grid enables 2D grid layouts.

Visual Example

<div style="display: inline-block; width: 100px; background: lightgray;">

Box 1
</div>
<div style="display: inline-block; width: 100px; background: lightblue;">
Box 2
</div>

These boxes appear side by side with a fixed width.


C

Changing Display in Practice


od
eW

nav {
display: block;
}
ith

nav a {
H

display: inline-block;
ar

padding: 10px;
}
ry
Summary

• block : Full width, starts new line.


• inline : Sits within a line, no block features.
• inline-block : Inline behavior with block features.
• none : Removes the element completely.
• flex and grid : Modern layouts covered soon.
C
od
eW
ith
H
ar
ry
Positioning in CSS
CSS positioning allows you to move elements from their default flow and place
them precisely where you want on the page. It’s an essential part of creating
modern, interactive layouts.

The position Property

There are five main values:

Value for
Description
Position

static Default. Element stays in the normal document flow

relative Moves the element relative to its normal position


C

Removes from flow; positions relative to nearest


od

absolute
positioned ancestor
eW

Positions the element relative to the browser window,


fixed
even on scroll

Behaves like relative , but sticks to a position while


ith

sticky
scrolling
H
ar

1. static (Default)
ry

Every element is positioned statically by default.


div {

position: static;
}

You can’t move statically positioned elements with top , left , etc.

2. relative

Moves the element relative to where it would normally be.

.box {
position: relative;
top: 20px;
left: 10px;

It stays in the document flow, but shifts slightly.


C
od

3. absolute
eW

• Removes the element from normal flow.


• Positions it relative to the closest ancestor with position set (not static ).
ith

• If no positioned ancestor, it uses the <html> element.


H
ar

.parent {
position: relative;
ry

.child {
position: absolute;
top: 0;
right: 0;
}

The .child will stick to the top-right of .parent .

4. fixed

• Stays in a fixed position relative to the viewport.


• Does not move when scrolling.

.banner {
position: fixed;
top: 0;
left: 0;
width: 100%;

Great for sticky headers, floating buttons, or back-to-top links.


C
od

5. sticky
eW

• Acts like relative until a scroll threshold is reached, then behaves like
ith

fixed .
H

.heading {
ar

position: sticky;
top: 0;
ry

background: white;
}

Sticky headers or sidebars often use this behavior.


top , right , bottom , left

These properties only work with relative , absolute , fixed , or sticky .

.box {
position: absolute;
top: 50px;
left: 100px;
}

z-index

Controls the stacking order of overlapping elements.

.modal {
position: absolute;
z-index: 100;
C

}
od

Higher z-index values appear above lower ones.


eW

Summary
ith

• Use relative for minor adjustments.


H

• Use absolute to fully control placement inside containers.


ar

• Use fixed for elements that stay on screen while scrolling.


ry

• Use sticky for scroll-based sticky behaviors.


• Always understand the positioning context — especially when using
absolute .
ry
ar
H
ith
eW
od
C
ry
ar
H
ith
eW
od
C
ry
ar
H
ith
eW
od
C
Flexbox in CSS
Flexbox (Flexible Box Layout) is a powerful layout system in CSS that allows you to
align, space, and distribute elements easily — especially when building responsive
layouts.

It’s ideal for one-dimensional layouts (either a row or a column).

Getting Started

To use Flexbox, set the parent container’s display to flex :

.container {
display: flex;
}
C
od

Now, all direct children of .container become flex items.


eW

Main Concepts
ith

Term Description
H

Main Axis The primary direction ( row by default)


ar

Cross Axis Perpendicular to main axis


ry

Flex Container The parent element with display: flex

Flex Items The children inside the container


Flex Direction

Controls the direction of flex items.

.container {
display: flex;
flex-direction: row; /* default */

flex-direction: row-reverse;
flex-direction: column;
flex-direction: column-reverse;
}
C
od
eW

Justify Content (Main Axis Alignment)

Controls how items are aligned along the main axis (horizontal by default).
ith
H

.container {
justify-content: flex-start; /* default */
ar

justify-content: flex-end;
justify-content: center;
ry

justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;
}
C
od
eW
ith

Align Items (Cross Axis Alignment)


H

Controls how items are aligned on the cross axis (vertical by default).
ar
ry

.container {
align-items: stretch; /* default */
align-items: flex-start;
align-items: flex-end;
align-items: center;
align-items: baseline;
}

C
od
eW

Align Self
ith

Allows individual items to override align-items .


H
ar

.item {
ry

align-self: flex-end;
}
Flex Wrap

By default, items try to fit into a single line. Use flex-wrap to wrap them:

.container {
flex-wrap: wrap;
flex-wrap: nowrap; /* default */
flex-wrap: wrap-reverse;
}

Gap (Spacing Between Items)

.container {
gap: 20px;

This replaces the need for margins between flex items.


C
od

Flex Grow, Shrink, Basis


eW

Control how items grow, shrink, or have an initial size:


ith

.item {
H

flex-grow: 1; /* takes remaining space */


flex-shrink: 1; /* shrink if needed */
ar

flex-basis: 200px; /* default size */


ry

Shorthand:
.item {

flex: 1 1 200px;
}

Example Layout

<div class="container">
<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
</div>

.container {

display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
C

}
od

.item {
background: lightgray;

padding: 20px;
eW

flex: 1;
}
ith
H

Summary
ar
ry

• display: flex turns a container into a Flexbox layout.


• Use justify-content , align-items , and flex-direction to control layout
flow.
• flex shorthand ( grow shrink basis ) gives you fine-grained sizing control.
• Use gap instead of margins for consistent spacing.
CSS Grid
CSS Grid Layout is a two-dimensional layout system that allows you to design web
pages in rows and columns. It gives you complete control over both axes, unlike
Flexbox which is mostly one-dimensional.

Enabling Grid

Set the container’s display property to grid :

.container {

display: grid;
}

All direct children of this container become grid items.


C
od

Defining Rows and Columns


eW

You use grid-template-columns and grid-template-rows to define the grid


ith

structure:
H

.container {
ar

display: grid;
grid-template-columns: 200px 1fr 1fr;
ry

grid-template-rows: 100px auto;


}

• 1fr means “1 fraction of remaining space”


• You can mix fixed units (e.g. px ) with flexible ones ( fr )
Repeat Syntax

To avoid repeating values:

.container {
grid-template-columns: repeat(3, 1fr);
}

Creates 3 equal-width columns.

Grid Gap

Adds spacing between rows and columns:

.container {
gap: 20px; /* shorthand for row-gap and column-gap */
}
C
od
eW

Placing Items
ith

You can control where an item appears in the grid using grid-column and grid-
row .
H
ar

.item {
grid-column: 1 / 3; /* spans column 1 to 2 (exclusive of 3) */
ry

grid-row: 2 / 3;
}

You can also use span :


.item {

grid-column: span 2;
}

Named Areas (Optional but Powerful)

Define areas using grid-template-areas :

.container {

display: grid;
grid-template-areas:
"header header"
"sidebar content"
"footer footer";

grid-template-columns: 1fr 3fr;


grid-template-rows: auto 1fr auto;
}
C

Then assign each item:


od

.header { grid-area: header; }


eW

.sidebar { grid-area: sidebar; }


.content { grid-area: content; }
ith

.footer { grid-area: footer; }


H
ar

Auto-Placement
ry

Grid can automatically place items:

.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}

This makes the layout responsive, automatically filling space with flexible-width
items.

Complete Example

<div class="container">

<div class="item header">Header</div>


<div class="item sidebar">Sidebar</div>
<div class="item content">Content</div>
<div class="item footer">Footer</div>
</div>

.container {
display: grid;
grid-template-areas:
C

"header header"
od

"sidebar content"
"footer footer";
eW

grid-template-columns: 1fr 3fr;


grid-template-rows: auto 1fr auto;
gap: 10px;
ith

.header { grid-area: header; background: #ddd; }


H

.sidebar { grid-area: sidebar; background: #bbb; }


ar

.content { grid-area: content; background: #eee; }


.footer { grid-area: footer; background: #ccc; }
ry

.item {
padding: 20px;
}
Summary

• CSS Grid is perfect for page layouts with rows and columns.
• grid-template-columns and grid-template-rows define structure.
• Use grid-column and grid-row to place or span items.
• Named grid areas make your layout more readable and semantic.
• Auto-fill and auto-fit allow responsive grids.
C
od
eW
ith
H
ar
ry
CSS Media Queries
Media Queries allow you to create responsive designs by applying CSS rules based
on the device’s characteristics — such as screen width, height, orientation, and
resolution.

They are essential for building mobile-first, responsive websites that adapt to
various screen sizes (phones, tablets, desktops).

Basic Syntax

@media (condition) {
/* CSS rules */
}
C

Example: Target screens smaller than 768px


od

@media (max-width: 768px) {


eW

body {
background-color: lightgray;
}
ith

}
H

This CSS will apply only when the screen width is 768px or less.
ar
ry
Common Conditions

Media
Description Example
Feature

max- @media (max-width:


Target screens up to a width
width 600px)

min- Target screens starting from a @media (min-width:


width width 1024px)

orienta Target portrait or landscape @media (orientation:


tion mode landscape)

max- @media (max-height:


Target screen height
height 500px)

resolut @media (min-resolution:


Target pixel density
ion 2dppx)
C

Responsive Layout Example


od

.container {
eW

padding: 20px;
font-size: 18px;
}
ith

@media (max-width: 768px) {


H

.container {
ar

padding: 10px;
font-size: 16px;
ry

}
}

@media (max-width: 480px) {


.container {
font-size: 14px;
}
}

This approach ensures your layout adjusts smoothly as screen sizes change.

Combining Multiple Conditions

@media (min-width: 600px) and (max-width: 1024px) {


.sidebar {
display: none;
}
}

You can combine conditions using and , or , or not .

Mobile-First Approach
C

Start with styles for small screens, then use min-width to add enhancements for
od

larger screens.
eW

/* Mobile-first (default) */
.card {
ith

font-size: 14px;
}
H
ar

/* Tablet and up */
@media (min-width: 768px) {
ry

.card {
font-size: 16px;
}
}

/* Desktop and up */

@media (min-width: 1024px) {


.card {
font-size: 18px;

}
}

Media Queries for Print

@media print {
body {
background: white;
color: black;
}

.no-print {
display: none;

}
}
C

Used to style web pages when printed.


od
eW

Summary

• Media queries help build responsive and accessible websites.


ith

• Use min-width for mobile-first, scalable layouts.


H

• Combine media queries for precise control across devices.


ar
ry
CSS Variables and Custom Properties
CSS Variables, also called Custom Properties, allow you to store values in a
reusable way — making your CSS more maintainable and dynamic.

They follow the pattern of:

--custom-name: value;

Declaring a CSS Variable

Variables are declared inside a selector using the -- prefix:

:root {
C

--primary-color: #3498db;
--font-size: 16px;
od

}
eW

• :root is the highest-level selector (like html ) — variables here are global.
• Variables declared inside :root can be used throughout your stylesheet.
ith
H

Using a CSS Variable


ar
ry

Use the var() function to apply the variable:

body {
color: var(--primary-color);
font-size: var(--font-size);
}

Why Use CSS Variables?

✅ Consistency ✅ Easy to update (change in one place) ✅ Theme support


(light/dark mode) ✅ Cleaner, scalable CSS

Example: Theming with CSS Variables

:root {
--bg-color: white;

--text-color: black;
}

body {
C

background-color: var(--bg-color);
color: var(--text-color);
od

}
eW

You can override these in a different class for themes:


ith

.dark-theme {
--bg-color: #121212;
H

--text-color: #ffffff;
ar

}
ry

Now just add class="dark-theme" to <body> or a wrapper div to switch themes.


Fallback Values

If a variable isn’t defined, you can specify a fallback:

h1 {
color: var(--heading-color, blue);
}

If --heading-color is not set, blue will be used instead.

Scoped Variables

Variables can also be scoped to a class or element:

.card {
--border-radius: 10px;
border-radius: var(--border-radius);
}
C
od

Only elements within .card can access this variable.


eW

Real-World Example
ith
H

:root {
--btn-padding: 12px 24px;
ar

--btn-color: #fff;
--btn-bg: #2ecc71;
ry

.button {
padding: var(--btn-padding);
color: var(--btn-color);

background-color: var(--btn-bg);
border: none;
border-radius: 6px;

cursor: pointer;
}

Update theme by just changing variables in :root .

Summary

• Use --variable-name to declare and var(--variable-name) to use.


• Declare in :root for global usage.
• Support theming, dynamic styles, and cleaner code.
• Can be scoped or overridden for flexibility.
C
od
eW
ith
H
ar
ry
CSS Transitions and Animations
CSS provides powerful tools for creating smooth, engaging user experiences
through transitions and animations. These effects can enhance the visual appeal
and usability of your website without needing JavaScript.

1. CSS Transitions

A transition is used to change CSS properties smoothly over a given duration.

Basic Syntax

selector {
transition: property duration timing-function delay;
}
C
od

• property : The CSS property to animate (e.g., background-color ,


transform , etc.)
eW

• duration : How long the transition lasts (e.g., 0.3s , 1s )


• timing-function : The pace of the transition ( ease , linear , ease-in ,
ith

ease-out , etc.)

• delay : Optional delay before starting


H
ar

Example
ry

.button {
background-color: blue;
color: white;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: green;

This smoothly changes the button’s background color on hover.

Shorthand vs Longhand
Shorthand:

transition: all 0.5s ease;

Longhand:

transition-property: background-color;

transition-duration: 0.5s;
transition-timing-function: ease;
transition-delay: 0s;
C
od

2. CSS Animations
eW

CSS animations allow more complex, keyframe-based changes over time.


ith

Basic Syntax
H
ar

selector {
animation: animation-name duration timing-function delay iteration-count
ry

direction;
}

Keyframes
Define how the animation should behave at different points:
@keyframes slideIn {

from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}

Example

.box {
width: 100px;
height: 100px;
background-color: red;
animation: slideIn 1s ease-in-out;
}
C
od

Animation Properties
eW

Property Description
ith

animation-name Name of the @keyframes to use

How long the animation takes


H

animation-duration
ar

animation-delay Delay before starting


ry

animation-iteration-
Number of times to run (or infinite )
count

animation-direction normal , reverse , alternate

animation-fill-mode Defines final state: forwards , backwards , both


Property Description

animation-play-state running or paused

Looping Animations

.pulse {
animation: pulse 2s infinite;
}

@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.1);

}
}
C
od

Combining Transitions and Animations


eW

Transitions are great for hover and interactive effects. Animations are better for
more dynamic, self-running effects.
ith

Example using both:


H

.card {
ar

transition: transform 0.3s;


ry

.card:hover {
transform: scale(1.05);
}

@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }

.card {
animation: fadeIn 1s ease;
}

Summary

• Use transitions for smooth changes on hover, focus, etc.


• Use animations for keyframe-driven effects like entrance, bounce, etc.
• Keep animations subtle and purposeful — avoid overwhelming the user.
C
od
eW
ith
H
ar
ry
CSS Transformations
CSS transforms allow you to visually manipulate elements by rotating, scaling,
skewing, or translating them. Transforms are applied using the transform
property.

1. transform Property

Syntax:

selector {

transform: function(value);
}
C

Multiple functions can be combined:


od

transform: translateX(50px) rotate(45deg) scale(1.2);


eW
ith

2. Types of Transformations
H

a. translate()
ar
ry

Moves an element from its current position.

.box {
transform: translateX(50px); /* Move 50px to the right */
}
Other variations:

• translateY(30px) – moves vertically


• translate(50px, 30px) – moves on both axes

b. rotate()

Rotates the element clockwise by default.

.box {
transform: rotate(45deg); /* Rotate 45 degrees */
}

Use negative values to rotate counter-clockwise:

transform: rotate(-45deg);
C

c. scale()
od

Scales the size of an element.


eW

.box {
transform: scale(1.5); /* Increase size by 1.5x */
ith

}
H

• scaleX(2) – scales horizontally


ar

• scaleY(0.5) – scales vertically


ry

d. skew()

Slants an element along the X and/or Y axis.


.box {

transform: skew(20deg, 10deg); /* Skew in X and Y */


}

Individual axis:

• skewX(20deg)
• skewY(10deg)

e. matrix()

A shorthand to apply multiple transformations using a 2D matrix. Rarely used


directly because it’s less readable.

3. Transform Origin

By default, transforms are applied relative to the center of the element. You can
C

change this with transform-origin .


od

.box {
eW

transform: rotate(45deg);
transform-origin: top left;
}
ith
H
ar

4. Combining Multiple Transforms


ry

.box {
transform: translateX(100px) rotate(30deg) scale(1.2);
}
The order matters: transforms are applied from left to right.

5. 3D Transforms (Intro Only)

• rotateX() , rotateY() , and rotateZ() add 3D rotation.


• perspective property is needed to see 3D depth.

Example:

.box {
transform: rotateY(45deg);
transform-style: preserve-3d;
}

Summary
C

Transform Function Description


od

translate() Moves element

Rotates element
eW

rotate()

scale() Resizes element


ith

skew() Slants element


H

matrix() Combines multiple transforms


ar

CSS Transforms are foundational for building modern UI effects — often combined
with transitions and animations.
ry
Introduction to JavaScript

What is JavaScript?
JavaScript is a programming language used to make web pages interactive. While
HTML structures the page and CSS styles it, JavaScript adds behavior.

For example:

• Want to show a popup when a user clicks a button? Use JavaScript.


• Want to build a game, form validation, or fetch data from a server? Use
JavaScript.

JavaScript runs in the browser, meaning it executes on the user’s device.


C

Why JavaScript?
od

• Works on all modern browsers


• Essential for front-end development
eW

• Used by frameworks like React, Vue, Angular


• Can also be used on the backend ([Link])
ith
H

Where Can You Write JavaScript?


ar

There are 3 common ways to write JavaScript in a webpage:


ry

Inline (Not recommended)

<button onclick="alert('Hello!')">Click Me</button>


In a <script> tag inside HTML

<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<script>

[Link]("JavaScript is working!");
</script>
</body>
</html>

External JavaScript File (Recommended)

<!-- [Link] -->


<!DOCTYPE html>
<html>

<body>
<h1>Hello</h1>
<script src="[Link]"></script>
</body>
C

</html>
od

// [Link]
eW

[Link]("Hello from external JS file!");


ith

Your First JavaScript Code


H

Let’s start with the simplest code that prints something:


ar
ry

[Link]("Hello JavaScript");

[Link]() is used to print messages to the browser console.


How to Open the Console
• Right-click on the page > Inspect
• Go to the Console tab
• You’ll see outputs from [Link]() here

JavaScript is Case-Sensitive

let x = 5;
let X = 10;

[Link](x); // 5
[Link](X); // 10

Comments in JavaScript
Use comments to explain your code:
C

// This is a single-line comment


od

/*
This is a
eW

multi-line comment
*/
ith
H

Summary
ar

• JavaScript makes your website interactive.


ry

• You can write it inside HTML or in separate .js files.


• Use [Link]() to test your code.
• Practice by writing simple scripts and watching them work in the browser.
Variables and Data Types in JavaScript

What is a Variable?

A variable is a named container for storing data. In JavaScript, we can declare


variables using:

let name = "Harry";


const age = 25;
var city = "Delhi";

let vs const vs var


C

Keyword Reassignable? Block Scoped? Hoisted?


od

let Yes Yes Yes

No Yes Yes
eW

const

var Yes No Yes (but undefined)


ith

Use let when:


H

• You plan to change the value later.


ar
ry

let score = 0;
score = 10;

Use const when:

• The value should not change.


const pi = 3.14159;

// pi = 3.14; Error

Avoid var

• It behaves inconsistently due to hoisting and lack of block scoping.

JavaScript Data Types

JavaScript has two categories of data types:

1. Primitive (Value) Data Types


These are immutable and stored directly in memory.

Data Type Example


C

string "Hello World"


od

number 42 , 3.14 , -100


eW

boolean true , false

null null
ith

undefined undefined
H

bigint 12345678901234567890n
ar

symbol Symbol("id")
ry

let name = "Harry"; // string


let age = 25; // number
let isCool = true; // boolean
let noValue = null; // null
let notDefined; // undefined
Note: typeof null is "object" due to a long-standing bug in JS.

2. Non-Primitive (Reference) Data Types


These hold references to memory, not actual values.

Type Example

Object { name: "Harry" }

Array [1, 2, 3]

Function function() {}

Date, RegExp, etc. Built-in Objects

let person = { name: "Harry", age: 25 }; // Object


let colors = ["red", "blue", "green"]; // Array
let greet = function() { [Link]("Hi") }; // Function
C
od

Differences Between Primitive and Reference Types


eW

Feature Primitive Reference

Stored as Value Memory address (reference)


ith

Mutable? Immutable Mutable


H

Copied as Value Reference


ar
ry

let a = 10;
let b = a; // Copy by value
b = 20;
[Link](a); // 10 (unchanged)

let obj1 = { x: 1 };
let obj2 = obj1; // Copy by reference
obj2.x = 2;

[Link](obj1.x); // 2 (both point to same object)

typeof Operator

Use typeof to check the type of a variable:

[Link](typeof "Hello"); // string


[Link](typeof 100); // number
[Link](typeof true); // boolean
[Link](typeof undefined); // undefined
[Link](typeof null); // object (quirk!)
[Link](typeof {}); // object
[Link](typeof []); // object (array is also object)

[Link](typeof function(){});// function


C
od

Summary
eW

• Use let for changeable values, const for constants.


• Understand the difference between primitive (copied by value) and reference
types (copied by reference).
ith

• typeof is useful but not perfect (e.g., typeof null === "object" ).
H
ar
ry
Naming Variables in JavaScript

Rules for Naming Variables

1. Variable names must begin with a letter, underscore _ , or dollar sign $ .


Valid examples:

let name;
let _count;
let $price;

Invalid example:

let 1user; // Invalid: cannot start with a number


C

2. Use camelCase for variable names. In JavaScript, the convention is to use


camelCase, where the first word is lowercase and each new word starts with an
od

uppercase letter:
eW

let userName;
let totalAmount;
ith

let isLoggedIn;
H

3. Be descriptive and meaningful. Use names that describe the purpose of the
ar

variable:
ry

let age = 25; // Good


let userAge = 25; // Better
let a = 25; // Poor
4. Avoid using reserved keywords. JavaScript has reserved words that cannot be
used as variable names:

let let; // Invalid

let function; // Invalid

5. No spaces or special characters. Variable names must not contain spaces or


symbols like @ , - , or # :

let user name; // Invalid


let user-name; // Invalid
let user_name; // Valid, but camelCase is preferred

Good Examples

let firstName = "John";


let totalPrice = 100;
C

let isAvailable = true;


od
eW

Bad Examples
ith

let x = "John"; // Not descriptive


H

let user_123_abc = 25; // Unclear naming


let 1user = "Alice"; // Invalid syntax
ar
ry

Boolean Variable Naming

When naming variables that store true or false , use prefixes like is , has , or
can to make their intent clear:
let isLoggedIn = true;

let hasAccess = false;


let canEdit = true;

Summary

• Use camelCase.
• Choose meaningful names.
• Start names with a letter, _ , or $ .
• Avoid JavaScript keywords.
• Avoid spaces and special characters.
C
od
eW
ith
H
ar
ry
Operators in JavaScript
Operators are symbols used to perform operations on values and variables. For
example, you use + to add two numbers, = to assign values, and == to
compare values.

1. Arithmetic Operators

Used to perform mathematical operations.

Operator Description Example Result

+ Addition 5 + 2 7

- Subtraction 5 - 2 3

Multiplication
C

* 5 * 2 10
od

/ Division 10 / 2 5

% Modulus (Remainder) 5 % 2 1
eW

** Exponentiation 2 ** 3 8
ith

++ Increment let x = 1; x++ 2

-- Decrement let x = 2; x-- 1


H
ar
ry

2. Assignment Operators

Used to assign values to variables.


Operator Example Same As

= x = 5 Assign 5 to x

+= x += 2 x = x + 2

-= x -= 3 x = x - 3

*= x *= 4 x = x * 4

/= x /= 2 x = x / 2

%= x %= 2 x = x % 2

3. Comparison Operators

Used to compare two values. They return a Boolean ( true or false ).

Operator Description Example Result

== Equal (loose) 5 == '5' true


C

=== Strict equal (type + value) 5 === '5' false


od

!= Not equal 5 != '5' false


eW

!== Strict not equal 5 !== '5' true

> Greater than 5 > 3 true


ith

< Less than 5 < 3 false


H

>= Greater than or equal 5 >= 5 true


ar

<= Less than or equal 3 <= 5 true


ry

4. Logical Operators

Used to combine multiple conditions.


Operator Description Example Result

&& Logical AND true && false false

|| Logical OR true || false true

! Logical NOT !true false

Example:

let age = 20;


if (age > 18 && age < 60) {
[Link]("You are eligible");
}

5. Ternary Operator

A shorthand way to write simple if...else .


C

let age = 17;


od

let result = age >= 18 ? "Adult" : "Minor";


[Link](result); // "Minor"
eW
ith

Summary
H

• Use arithmetic operators to perform math.


ar

• Use assignment operators to update variables.


ry

• Use comparison and logical operators for decision making.


• Ternary operator is a cleaner way to write simple conditions.
If-Else Statements in JavaScript

What is an If-Else Statement?

An if statement is used to run a block of code only if a specified condition is


true. You can use else or else if to run different blocks of code based on
different conditions.

Basic Syntax

if (condition) {
// code to run if condition is true
} else {
// code to run if condition is false
C

}
od
eW

Example
ith

let age = 18;


H
ar

if (age >= 18) {


[Link]("You are an adult.");
ry

} else {
[Link]("You are a minor.");
}
if-else-if Ladder

You can check multiple conditions using else if :

let score = 85;

if (score >= 90) {


[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else if (score >= 70) {
[Link]("Grade: C");

} else {
[Link]("Grade: F");
}

Nested if Statements
C

You can place one if statement inside another:


od

let age = 25;


eW

let hasID = true;

if (age >= 18) {


ith

if (hasID) {
[Link]("Access granted.");
H

} else {
[Link]("ID required.");
ar

}
ry

} else {
[Link]("Access denied. You must be at least 18.");
}
Using the Ternary Operator (Short Form)

The ternary operator is a shorter way to write simple if-else statements:

let isLoggedIn = true;

let message = isLoggedIn ? "Welcome back!" : "Please log in.";


[Link](message);

Summary

• Use if to test a condition.


• Use else for an alternative block if the condition is false.
• Use else if to test multiple conditions.
• The ternary operator is a compact way to write simple if-else logic.
C
od
eW
ith
H
ar
ry
Objects in JavaScript – Deep Dive
Objects in JavaScript are used to store collections of key-value pairs. They are one
of the most important and widely used data types in the language.

Creating an Object

You can create an object using object literal syntax:

let person = {
name: "Alice",

age: 30,
isEmployed: true
};
C
od

Accessing Object Properties


eW

You can access properties using dot notation or bracket notation:


ith

[Link]([Link]); // "Alice"
H

[Link](person["age"]); // 30
ar

Use bracket notation when the property name is stored in a variable or contains
ry

special characters:

let key = "isEmployed";


[Link](person[key]); // true
Modifying Object Properties

[Link] = 31;
person["name"] = "Bob";

Adding New Properties

[Link] = "Delhi";

person["hobby"] = "Reading";

Deleting Properties

delete [Link];
C
od

Checking if a Property Exists


eW

[Link]("age" in person); // true


ith

[Link]([Link]("city")); // true
H
ar

Looping Through Object Properties


ry

Use for...in to iterate over an object’s keys:


for (let key in person) {

[Link](key + ": " + person[key]);


}

Nested Objects

Objects can contain other objects:

let student = {
name: "John",
address: {
city: "Mumbai",
pin: 400001
}
};

[Link]([Link]); // "Mumbai"
C
od

Objects and Functions


eW

Objects can have methods (functions defined inside them):


ith

let user = {
H

name: "Sara",
greet: function () {
ar

[Link]("Hello, " + [Link]);


ry

}
};

[Link](); // "Hello, Sara"

You can also use shorthand syntax for methods:


let user = {

name: "Sara",
greet() {
[Link]("Hello, " + [Link]);
}
};

Summary

• Objects store key-value pairs.


• Access and modify properties with dot or bracket notation.
• Use for...in to loop through properties.
C
od
eW
ith
H
ar
ry
Loops in JavaScript
Loops allow you to execute a block of code multiple times, which is useful for tasks
like iterating over arrays or repeating operations until a condition changes.

1. for Loop

Syntax

for (initialization; condition; finalExpression) {


// code to execute on each iteration

Example
C

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


od

[Link](i); // prints 0, 1, 2, 3, 4
}
eW

• initialization: executed once before the loop starts (e.g., let i = 0 )


ith

• condition: checked before each iteration; if true , the loop continues


• finalExpression: executed at the end of each iteration (e.g., i++ )
H
ar
ry

2. while Loop

Syntax
while (condition) {

// code to execute while condition is true


}

Example

let count = 0;
while (count < 3) {
[Link](count); // prints 0, 1, 2
count++;
}

• The condition is evaluated before each iteration.


• If the condition is initially false , the loop body may never run.

3. do...while Loop
C

Syntax
od

do {
eW

// code to execute
} while (condition);
ith

Example
H

let num = 0;
ar

do {
[Link](num); // prints 0
ry

num++;
} while (num < 1);

• The loop body executes at least once, then the condition is checked.
4. for...of Loop

Purpose: Iterate over iterable objects (arrays, strings, etc.).

Syntax

for (variable of iterable) {


// code using variable
}

Example

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


for (let color of colors) {
[Link](color);
}

5. for...in Loop
C
od

Purpose: Iterate over the keys of an object.

Syntax
eW

for (key in object) {


ith

// code using key and object[key]


}
H
ar

Example
ry

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


for (let prop in person) {
[Link](prop + ": " + person[prop]);
// prints "name: Alice" and then "age: 30"
}
Summary

• for : general-purpose loop with counter.


• while : loop based on a condition.
• do...while : condition checked after first execution.
• for...of : iterate over iterable values.
• for...in : iterate over object keys.
C
od
eW
ith
H
ar
ry
Control Flow in JavaScript
Control flow means how your code runs step-by-step, and how you can make
decisions or repeat actions.

JavaScript runs code from top to bottom, but you can control the flow using:

• Conditional statements ( if , else , switch )


• Loops ( for , while , do...while )

1. if , else if , and else

Use these to run code only if a condition is true.

let age = 18;


C

if (age >= 18) {


od

[Link]("You are an adult");

} else if (age >= 13) {


eW

[Link]("You are a teenager");


} else {
[Link]("You are a child");
ith

}
H

The first condition that is true will run, others will be skipped.
ar
ry

2. switch Statement

Use this when you have multiple fixed cases to check.


let day = "Monday";

switch (day) {
case "Monday":
[Link]("Start of the week");
break;
case "Friday":
[Link]("End of the week");
break;
default:
[Link]("Midweek day");
}

• Use break to stop after each case.


• default runs if no cases match.

3. Loops
C

Loops let you run code multiple times.


od

a. for Loop
eW

Used when you know how many times to repeat.


ith

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


[Link]("Count:", i);
H

}
ar

b. while Loop
ry

Used when the number of repetitions is unknown.

let i = 1;
while (i <= 3) {
[Link]("While loop:", i);
i++;
}

c. do...while Loop

Same as while , but runs at least once, even if the condition is false.

let i = 1;
do {
[Link]("Do while:", i);
i++;

} while (i <= 3);

4. break and continue

• break = exit the loop immediately


• continue = skip the current iteration
C

Example:
od
eW

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


if (i === 3) continue; // skip 3
[Link](i); // 1, 2, 4, 5
ith

}
H
ar

Summary
ry

• Use if , else if , and else to control logic.


• Use switch for multiple case checking.
• Use loops to repeat actions.
• Use break to stop loops, and continue to skip one turn.
break and continue in JavaScript

break Statement

The break statement is used to exit a loop prematurely, before the loop condition
evaluates to false.

Syntax

break;

Example: Exiting a loop when a condition is met

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


if (i === 5) {
C

break; // exits the loop when i equals 5


od

}
[Link](i);
eW

Output:
ith

0
H

1
ar

2
3
ry

Use Cases
• Exiting a for , while , or do...while loop early
continue Statement

The continue statement skips the current iteration of a loop and proceeds to the
next one.

Syntax

continue;

Example: Skipping a loop iteration

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


if (i % 2 === 0) {
continue; // skips even numbers

}
[Link](i);
}
C

Output:
od

1
eW

3
5
7
ith

9
H

Use Cases
ar

• Skipping specific iterations based on a condition


ry

• Useful in filtering or avoiding certain values during iteration


Summary

Statement Purpose Effect

break Exit the loop entirely Stops loop execution

Skip current
continue Moves to the next iteration immediately
iteration

Both statements help in controlling loop execution flow more precisely based on
conditions.
C
od
eW
ith
H
ar
ry
Functions in JavaScript
A function is a block of code that performs a specific task. Instead of repeating the
same code again and again, you can write it once in a function and call it whenever
needed.

1. Function Declaration

This is the most common way to define a function.

function greet() {
[Link]("Hello, JavaScript!");
}

greet(); // Call the function


C
od
eW

2. Function with Parameters

You can pass data into functions using parameters.


ith
H

function greetUser(name) {
[Link]("Hello, " + name);
ar

}
ry

greetUser("Ali"); // Output: Hello, Ali


3. Function with Return Value

Functions can return values using the return keyword.

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

let result = add(5, 3); // 8


[Link](result);

4. Function Expressions

Functions can also be stored in variables.

const sayHi = function() {


[Link]("Hi there!");
};
C
od

sayHi();
eW

5. Arrow Functions (ES6+)


ith

A shorter way to write functions.


H
ar

const square = (num) => {


ry

return num * num;


};

[Link](square(4)); // 16
One-liner version (if only returning a value):

const multiply = (a, b) => a * b;


[Link](multiply(2, 3)); // 6

6. Scope (Simple Explanation)

Variables declared inside a function are local and can’t be accessed outside.

function showAge() {
let age = 25;
[Link](age);
}

showAge();
// [Link](age); // Error: age is not defined
C
od

7. Why Use Functions?


eW

• Organize code into reusable pieces


• Avoid repetition
• Make your code cleaner and easier to understand
ith

• Useful in handling events and user interactions


H
ar

Summary
ry

• Use function to define reusable code blocks.


• Pass data using parameters and return results with return .
• Store functions in variables or use arrow functions for brevity.
• Functions help you write cleaner and modular code.
Arrays in JavaScript
An array is a collection of items stored in a single variable. It lets you store multiple
values — like a list of names, numbers, or even other arrays.

1. Creating Arrays

let fruits = ["apple", "banana", "mango"];


let numbers = [10, 20, 30, 40];

You can mix data types, but it’s better to keep arrays consistent.

let mixed = [1, "hello", true];


C
od

2. Accessing and Modifying Elements


eW

Arrays use zero-based indexing.


ith

let fruits = ["apple", "banana", "mango"];


[Link](fruits[0]); // "apple"
H

fruits[1] = "orange"; // change "banana" to "orange"


ar

[Link](fruits); // ["apple", "orange", "mango"]


ry
3. Array Length

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


[Link]([Link]); // 3

4. Common Array Methods

a. push() – Add item at the end

[Link]("yellow");

b. pop() – Remove last item

[Link]();
C

c. shift() – Remove first item


od

[Link]();
eW

d. unshift() – Add item at the beginning


ith

[Link]("pink");
H
ar
ry
5. Looping Through Arrays

Using for loop:

let fruits = ["apple", "banana", "mango"];


for (let i = 0; i < [Link]; i++) {

[Link](fruits[i]);
}

Using for...of loop:

for (let fruit of fruits) {


[Link](fruit);
}

6. map() – Transform Array


C

Creates a new array by applying a function to each item.


od

let numbers = [1, 2, 3];


eW

let doubled = [Link](num => num * 2);


[Link](doubled); // [2, 4, 6]
ith
H

7. filter() – Filter Items


ar
ry

Returns a new array of items that match a condition.

let scores = [30, 50, 90, 20];


let passed = [Link](score => score >= 50);
[Link](passed); // [50, 90]
8. Other Useful Methods

Method Description

includes() Checks if an item exists in the array

indexOf() Finds index of an item

slice() Extracts part of the array

join() Joins array into a string

Example:

let names = ["Ali", "Sara", "John"];


[Link]([Link]("Sara")); // true
[Link]([Link]("John")); // 2
[Link]([Link](" - ")); // Ali - Sara - John
C
od

Summary
eW

• Arrays store lists of data in one variable.


• Use indexing to access or update items.
• Common methods like push , pop , map , filter make array handling
ith

easier.
H

• Looping is essential for displaying or processing lists.


ar
ry
Common Array Methods

a. push() – Add item at the end

[Link]("yellow");

b. pop() – Remove last item

[Link]();

c. shift() – Remove first item


C

[Link]();
od

d. unshift() – Add item at the beginning


eW
ith

[Link]("pink");
H
ar
ry
Looping Through Arrays

Using for loop:

let fruits = ["apple", "banana", "mango"];


for (let i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}

Using for...of loop:

for (let fruit of fruits) {


[Link](fruit);

}
C

map() – Transform Array


od
eW

Creates a new array by applying a function to each item.


ith

let numbers = [1, 2, 3];


let doubled = [Link](num => num * 2);
H

[Link](doubled); // [2, 4, 6]
ar
ry

filter() – Filter Items

Returns a new array of items that match a condition.


let scores = [30, 50, 90, 20];

let passed = [Link](score => score >= 50);


[Link](passed); // [50, 90]

Other Useful Methods


Method Description

includes() Checks if an item exists in the array

indexOf() Finds index of an item

slice() Extracts part of the array

join() Joins array into a string

Example:
C
od

let names = ["Ali", "Sara", "John"];


[Link]([Link]("Sara")); // true
eW

[Link]([Link]("John")); // 2
[Link]([Link](" - ")); // Ali - Sara - John
ith
H

Summary
ar
ry

• Arrays store lists of data in one variable.


• Use indexing to access or update items.
• Common methods like push , pop , map , filter make array handling
easier.
• Looping is essential for displaying or processing lists.
Strings in JavaScript

What is a String?

A string is a sequence of characters used to represent text.


It can contain letters, numbers, symbols, or even be empty.

In JavaScript, strings are written inside single quotes, double quotes, or backticks.

let single = 'Hello';


let double = "World";
let template = `Hello World`;

All three are valid, but backticks ( ` ) are useful for string interpolation (covered
later).
C
od

Declaring Strings
eW

let message = "Welcome to JavaScript!";


let name = 'Salman';
ith
H
ar

String Length
ry

You can check how many characters are in a string using the .length property.

let msg = "Hello";


[Link]([Link]); // 5
Multiline Strings

Using \n (newline character):

let text = "Line 1\nLine 2\nLine 3";

[Link](text);

Using template literals (backticks):

let multiline = `This is line 1


This is line 2
This is line 3`;
[Link](multiline);

String Indexing
C

Strings are indexed like arrays — the first character is at position 0 .


od
eW

let word = "JavaScript";


[Link](word[0]); // "J"
[Link](word[4]); // "S"
ith
H
ar

Strings are Immutable


ry

You cannot change a specific character in a string directly.

let greeting = "Hello";


greeting[0] = "Y"; // This will not work
[Link](greeting); // Still "Hello"
To change a string, you have to create a new one.

Concatenation (Combining Strings)

Using + operator:

let firstName = "Salman";


let lastName = "Khan";

let fullName = firstName + " " + lastName;


[Link](fullName); // "Salman Khan"

Summary

• Strings are sequences of characters.


• Use single, double, or backticks to define them.
• Strings are immutable.
C

• You can access characters using indices.


od

• Use + for concatenation or backticks for string interpolation.


eW
ith
H
ar
ry
Template Literals in JavaScript
Template literals are a way to work with strings in JavaScript that allow for easier
multi-line strings and string interpolation.

let name = "Salman";


let message = `Hello, ${name}!`;
[Link](message); // "Hello, Salman!"

Template literals are enclosed in backticks ( ` ) and can contain placeholders for
variables or expressions, which are wrapped in ${} .

Multiline Strings with Template Literals

You can create multi-line strings without using escape characters:


C

let multiline = `This is line 1


od

This is line 2
This is line 3`;
eW

[Link](multiline);
ith

Summary
H

• Template literals use backticks ( ` ).


ar

• They allow for string interpolation with ${} .


ry

• Multi-line strings can be created easily without escape characters.


String Methods in JavaScript
JavaScript provides many built-in methods to work with strings — to inspect,
modify, or extract information from them.

All string methods return a new string or value. The original string remains
unchanged.

1. length

Returns the number of characters in the string.

let text = "JavaScript";


[Link]([Link]); // 10
C
od

2. toUpperCase() and toLowerCase()


eW

Convert a string to upper or lower case.


ith

let name = "Ali";


H

[Link]([Link]()); // "ALI"
[Link]([Link]()); // "ali"
ar
ry

3. trim()

Removes extra whitespace from both ends of a string.


let input = " Hello World ";

[Link]([Link]()); // "Hello World"

4. includes()

Checks if a string contains another string.

let msg = "Learn JavaScript";


[Link]([Link]("Java")); // true
[Link]([Link]("Python")); // false

5. indexOf() and lastIndexOf()

Returns the index of the first/last occurrence of a substring. Returns -1 if not


found.
C
od

let str = "banana";

[Link]([Link]("a")); // 1
eW

[Link]([Link]("a")); // 5
ith
H

6. startsWith() and endsWith()


ar

Check if a string starts or ends with a specific value.


ry

let title = "Frontend Developer";


[Link]([Link]("Front")); // true
[Link]([Link]("Dev")); // false
7. slice(start, end)

Extracts part of a string. end is not included.

let word = "JavaScript";


[Link]([Link](0, 4)); // "Java"
[Link]([Link](4)); // "Script"

8. substring(start, end)

Similar to slice() , but cannot accept negative indexes.

let text = "Coding";


[Link]([Link](0, 3)); // "Cod"
C

9. replace(old, new)
od

Replaces the first occurrence of a substring.


eW

let msg = "I love Python";


[Link]([Link]("Python", "JavaScript")); // "I love JavaScript"
ith
H

Note: Only the first match is replaced. To replace all, use a regular expression
with /g .
ar
ry

let msg = "apple apple apple";


[Link]([Link](/apple/g, "banana")); // "banana banana banana"
10. split(separator)

Splits a string into an array based on the given separator.

let data = "HTML,CSS,JavaScript";


let parts = [Link](",");
[Link](parts); // ["HTML", "CSS", "JavaScript"]

11. charAt(index)

Returns the character at a specific position.

let lang = "JavaScript";


[Link]([Link](0)); // "J"
C

12. repeat(count)
od

Repeats a string multiple times.


eW

let wow = "ha";


[Link]([Link](3)); // "hahaha"
ith
H
ar

Summary
ry

Method Description

.length String length

.toUpperCase() Convert to uppercase


Method Description

.toLowerCase() Convert to lowercase

.trim() Remove spaces from both ends

.includes() Check if string contains a value

.indexOf() Index of first occurrence

.lastIndexOf() Index of last occurrence

.startsWith() Check if string starts with a substring

.endsWith() Check if string ends with a substring

.slice() Extract part of a string

.replace() Replace a part of the string

.split() Convert string to array

.charAt() Get character at specific position

.repeat() Repeat a string multiple times


C
od
eW
ith
H
ar
ry
What is the DOM?

Introduction

The DOM (Document Object Model) is a programming interface provided by the


browser that represents an HTML or XML document as a structured tree of objects.
Each element, attribute, and piece of text in the HTML document becomes a node
in the DOM tree.

This allows JavaScript to interact with the HTML and CSS of a web page — you can
use JavaScript to read and modify the page’s structure, content, and style
dynamically.

Key Points:
• The DOM is not part of JavaScript, but it is provided by the browser’s Web
APIs.
C

• The browser turns HTML into a tree structure called the DOM.
od

• JavaScript can use this tree to:


• Select elements
eW

• Modify content or style


• Add or remove elements
ith

• Respond to user interactions


H

Example HTML
ar
ry

<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>

<body>
<h1>Hello, DOM!</h1>
<p>This is a paragraph.</p>

</body>
</html>

How the DOM Sees It

The browser parses the above HTML and creates a tree-like structure:

• document

• html

• head

• title

• body

• h1
• p
C
od

Accessing the DOM in JavaScript


eW

The document object is the entry point to the DOM in JavaScript.


ith

[Link](document); // Logs the entire DOM tree


[Link]([Link]); // Logs the <body> element
H

[Link]([Link]); // Logs the content of <title>


ar

Summary
ry

• The DOM represents the page so that JavaScript can interact with it.
• You can access and modify HTML elements using JavaScript through the DOM.
• Understanding the DOM is essential for web development and dynamic page
interactions.
Accessing the DOM

Introduction

To manipulate or interact with elements in an HTML document using JavaScript,


you must first access the DOM. The browser provides two main global objects for
this:

• window
• document

The window Object

The window object represents the browser window. It is the global scope in a
C

browser environment. All global variables and functions become properties of the
window object.
od
eW

[Link](window); // Logs the global window object


[Link]([Link]); // Gets the width of the browser window
ith

You don’t usually need to reference window explicitly, because it’s the default
context:
H
ar

alert("Hello"); // Same as [Link]("Hello")


ry
The document Object

The document object is a property of the window and serves as the main entry
point to the web page’s DOM.

[Link](document); // Logs the entire HTML document as a DOM tree


[Link]([Link]); // Gets the current page URL

Common Properties of document

Property Description

[Link] Refers to the <body> element

[Link] Refers to the <head> element

[Link] Gets or sets the document’s title

[Link] Returns the full URL of the page


C
od

Example
eW

<!DOCTYPE html>
<html>
<head>
ith

<title>Accessing the DOM</title>


</head>
H

<body>
ar

<h1>Hello World</h1>
<script>
ry

[Link]([Link]); // "Accessing the DOM"


[Link] = "New Title";
</script>
</body>
</html>
Summary

• The window object is the global context and represents the browser window.
• The document object gives you access to the DOM structure of the HTML
page.
• You use document to navigate and manipulate HTML elements via JavaScript.
C
od
eW
ith
H
ar
ry
Selecting Elements in JavaScript
When working with the DOM (Document Object Model), selecting elements is
often the first step to manipulate them. JavaScript provides multiple methods to
select HTML elements based on their ID, class, tag name, or CSS selector.

1. getElementById

Selects a single element by its unique id .

2. getElementsByClassName

Returns a live HTMLCollection of all elements with the specified class name.

3. getElementsByTagName
C
od

Returns a live HTMLCollection of all elements with the specified tag name (e.g.,
div , p , h1 , etc.).
eW

4. querySelector
ith

Returns the first element that matches a specified CSS selector.


H
ar

5. querySelectorAll
ry

Returns a static NodeList of all elements that match a specified CSS selector.

These methods allow you to access and manipulate elements dynamically. We’ll
explore each of them in detail with examples next.
Changing textContent , innerHTML ,
value , and style in JavaScript

In this section, you’ll learn how to dynamically change content and appearance on
a webpage using JavaScript.

1. textContent

The textContent property sets or returns the text content of a node and its
descendants. It ignores any HTML tags.

<p id="demo">Hello <strong>World</strong></p>


C

const para = [Link]("demo");


od

[Link]([Link]); // Hello World


[Link] = "New text content";
eW
ith

2. innerHTML
H

The innerHTML property sets or returns the HTML content of an element.


ar
ry

<p id="demo">Hello</p>

const para = [Link]("demo");


[Link] = "<strong>Bold Text</strong>";
Use innerHTML carefully to avoid XSS vulnerabilities when inserting user-
provided data.

3. value

The value property is used to get or set the value of form elements such as
<input> , <textarea> , and <select> .

<input type="text" id="username" value="John">

const input = [Link]("username");


[Link]([Link]); // John
[Link] = "Harry";

4. style
C

You can change the inline style of an element using the style property.
od
eW

<p id="demo">This is a paragraph.</p>


ith

const para = [Link]("demo");


[Link] = "red";
H

[Link] = "20px";
[Link] = "#f0f0f0";
ar

Note: CSS property names with dashes (e.g., background-color ) become


ry

camelCase ( backgroundColor ) in JavaScript.


Summary

Property Purpose

textContent Changes plain text (ignores HTML)

innerHTML Changes or inserts HTML content

value Reads or sets form input values

style Dynamically changes inline CSS


C
od
eW
ith
H
ar
ry
Working with Attributes and Classes in
JavaScript
JavaScript allows you to dynamically control HTML element attributes and CSS
classes, enabling powerful, interactive web experiences.

1. Setting and Getting Attributes

Use setAttribute() to add or update an attribute and getAttribute() to


retrieve its value.

Example:

<img id="myImage" src="[Link]">


C
od

const img = [Link]("myImage");


eW

// Set a new attribute


[Link]("alt", "Company Logo");
ith

// Get an attribute value


[Link]([Link]("src")); // "[Link]"
H

// Update an existing attribute


ar

[Link]("src", "[Link]");
ry

2. Removing Attributes

Use removeAttribute() to completely remove an attribute from an element.


Example:

const img = [Link]("myImage");

// Remove the alt attribute


[Link]("alt");

3. Adding Classes

Use [Link]() to add one or more CSS classes to an element.

Example:

<div id="box"></div>

const box = [Link]("box");


C

[Link]("active");
[Link]("highlight", "shadow"); // Multiple classes
od
eW

4. Removing Classes
ith

Use [Link]() to remove one or more classes.


H
ar

[Link]("highlight");
ry

5. Toggling Classes

Use [Link]() to add a class if it doesn’t exist, or remove it if it does.


[Link]("hidden");

6. Checking for a Class

Use [Link]() to check whether an element has a specific class.

if ([Link]("active")) {
[Link]("The box is active");
}

Summary

Task Method

Set attribute [Link]()


C

Get attribute [Link]()


od

Remove attribute [Link]()


eW

Add class [Link]()

Remove class [Link]()


ith

Toggle class [Link]()


H

Check class existence [Link]()


ar
ry
Creating, Appending, and Removing
Elements in JavaScript
JavaScript allows you to dynamically create, insert, and remove elements from the
DOM, enabling highly interactive web applications.

1. Creating Elements

Use [Link]() to create a new HTML element in memory (not


yet in the DOM).

Example:

const newDiv = [Link]("div");


C

[Link] = "Hello, I was created dynamically!";


od

You can also set attributes or classes:


eW

[Link]("id", "dynamicDiv");
[Link]("box", "highlight");
ith
H
ar

2. Appending Elements
ry

Use methods like appendChild() or append() to insert an element into the


DOM.
Example:

<div id="container"></div>

const container = [Link]("container");


[Link](newDiv); // Adds the newDiv as the last child

Or using append() which allows multiple nodes or strings:

[Link]("Another text node", [Link]("hr"));

3. Prepending Elements

Use prepend() to insert an element at the beginning of the parent.

const heading = [Link]("h2");


[Link] = "Welcome!";
C

[Link](heading);
od
eW

4. Removing Elements
ith

To remove an element, you can use:


H

a) removeChild() (from parent)


ar
ry

[Link](newDiv);
b) [Link]() (directly on the element)

[Link](); // Removes the heading element directly

Note: [Link]() is widely supported but not in very old browsers.

Summary

Task Method

Create element [Link]()

Set text content [Link]

Add attribute or class setAttribute() , [Link]()

Append to parent appendChild() , append()

Prepend to parent prepend()

Remove from parent [Link](child)


C

Remove element directly [Link]()


od
eW
ith
H
ar
ry
Introduction to Events in JavaScript
In web development, events are actions or occurrences that happen in the browser,
often triggered by the user. JavaScript allows us to listen for these events and
respond with custom behavior.

Common examples of events include:

• Clicking a button
• Pressing a key
• Submitting a form
• Hovering over an element
• Scrolling the page

Why Events Matter

Events make your web pages interactive. They allow users to engage with your
C

content dynamically, rather than just reading static information.


od

Types of Common Events


eW

Here are some commonly used event types in JavaScript:


ith

1. click
H

Triggered when an element is clicked.


ar
ry

const button = [Link]('button');


[Link]('click', () => {
alert('Button clicked!');
});
2. keyup

Fires when the user releases a key on the keyboard.

const input = [Link]('input');


[Link]('keyup', (event) => {
[Link](`You typed: ${[Link]}`);

});

3. submit

Occurs when a form is submitted.

const form = [Link]('form');


[Link]('submit', (event) => {
[Link](); // Prevents the page from reloading
[Link]('Form submitted');

});

4. mouseover and mouseout


C
od

Fired when the mouse enters or leaves an element.


eW

const box = [Link]('.box');


[Link]('mouseover', () => {
[Link] = 'lightblue';
ith

});
[Link]('mouseout', () => {
H

[Link] = '';
ar

});
ry

Attaching Event Listeners

To handle events, use the addEventListener method:


[Link]('eventName', callbackFunction);

Example:

[Link]('h1').addEventListener('click', () => {
[Link]('Heading clicked!');

});

Summary

• Events allow JavaScript to react to user interactions.


• Use addEventListener to attach event handlers.
• Prevent default behavior using [Link]() if needed (e.g., in
forms).
• Always test your event listeners to ensure the intended behavior works across
different browsers.
C
od
eW
ith
H
ar
ry
Attaching Event Listeners in JavaScript
In JavaScript, you can use the addEventListener() method to handle user
interactions like clicks, typing, mouse movements, etc.

Syntax:

[Link](event, callback);

Common Events:
• click – when an element is clicked
• mouseover – when the mouse hovers over an element
• keydown – when a key is pressed
• submit – when a form is submitted
C

Examples:
od

<button id="clickBtn">Click Me</button>


eW

<input id="inputBox" placeholder="Type something" />


<form id="myForm">
<input type="text" required />
ith

<button type="submit">Submit</button>
</form>
H
ar

<script>
// Click event
ry

[Link]("clickBtn").addEventListener("click", () => {
alert("Button was clicked!");
});

// Keydown event
[Link]("inputBox").addEventListener("keydown", (e) => {
[Link]("Key pressed:", [Link]);
});

// Submit event
[Link]("myForm").addEventListener("submit", (e) => {
[Link]();
alert("Form submitted!");
});
</script>
C
od
eW
ith
H
ar
ry
Event Bubbling and Delegation in
JavaScript
Understanding event bubbling and event delegation is essential for writing clean,
efficient event-driven code in JavaScript.

What is Event Bubbling?

When an event occurs on a DOM element, it bubbles up through its ancestors. This
means the event is first captured and handled by the target element, and then
propagated upward to its parent, grandparent, and so on.

Example:

<div id="parent">
<button id="child">Click Me</button>
C

</div>
od

[Link]('child').addEventListener('click', () => {
eW

[Link]('Child clicked');
});
ith

[Link]('parent').addEventListener('click', () => {
[Link]('Parent clicked');
H

});
ar

Output when button is clicked:


ry

Child clicked
Parent clicked

This shows that the event bubbles from the child to the parent.
Stopping Event Bubbling

To stop the event from bubbling up the DOM tree, use:

[Link]();

[Link]('click', (event) => {


[Link]();
[Link]('This won’t bubble up');

});

What is Event Delegation?

Event delegation is a technique where a single event listener is added to a


common parent instead of individual child elements. This works because of event
bubbling.

Why Use Event Delegation?


C

• Improved performance with many child elements


od

• Simplified code
• Useful for dynamic elements added after page load
eW

Example:
ith

<ul id="menu">
H

<li>Home</li>
<li>About</li>
ar

<li>Contact</li>
</ul>
ry

Instead of attaching a click listener to every li , delegate it to the ul :

[Link]('menu').addEventListener('click', (event) => {


if ([Link] === 'LI') {
[Link](`You clicked on ${[Link]}`);
}

});

This even works if new <li> elements are added later using JavaScript.

Summary

• Event bubbling: Events move up the DOM tree from child to parent.
• Use [Link]() to prevent bubbling.
• Event delegation: Handle events at a parent level for better performance and
maintainability.
C
od
eW
ith
H
ar
ry
Preventing Default Behavior in
JavaScript
Many HTML elements have default behaviors. For example:

• Clicking a link navigates to a new URL


• Submitting a form reloads the page
• Pressing certain keys triggers built-in browser actions

In JavaScript, you can override these default behaviors using


[Link]() .

Syntax

[Link]('eventType', (event) => {


[Link]();
C

});
od

This method tells the browser not to perform the default action associated with
eW

the event.

Common Use Cases


ith
H

1. Preventing Form Submission


ar

By default, submitting a form reloads the page. You can prevent this to handle
ry

form data using JavaScript:

<form id="myForm">
<input type="text" />
<button type="submit">Submit</button>
</form>

const form = [Link]('myForm');

[Link]('submit', (event) => {


[Link]();
[Link]('Form submission prevented');
});

2. Preventing Link Navigation


You may want to handle navigation manually using JavaScript:

<a href="[Link] id="myLink">Go to CodeWithHarry</a>

const link = [Link]('myLink');

[Link]('click', (event) => {


C

[Link]();
[Link]('Navigation prevented');
od

});
eW

3. Preventing Checkbox Default Toggle


ith

In special cases, you might want to keep a checkbox from changing state:
H

const checkbox = [Link]('input[type="checkbox"]');


ar

[Link]('click', (event) => {


ry

[Link]();
[Link]('Checkbox toggle prevented');
});
When Not to Use preventDefault()

Avoid using preventDefault() unless necessary. Overusing it can confuse users


and break expected behavior (like tabbing between fields or pressing Enter to
submit).

Summary

• Use [Link]() to cancel default browser actions.


• Common in form handling, link overrides, or input control.
• Always test to ensure usability and accessibility are not harmed.
C
od
eW
ith
H
ar
ry
Working with localStorage in
JavaScript
The localStorage API allows you to store key-value data in the browser, with no
expiration date. This data persists across page reloads and browser sessions,
unless manually cleared.

Key Features

• Stores data as strings


• Synchronous API (blocking)
• Maximum storage capacity: around 5MB (varies by browser)
• Data is domain-specific

Basic Syntax
C
od

// Set item

[Link]('key', 'value');
eW

// Get item
ith

const value = [Link]('key');

// Remove item
H

[Link]('key');
ar

// Clear all items


ry

[Link]();
Example: Storing and Retrieving Data

[Link]('username', 'haris');

const user = [Link]('username');


[Link](user); // Output: haris

Storing Objects

Since localStorage only stores strings, you must convert objects using
[Link]() and retrieve them using [Link]() :

const user = {
name: 'Harry',
age: 25

};

// Store the object


[Link]('user', [Link](user));
C
od

// Retrieve the object


const storedUser = [Link]([Link]('user'));

[Link]([Link]); // Output: Harry


eW

Checking if Key Exists


ith
H

if ([Link]('theme')) {
ar

[Link]('Theme is set');
}
ry

Use Cases

• Saving user preferences (e.g., theme, language)


• Caching small amounts of data
• Keeping users logged in (store tokens)
• Temporarily saving form data

Limitations

• Synchronous (can block main thread)


• Storage limit (~5MB)
• No automatic expiration (unlike sessionStorage or cookies)
• Not secure for sensitive data (easily inspectable via DevTools)

Summary

• localStorage provides simple, persistent browser storage.


• Use setItem , getItem , removeItem , and clear methods.
• Always stringify objects before storing.
• Avoid storing sensitive data.
C
od
eW
ith
H
ar
ry
Parsing JSON in JavaScript
JSON (JavaScript Object Notation) is a lightweight data format used for
exchanging data between a server and a client. JavaScript provides built-in
methods to parse and stringify JSON.

What is JSON?

JSON is a string representation of data structured in key-value pairs.

Example JSON string:

"name": "Harry",
"age": 25,
"skills": ["JavaScript", "Python"]
}
C
od

This looks like a JavaScript object, but it’s actually a string.


eW

Parsing JSON with [Link]()


ith

To convert a JSON string into a JavaScript object, use [Link]() :


H
ar

const jsonString = '{"name":"Harry","age":25}';


ry

const user = [Link](jsonString);


[Link]([Link]); // Output: Harry
Note:
• The string must be valid JSON, otherwise [Link]() will throw an error.
• All keys must be enclosed in double quotes ( " ).

Stringifying JavaScript Objects with


[Link]()

To convert a JavaScript object into a JSON string, use [Link]() :

const user = {
name: 'Harry',
age: 25
};

const json = [Link](user);


[Link](json); // Output: {"name":"Harry","age":25}
C
od

Common Use Case: localStorage


eW

Since localStorage can only store strings, you often use JSON methods to store
and retrieve objects:
ith

// Store object
H

[Link]('user', [Link](user));
ar

// Retrieve and parse object


ry

const storedUser = [Link]([Link]('user'));


Handling Errors

Wrap parsing in a try...catch block to handle invalid JSON:

try {
const data = [Link](badJSONString);
} catch (error) {
[Link]('Invalid JSON:', [Link]);
}

Summary

• Use [Link]() to convert a JSON string into a JavaScript object.


• Use [Link]() to convert a JavaScript object into a JSON string.
• These methods are commonly used with localStorage , APIs, and data
exchange.
C
od
eW
ith
H
ar
ry
Error Handling in JavaScript
Errors are inevitable in any application. JavaScript provides robust tools to detect,
handle, and respond to runtime errors, allowing your code to fail gracefully.

Types of Errors

• Syntax Errors: Mistakes in the code structure (e.g., missing brackets)


• Runtime Errors: Occur during execution (e.g., accessing undefined variables)
• Logical Errors: Code runs but doesn’t behave as intended

The try...catch Statement

Use try...catch to handle errors without crashing the entire script.


C
od

Syntax:
eW

try {
// Code that may throw an error
} catch (error) {
ith

// Handle the error


}
H
ar

Example:
ry

try {
let result = 10 / x; // x is not defined
} catch (error) {
[Link]('An error occurred:', [Link]);
}
The finally Block

The finally block is optional and always runs, whether an error occurred or not.

try {
// Risky code
} catch (error) {
// Handle error

} finally {
// Always runs
[Link]('Cleanup complete');
}

Throwing Custom Errors

You can manually throw errors using the throw statement.


C
od

function divide(a, b) {
if (b === 0) {
throw new Error('Cannot divide by zero');
eW

}
return a / b;
}
ith

try {
H

divide(5, 0);
ar

} catch (error) {
[Link]([Link]); // Output: Cannot divide by zero
ry

}
Catching Specific Error Types

The catch block receives an Error object with useful properties:

try {
[Link]('invalid JSON');
} catch (error) {
[Link]([Link]); // SyntaxError
[Link]([Link]); // Unexpected token i in JSON
}

Best Practices

• Always handle expected errors (e.g., API failures, user input)


• Avoid swallowing errors silently — log them
• Use specific error messages for debugging
• Don’t use try-catch for control flow in performance-critical code
C
od

Summary
eW

• Use try...catch to prevent your app from crashing.


• Add finally for cleanup logic.
ith

• Use throw to raise custom errors.


H

• Proper error handling makes applications more stable and user-friendly.


ar
ry
Timers and Intervals in JavaScript
JavaScript provides built-in functions to schedule code execution after a delay or at
repeated intervals. These are useful for animations, delayed actions, auto-saving,
and more.

setTimeout() : Run Code After a Delay

The setTimeout() function executes code once after a specified delay (in
milliseconds).

Syntax

setTimeout(callback, delay);
C

Example
od
eW

setTimeout(() => {
[Link]('This runs after 2 seconds');
}, 2000);
ith

Canceling a Timeout
H
ar

Use clearTimeout() to stop a scheduled timeout.


ry

const timeoutId = setTimeout(() => {


[Link]('Will not run');
}, 3000);

clearTimeout(timeoutId);
setInterval() : Run Code Repeatedly

The setInterval() function executes code repeatedly at a specified interval (in


milliseconds).

Syntax

setInterval(callback, interval);

Example

setInterval(() => {
[Link]('Runs every second');
}, 1000);

Canceling an Interval
Use clearInterval() to stop the repetition.
C
od

const intervalId = setInterval(() => {


[Link]('Repeating...');
eW

}, 1000);
ith

setTimeout(() => {

clearInterval(intervalId);
[Link]('Interval stopped');
H

}, 5000);
ar
ry

Use Cases

• Delayed popups or notifications


• Auto-refreshing data (like a clock or stock ticker)
• Game loops and animations
• Debouncing or throttling user input

Important Notes

• Delays are not guaranteed to be exact — they depend on the event loop and
execution stack.
• Avoid overly frequent intervals ( <10ms ) as it may block the main thread.

Summary

Function Purpose Cancel with

setTimeout() Run code once after delay clearTimeout()

setInterval() Run code repeatedly with delay clearInterval()


C
od
eW
ith
H
ar
ry
Introduction to [Link]

Why Do We Need a Backend?

In web development, frontend and backend are two key parts of an application.

• The frontend is what users see and interact with—like buttons, forms, and text
on a webpage. It runs in the browser.

• The backend is like the behind-the-scenes part. It handles things like:

• Storing and retrieving data from databases


• Authenticating users (login/signup)
• Processing business logic
• Securing sensitive operations
• Handling API requests from the frontend
C

Without a backend, a website can’t store user data, communicate with a database,
od

or perform secure tasks. The frontend would just be a static page with limited
interactivity.
eW

Example
ith

Imagine a to-do list app:

• The frontend displays the tasks and lets the user add or remove them.
H

• The backend saves these tasks to a database, so they’re still there when the
ar

user comes back later.


ry
Introduction to [Link]

[Link] is a runtime environment that lets you run JavaScript on the server, not
just in the browser.

• Normally, JavaScript runs only in the browser (client-side).


• [Link] allows you to run JavaScript on your computer or server (server-side).

With [Link], you can build the backend of your application using JavaScript—the
same language you use for the frontend. This makes development faster and
easier, especially for beginners.

Key Features of [Link]


• Built on Chrome’s V8 JavaScript engine
• Handles many requests at once using non-blocking (asynchronous) code
• Has a large ecosystem of libraries (called npm)
• Great for building APIs, real-time apps (like chat apps), and full-stack
JavaScript projects
C

Server-side vs. Client-side JavaScript


od
eW

Feature Client-side (Browser) Server-side ([Link])

Runs on User’s browser Web server


ith

Displaying content, UI
Use case Storing data, handling logic
interaction
H

Access to system Full access (file system,


ar

Limited (sandboxed)
resources network)
ry

Performance Depends on user’s device Depends on server

Form validation, Database queries, user


Examples
animations authentication
Why the Difference Matters
• Running JavaScript in the client is good for creating interactive webpages, but
it’s limited and not secure for sensitive operations.
• Running JavaScript in the server (with [Link]) allows you to perform secure
tasks and manage application logic centrally.

Summary

• A backend is essential for dynamic websites that need to store data, handle
users, or connect to databases.
• [Link] lets you write backend code using JavaScript, making full-stack
development more accessible.
• Client-side JavaScript is for user interaction; server-side JavaScript (via
[Link]) handles the logic and data behind the scenes.
C
od
eW
ith
H
ar
ry
Installing [Link] and npm
To run JavaScript on the server and build backend applications with [Link], you
first need to install [Link]. When you install [Link], npm (Node Package
Manager) is installed automatically.

Step 1: Download [Link]

1. Go to the official [Link] website: [Link]

2. You’ll see two versions:

1. LTS (Long-Term Support): Recommended for most users. It’s stable and
reliable.
2. Current: Has the latest features but may not be as stable.

3. Download the LTS version for your operating system (Windows, macOS, or
Linux).
C
od

Step 2: Install [Link] On Windows and macOS


eW

1. Run the installer you downloaded.

2. Follow the setup instructions:


ith

1. Accept the license agreement.


H

2. Choose the default options.


ar

3. After installation, [Link] and npm will be available globally on your system.
ry

Step 3: Verify Installation

After installation, open a terminal (Command Prompt, Terminal, or shell) and check
the versions:
node -v

This prints the installed [Link] version.

npm -v

This prints the installed npm version.

If you see version numbers for both, the installation was successful.

What is npm?

npm (Node Package Manager) is a tool that comes with [Link]. It allows you to:

• Install open-source packages and libraries (called “modules”)


• Manage project dependencies
• Run scripts for building, testing, and starting your app
C

You’ll use npm often when building projects with [Link].


od
eW

Summary

• Install [Link] from [Link]


ith

• [Link] includes npm, which is used to manage packages


H

• Use your terminal to verify the installation with node -v and npm -v
ar

You’re now ready to start building backend applications with JavaScript and
ry

[Link]. Let me know if you want a guide on starting your first [Link] project.
Using npm Packages in [Link] (with
Express)
In this guide, we’ll install and use an npm package in a [Link] project. We’ll use
Express, a popular web framework for [Link]. Don’t worry about the details of
Express for now—we’ll cover that later. The goal here is simply to show how to
install and use packages with npm.

Step 1: Initialize a New Project

Create a new project folder and initialize it:

mkdir my-npm-app
cd my-npm-app
C

npm init -y
od

This creates a [Link] file that keeps track of your project’s dependencies.
eW

Step 2: Install Express


ith
H

Use npm install to install the Express package:


ar

npm install express


ry

After installing, you’ll see a node_modules folder and a [Link] file


created. The [Link] file will also list Express under dependencies .
Step 3: Create a Simple Server with Express

Create a new file called [Link] :

touch [Link]

Add the following code to [Link] :

const express = require('express');


const app = express();

[Link]('/', (req, res) => {


[Link]('Hello from Express!');
});

const port = 3000;

[Link](port, () => {
[Link](`Server is running at [Link]
});
C

We’ll explore what this code does later. For now, it just starts a basic server.
od
eW

Step 4: Run Your App


ith

To start the app, run:


H

node [Link]
ar

Visit [Link] in your browser. You should see:


ry

Hello from Express!


Step 5: Use [Link] Watch Mode

[Link] now supports watch mode natively (from version 18 and above)

To run your app in watch mode:

node --watch [Link]

This means [Link] will automatically restart whenever you save changes to
[Link] or other imported files.

Note: Watch mode works best in modern versions of [Link]. You can check
your [Link] version using:

node -v

Step 6: Uninstall a Package


C

If you ever want to remove a package (like Express), use:


od

npm uninstall express


eW

This removes it from node_modules and updates your [Link] .


ith
H

Summary
ar

• Initialized a [Link] project using npm init -y


ry

• Installed an npm package ( express )


• Used it in a basic server file ( [Link] )
• Ran the app using both normal and watch mode ( node and node --watch )
• Learned how to uninstall packages with npm uninstall
Creating a Simple [Link] Application
Now that [Link] and npm are installed, you can create your first [Link]
application. This guide walks you through building a basic “Hello, World” server.

Step 1: Create a New Project Folder

Open your terminal and create a new folder for your project:

mkdir my-node-app
cd my-node-app

Step 2: Initialize the Project


C
od

Run the following command to create a [Link] file, which keeps track of
your project settings and dependencies:
eW

npm init -y
ith

This generates a basic [Link] file with default values.


H
ar
ry

Step 3: Create the Application File

Create a new file named [Link] (or any name you prefer):

touch [Link]
Open [Link] in your code editor and add the following code:

const http = require('http');

const server = [Link]((req, res) => {


[Link] = 200;
[Link]('Content-Type', 'text/plain');
[Link]('Hello, World!\n');
});

const port = 3000;


[Link](port, () => {
[Link](`Server running at [Link]
});

This creates a basic HTTP server that responds with “Hello, World!” to every
request.

Step 4: Run the Application


C
od

In your terminal, start the server:


eW

node [Link]

If everything is set up correctly, you should see this message in the terminal:
ith
H

Server running at [Link]


ar

Open your web browser and visit [Link] You should see “Hello,
ry

World!” displayed.
Summary

• You created a new folder and initialized a [Link] project.


• You wrote a simple server using Node’s built-in http module.
• You started the server and accessed it in your browser.
C
od
eW
ith
H
ar
ry
[Link] Modules
Modules in [Link] are reusable pieces of code that help organize programs into
separate files and components.

Types of Modules

1. Core Modules
Built into [Link], no need to install.
Example: fs , http , path

const fs = require('fs');
const data = [Link]('[Link]', 'utf8');

[Link](data);

2. Local Modules Custom modules created in your project.


C

Example: [Link]
od
eW

// [Link]
function add(a, b) {
return a + b;
ith

}
H

[Link] = { add };
ar

// [Link]
ry

const math = require('./math');


[Link]([Link](5, 3));

3. Third-party Modules Installed via npm (Node Package Manager). Example:


express , lodash
npm install express

const express = require('express');


const app = express();

[Link]('/', (req, res) => {


[Link]('Hello World');
});

[Link](3000);

Exporting and Importing

• Use [Link] to export


• Use require() to import

Summary
C

[Link] modules keep code organized, reusable, and maintainable. Whether you’re
od

using built-in modules, custom files, or third-party packages, modules are


fundamental to every [Link] project.
eW
ith
H
ar
ry
ES6 Modules vs CommonJS in [Link]
[Link] supports two main module systems:

1. CommonJS (CJS) – Default in older [Link] versions


2. ES6 Modules (ESM) – Modern standard, used in frontend and supported
natively in recent [Link] versions

1. CommonJS

• File Extension: .js


• Import Syntax: require()
• Export Syntax: [Link] or exports

Example:
C
od

// [Link]
function add(a, b) {
eW

return a + b;
}
[Link] = { add };
ith
H

// [Link]
const math = require('./math');
ar

[Link]([Link](2, 3));
ry

2. ES6 Modules

• File Extension: .mjs or .js with "type": "module" in [Link]


• Import Syntax: import
• Export Syntax: export / export default

Example:

// [Link]
export function add(a, b) {
return a + b;
}

// [Link]
import { add } from './[Link]';
[Link](add(2, 3));

Key Differences

Feature CommonJS (CJS) ES6 Modules (ESM)


C

require ,
Syntax import , export
od

[Link]

File .mjs or .js with "type":


eW

.js
extension "module"

Loading
ith

Synchronous Asynchronous
style
H

Support Default in [Link] Modern [Link] (14+)


ar

Top-level
Not supported Supported
await
ry

Used in [Link] traditionally Both frontend and backend


When to Use What

• Use CommonJS if you’re working on older [Link] projects or need


compatibility with legacy packages.
• Use ES6 Modules for new projects to align with modern JavaScript standards
and browser support.

Mixing CJS and ESM

Mixing module types can be tricky:

• You can’t use require() to import an ES6 module.


• You can’t use import to load a CommonJS module unless it’s default-
exported.

Conclusion
C

Both module systems help organize and reuse code, but ES6 modules are the
od

future, offering cleaner syntax and better interoperability across frontend and
backend.
eW
ith
H
ar
ry
Understanding the [Link] Wrapper
Function and Special Variables
In [Link], every JavaScript file is wrapped inside a special function before it is
executed. This allows each file to have its own private scope, preventing variables
from leaking into the global scope.

The Wrapper Function

[Link] wraps your code like this internally:

(function(exports, require, module, __filename, __dirname) {


// Your entire file code lives here
});

This is known as the Module Wrapper Function. Because of this, your [Link] file
C

gets access to the following special variables:


od
eW

Special Variables in [Link]


ith

__filename
H

• Returns the absolute path of the current file.


ar
ry

[Link](__filename);
// Example: /Users/haris/project/[Link]

__dirname

• Returns the absolute path of the directory that contains the current file.
[Link](__dirname);

// Example: /Users/haris/project

exports and [Link]

• Used to export variables or functions from a module.

require

• Used to import modules.

module

• Represents the current module and contains metadata about it.

Why This Matters

This wrapper allows each file to be treated as a separate module. It ensures:


C

• Code isolation (no global scope pollution)


od

• Access to helpful variables like __dirname and __filename


eW

• A consistent module system using CommonJS


ith

Example
H
ar

// [Link]
[Link]('Filename:', __filename);
ry

[Link]('Directory:', __dirname);

When you run this with node [Link] , it will print the full path of the file and its
directory.
Understanding the wrapper function and special variables is key to mastering how
[Link] modules work internally.

C
od
eW
ith
H
ar
ry
Asynchronous JavaScript
JavaScript runs code one line at a time — it’s single-threaded. This means only
one task can happen at any moment. Still, JavaScript can do things like wait for a
timer or handle user clicks without stopping everything else.

This is because JavaScript uses asynchronous behavior for certain tasks.

Synchronous Code

This is how JavaScript normally works — top to bottom.

[Link]("A");
[Link]("B");
[Link]("C");
C

// Output:
od

// A
// B
eW

// C

Each line waits for the previous one to finish. That’s synchronous execution.
ith
H
ar

Asynchronous Code
ry

Here’s where it gets interesting:

[Link]("A");

setTimeout(() => {
[Link]("B");
}, 1000);

[Link]("C");

// Output:
// A
// C
// B (after about 1 second)

Even though setTimeout is written before "C" , it runs after. Why?

What Happens Behind the Scenes

When JavaScript sees setTimeout , it:

1. Sends the task (along with its delay) to the browser (or [Link], if you’re
running it there).
2. Continues running the rest of the code — it doesn’t wait.
C

3. After the timer finishes, the function you passed to setTimeout is sent back
od

to JavaScript to be run.
4. But it will only run after the current code is done.
eW

This system of handling things is managed by the event loop.


ith

The Event Loop (In Simple Words)


H
ar

The event loop is a mechanism that:


ry

• Keeps checking if JavaScript is done running your current code.


• If yes, it picks up any pending tasks (like the setTimeout callback) and runs
them.
Real-Life Analogy

Imagine you’re cooking:

• You put rice on the stove and set a timer.


• You don’t just stand there — you cut vegetables.
• When the timer rings, you go back to check the rice.

Similarly, JavaScript schedules tasks like timers to run later, and continues with the
rest of the code.

Another Example

[Link]("Start");

setTimeout(() => {
[Link]("Waiting over");
}, 2000);
C

[Link]("End");
od

// Output:
eW

// Start
// End
// Waiting over (after ~2 seconds)
ith

Even with 2 seconds delay, "End" appears immediately after "Start" — that’s
H

the power of async.


ar
ry

Summary

• JavaScript is single-threaded: one thing at a time.


• Functions like setTimeout are asynchronous.
• These async tasks are handled by the browser/Node and returned later.
• The event loop checks when JavaScript is free to run those returned tasks.

Understanding this helps you write programs that don’t get “stuck” waiting and
can handle things like user input, network requests, and timers smoothly.
C
od
eW
ith
H
ar
ry
Introduction to JavaScript Promises
A Promise in JavaScript is a way to handle asynchronous operations. It lets you
write code that runs after something finishes, without getting stuck in messy
nested callbacks.

Think of a Promise like a placeholder for a value that will be available in the future.

Why Do We Need Promises?

With callbacks, things can quickly become hard to read and maintain, especially
when we have to wait for multiple things.

Example of callback hell:

doTask1(function (result1) {
C

doTask2(result1, function (result2) {


od

doTask3(result2, function (result3) {


[Link]("All tasks done");
eW

});
});
});
ith

This kind of nested code becomes difficult to manage. Promises solve this by
H

allowing a cleaner, more readable structure.


ar
ry

Basic Promise Syntax

const promise = new Promise(function (resolve, reject) {


// Do some work...
// Call resolve(result) if successful
// Call reject(error) if there’s an error

});

Once a Promise is created, we can handle its result using .then() and .catch() :

promise
.then(function (result) {
// This runs if the promise was resolved
})
.catch(function (error) {
// This runs if the promise was rejected
});

A Simple Example: Fake Async Task

Let’s create a Promise that waits for 2 seconds and then resolves.
C

function waitTwoSeconds() {
od

return new Promise(function (resolve, reject) {


setTimeout(function () {
eW

resolve("Done waiting");
}, 2000);
});
ith

}
H

[Link]("Start");
ar

waitTwoSeconds()
ry

.then(function (message) {
[Link](message); // "Done waiting"
})
.catch(function (error) {
[Link]("Something went wrong");
});
[Link]("End");

Output:

Start
End
Done waiting

Even though the Promise is written earlier, it runs after the rest of the synchronous
code — just like with callbacks.

Solving Callback Hell with Promises

You can chain multiple .then() calls instead of nesting:

doTask1()
.then(function (result1) {
C

return doTask2(result1);
od

})
.then(function (result2) {
eW

return doTask3(result2);
})
.then(function (result3) {
ith

[Link]("All tasks done");


})
H

.catch(function (error) {
[Link]("Something failed", error);
ar

});
ry

This is much cleaner than deeply nested callbacks.


Summary

• A Promise is an object representing a value that may be available now, later,


or never.

• It has three states:

• Pending: not yet finished


• Resolved: finished successfully
• Rejected: finished with an error

• Use .then() to handle success and .catch() to handle errors.

• Promises help write cleaner async code, especially when chaining tasks.
C
od
eW
ith
H
ar
ry
JavaScript async and await
Writing asynchronous code using .then() and .catch() works well, but as your
code grows, it can still feel a bit hard to follow.

JavaScript gives us a cleaner way to work with Promises:


async and await

What is async ?

If you put the keyword async before a function, it automatically returns a


Promise.

async function greet() {


return "Hello";
C

}
od

greet().then(function (message) {
eW

[Link](message); // "Hello"
});
ith

Even though we just returned a string, greet() becomes a Promise.


H
ar

What is await ?
ry

The await keyword is used inside an async function. It tells JavaScript to wait
for the Promise to resolve, then continue.
Basic Example

Let’s simulate a delay using setTimeout wrapped in a Promise:

function waitTwoSeconds() {
return new Promise(function (resolve) {
setTimeout(function () {
resolve("Waited for 2 seconds");
}, 2000);
});
}

async function runTask() {


[Link]("Start");

const result = await waitTwoSeconds();


[Link](result);

[Link]("End");
}
C

runTask();
od

Output:
eW

Start
Waited for 2 seconds
ith

End
H
ar
ry

Why Use async and await ?

Let’s compare the same logic using .then() :


waitTwoSeconds().then(function (result) {

[Link](result);
});

It works, but once you have multiple async operations, the .then() style gets
harder to follow.

With await , your code looks more like regular, synchronous code — even though
it’s asynchronous.

Handling Errors with try...catch

If a Promise rejects, you can catch the error using try...catch .

function fakeTask(fail) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (fail) {
C

reject("Something went wrong");


od

} else {
resolve("Task completed");
eW

}
}, 1000);
});
ith

}
H

async function run() {


try {
ar

const result = await fakeTask(false);


[Link](result);
ry

} catch (error) {
[Link]("Caught error:", error);
}
}
run();

Summary

• async makes a function return a Promise.


• await pauses inside the function until the Promise is done.
• You can use try...catch to handle errors just like synchronous code.
• async / await makes asynchronous code easier to read and write.
C
od
eW
ith
H
ar
ry
JavaScript async and await
Writing asynchronous code using .then() and .catch() works well, but as your
code grows, it can still feel a bit hard to follow.

JavaScript gives us a cleaner way to work with Promises:


async and await

What is async ?

If you put the keyword async before a function, it automatically returns a


Promise.

async function greet() {


return "Hello";
C

}
od

greet().then(function (message) {
eW

[Link](message); // "Hello"
});
ith

Even though we just returned a string, greet() becomes a Promise.


H
ar

What is await ?
ry

The await keyword is used inside an async function. It tells JavaScript to wait
for the Promise to resolve, then continue.
Basic Example

Let’s simulate a delay using setTimeout wrapped in a Promise:

function waitTwoSeconds() {
return new Promise(function (resolve) {
setTimeout(function () {
resolve("Waited for 2 seconds");
}, 2000);
});
}

async function runTask() {


[Link]("Start");

const result = await waitTwoSeconds();


[Link](result);

[Link]("End");
}
C

runTask();
od

Output:
eW

Start
Waited for 2 seconds
ith

End
H
ar
ry

Why Use async and await ?

Let’s compare the same logic using .then() :


waitTwoSeconds().then(function (result) {

[Link](result);
});

It works, but once you have multiple async operations, the .then() style gets
harder to follow.

With await , your code looks more like regular, synchronous code — even though
it’s asynchronous.

Handling Errors with try...catch

If a Promise rejects, you can catch the error using try...catch .

function fakeTask(fail) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (fail) {
C

reject("Something went wrong");


od

} else {
resolve("Task completed");
eW

}
}, 1000);
});
ith

}
H

async function run() {


try {
ar

const result = await fakeTask(false);


[Link](result);
ry

} catch (error) {
[Link]("Caught error:", error);
}
}
run();

Summary

• async makes a function return a Promise.


• await pauses inside the function until the Promise is done.
• You can use try...catch to handle errors just like synchronous code.
• async / await makes asynchronous code easier to read and write.
C
od
eW
ith
H
ar
ry
JavaScript Callbacks
A callback is simply a function passed as an argument to another function, to be
called later.

This might sound confusing at first, but once you see it in action, it becomes very
easy to understand.

Why Do We Need Callbacks?

Sometimes, you don’t want a function to run immediately.


Instead, you want it to run later, when something else happens — for example:

• When a timer finishes


• When a user clicks a button
• When some data is ready
C
od

Callbacks help us do that.


eW

Basic Example of a Callback


ith

function greet(name) {
H

[Link]("Hello, " + name);


ar

}
ry

function processUser(callback) {
const userName = "Harry";
callback(userName);
}
processUser(greet);

What’s Happening Here?


• greet is a function that prints a greeting.
• processUser is another function that receives a function (callback) and calls it
later.
• We pass greet as an argument to processUser .

So processUser(greet) ends up calling: greet("Harry")

Callbacks in Asynchronous Code

Callbacks are often used with async functions like setTimeout .

function showMessage() {
[Link]("This runs after 2 seconds");
C

}
od

setTimeout(showMessage, 2000);
eW

[Link]("This runs first");


ith

Output:
H

This runs first


ar

This runs after 2 seconds


ry

Even though showMessage is written before the timer, it runs later — after 2
seconds. That’s because we passed it as a callback to setTimeout .
Writing Inline Callback Functions

Instead of defining the function first, we can also write it directly:

setTimeout(function () {
[Link]("Hello after 1 second");
}, 1000);

This is still a callback — just written directly where it’s used.

Another Example with User Input (Browser Only)

If you’re in a browser and use something like this:

[Link]("btn").addEventListener("click", function () {
[Link]("Button clicked");
});
C

The second argument to addEventListener is a callback. It runs only when the


od

user clicks the button.


eW

Summary
ith

• A callback is just a function passed to another function.


H

• It can be used to run code later.


ar

• Callbacks are commonly used in:


ry

• setTimeout
• Event listeners
• Many asynchronous operations
Callbacks are the foundation for working with asynchronous JavaScript. Once
you’re comfortable with them, you’re ready to learn more advanced things like
Promises and async/await .
C
od
eW
ith
H
ar
ry
Introduction to [Link]

What is [Link]?

[Link] is a fast, unopinionated, and minimalist web framework for [Link]. It


simplifies the process of building web servers and APIs using JavaScript.

Instead of writing raw HTTP code in [Link], Express gives us a higher-level set of
tools to build robust backend applications quickly and efficiently.

Why Use [Link] Over [Link] Core Modules?

Raw [Link]:
• You need to manually parse requests and handle routes.
C

• No built-in support for things like middleware, form data, sessions, or routing.
od

[Link]:
eW

• Built-in routing support.


• Middleware support for handling requests and responses.
ith

• Easily serve static files.


H

• Simplifies API and web app development.


ar
ry

Real-World Use Cases

Express is used in many production-grade applications, such as:

• REST APIs
• Web applications (with HTML templating)
• Backend for mobile and single-page apps
• Server-side rendering setups

Installing [Link]

Before using Express, make sure [Link] and npm are installed.

To install Express:

npm install express

Your First Express App

Here’s a basic example of an Express server:


C

const express = require('express');


od

const app = express();


eW

[Link]('/', (req, res) => {


[Link]('Hello from Express!');
});
ith

[Link](3000, () => {
H

[Link]('Server is running on port 3000');


});
ar
ry

• express() creates an Express app.


• [Link]() defines a route handler.
• [Link]() starts the server.

Visit [Link] in your browser to test it.


Installing and Setting Up [Link]

Project Setup

Before we start writing code, let’s set up a new project folder.

1. Create a new folder:

mkdir express-intro
cd express-intro

1. Initialize a new [Link] project:

npm init -y

This creates a [Link] file with default settings.


C
od

1. Install Express:
eW

npm install express

You’ll now see express listed in your dependencies .


ith
H
ar

Creating Your First Express Server


ry

Create a file called [Link] :

const express = require('express');


const app = express();
// Define a basic GET route
[Link]('/', (req, res) => {

[Link]('Welcome to [Link]!');
});

// Start the server


[Link](3000, () => {
[Link]('Server is running on [Link]
});

Testing the Server

1. Run the server using:

node [Link]

1. Open your browser and visit:


C

[Link]
od

You should see the message: Welcome to [Link]!


eW
ith

Understanding the Code


H

• express() initializes the app.


ar

• [Link]() sets up a route for GET requests to the / path.


ry

• [Link]() sends a simple text response.


• [Link]() starts the server on the specified port.
Routing in [Link]

What is Routing?

Routing refers to how an application responds to client requests to specific paths


(URLs) using HTTP methods such as GET, POST, PUT, DELETE, etc.

In [Link], routes define the logic for what should happen when a user visits a
particular URL.

Basic GET Route

[Link]('/', (req, res) => {


[Link]('Home Page');
C

});
od

• This responds to a GET request to the root ( / ) URL.


eW

• [Link]() sends a response back to the client.


ith

Route Methods in Express


H
ar

Express provides methods for all standard HTTP methods:


ry

[Link]('/about', (req, res) => {


[Link]('About Page');
});

[Link]('/contact', (req, res) => {

[Link]('Contact form submitted');


});

[Link]('/user/:id', (req, res) => {


[Link](`Update user with ID ${[Link]}`);
});

[Link]('/user/:id', (req, res) => {


[Link](`Delete user with ID ${[Link]}`);
});

Route Parameters

Route parameters are named segments of the URL prefixed with a colon ( : ). They
allow you to capture values from the URL.

[Link]('/user/:id', (req, res) => {


const userId = [Link];
[Link](`User ID is ${userId}`);
C

});
od
eW

Query Parameters
ith

Query parameters are added to the URL after a ? and are accessible using
[Link] .
H
ar

// URL: /search?term=node
[Link]('/search', (req, res) => {
ry

const searchTerm = [Link];


[Link](`You searched for ${searchTerm}`);
});
Summary

• Use [Link]() to define routes.


• Use [Link] to get route parameters.
• Use [Link] for query parameters.
C
od
eW
ith
H
ar
ry
What is MongoDB?

Introduction

MongoDB is a NoSQL document-oriented database designed for modern


application development. It stores data in flexible, JSON-like documents, which
makes it easy to work with dynamic or semi-structured data.

Unlike traditional relational databases (like MySQL or PostgreSQL), MongoDB does


not use tables or rows. Instead, it uses:

• Databases → which contain


• Collections → which contain
• Documents (individual records in JSON/BSON format)

Key Features of MongoDB


C
od

• Document-Based Storage: Data is stored in BSON (binary JSON) documents.


• Schema-less: Each document can have a different structure.
eW

• High Performance: Built for high read/write throughput.


• Horizontal Scalability: Supports sharding to handle large datasets.
• Rich Query Language: Supports nested queries, filters, and aggregation.
ith
H

MongoDB vs Relational Databases


ar

Feature MongoDB Relational DB (e.g., MySQL)


ry

Data Model Document Table/Row

Schema Flexible (Schema-less) Fixed (Predefined Schema)

Embedded or
Relationships Foreign Keys
Referenced
Feature MongoDB Relational DB (e.g., MySQL)

Query
BSON-based SQL
Language

Best Use
Real-time apps, analytics Financial systems, complex joins
Cases

When to Use MongoDB

MongoDB is ideal for use cases like:

• Content management systems (CMS)


• Social media applications
• Product catalogs or inventory systems
• Real-time analytics dashboards
• IoT and sensor data storage

Conclusion
C

MongoDB is a powerful, flexible, and scalable database solution suited for


od

applications where data structure may evolve over time or performance at scale is
critical.
eW
ith
H
ar
ry
Setting Up MongoDB

Local Installation (Optional for Beginners)

To install MongoDB on your system:

On Windows
1. Go to MongoDB Community Download Center.

2. Download the MSI installer for your version.

3. Follow the installation steps and enable MongoDB as a service.

4. Use the terminal to run:

mongod
C
od

This starts the MongoDB server.


eW

On macOS (Using Homebrew)

brew tap mongodb/brew


ith

brew install mongodb-community


brew services start mongodb-community
H
ar

On Linux (Ubuntu Example)


ry

sudo apt update


sudo apt install -y mongodb
sudo systemctl start mongodb

To check if MongoDB is running:


mongo

This will open the MongoDB shell if it’s installed correctly.

Using MongoDB Atlas (Cloud Setup)

MongoDB Atlas is the easiest way to get started without installing anything.

Steps to Create a Cluster:


1. Visit [Link]

2. Sign up and create a free cluster (Shared Tier).

3. Choose cloud provider and region.

4. Create a username and password for database access.

5. Whitelist your IP address or allow all IPs ( [Link]/0 ) for testing.


C

6. Get your connection string, which looks like:


od

mongodb+srv://<username>:<password>@[Link]/myDatabase?
eW

retryWrites=true&w=majority
ith

MongoDB Compass (Optional GUI)


H
ar

MongoDB Compass is a GUI client to visually interact with your databases.


ry

• Download from: [Link]

• Connect using the same Atlas URI or local URI like:

mongodb://localhost:27017
You can:

• View collections and documents


• Run queries
• Inspect schema visually

Connecting to MongoDB with [Link]

Install the official MongoDB driver:

npm install mongodb

Sample connection code:

const { MongoClient } = require('mongodb');

const uri = 'your_connection_string';


const client = new MongoClient(uri);
C

async function run() {


od

await [Link]();

const db = [Link]('test');
eW

const collection = [Link]('students');


const result = await [Link]().toArray();
[Link](result);
ith

await [Link]();
}
H
ar

run();
ry
Create and Read Documents
In MongoDB, data is stored in documents (which are JSON-like objects) inside
collections. You can perform Create and Read operations using simple methods.

This section will cover:

• insertOne() , insertMany()
• find() , findOne()
• Basic filters and projections

Note: All code examples in this section are written for MongoDB Compass
(MongoDB Shell syntax). You can run these directly in the MongoDB Compass shell
or mongosh.

Setting Up Sample Data


C
od

Before we start, let’s create a school database with students and teachers. Run this
in MongoDB Compass:
eW

// Switch to school database


use school
ith

// Insert sample teachers


H

[Link]([
ar

{
_id: ObjectId("507f1f77bcf86cd799439011"),
ry

name: 'Dr. Kumar',


subject: 'MongoDB',
experience: 5
},
{
_id: ObjectId("507f1f77bcf86cd799439012"),
name: 'Prof. Sharma',
subject: '[Link]',

experience: 8
},
{
_id: ObjectId("507f1f77bcf86cd799439013"),
name: 'Ms. Patel',
subject: 'Express',
experience: 3
}
])

// Insert sample students with teacher references


[Link]([
{
name: 'Ali',
age: 22,
course: 'MongoDB',
enrolled: true,
teacherId: ObjectId("507f1f77bcf86cd799439011"),
grades: [85, 90, 88]
},
C

{
od

name: 'Sara',
age: 20,
eW

course: '[Link]',
enrolled: true,
teacherId: ObjectId("507f1f77bcf86cd799439012"),
ith

grades: [92, 88, 95]

},
H

{
name: 'Ahmed',
ar

age: 24,
course: 'Express',
ry

enrolled: true,
teacherId: ObjectId("507f1f77bcf86cd799439013"),
grades: [78, 82, 85]
},
{
name: 'Fatima',
age: 21,
course: 'MongoDB',

enrolled: true,
teacherId: ObjectId("507f1f77bcf86cd799439011"),
grades: [95, 93, 97]
},
{
name: 'Ravi',
age: 23,
course: '[Link]',
enrolled: false,
teacherId: ObjectId("507f1f77bcf86cd799439012"),
grades: [70, 75, 72]
}
])

Inserting Documents

insertOne
C
od

Use this to insert a single document into a collection.


eW

[Link]({
name: 'Priya',
age: 19,
ith

course: 'MongoDB',
enrolled: true,
H

teacherId: ObjectId("507f1f77bcf86cd799439011"),
ar

grades: [88, 91, 89]


})
ry

insertMany
Use this to insert multiple documents at once.
[Link]([

{
name: 'Kabir',
age: 20,
course: '[Link]',
enrolled: true,
teacherId: ObjectId("507f1f77bcf86cd799439012"),
grades: [84, 87, 86]
},
{
name: 'Zara',
age: 22,
course: 'Express',
enrolled: true,
teacherId: ObjectId("507f1f77bcf86cd799439013"),
grades: [90, 92, 94]
}
])
C

Reading Documents
od

findOne
eW

Returns the first document that matches the filter.


ith

[Link]({ name: 'Ali' })


H
ar

find
ry

Returns all matching documents. In MongoDB Compass, results are automatically


displayed.

[Link]({ course: 'MongoDB' })


To get all students:

[Link]({})

Projections

Use projections to include or exclude specific fields.

// Include only name and age (exclude _id)


[Link]({}, { _id: 0, name: 1, age: 1 })

// Include name, course, and grades


[Link]({}, { name: 1, course: 1, grades: 1 })

Other Options
C
od

Limiting Results
eW

[Link]().limit(3)
ith

Sorting Results
H

// Sort by age (descending)


ar

[Link]().sort({ age: -1 })
ry

Combining Operations

// Find MongoDB students, show only name and grades, sorted by age
[Link](

{ course: 'MongoDB' },
{ name: 1, grades: 1, _id: 0 }
).sort({ age: 1 })

Working with Teachers Collection

// Find all teachers


[Link]()

// Find teacher by subject


[Link]({ subject: '[Link]' })

// Find experienced teachers (more than 5 years)


[Link]({ experience: { $gt: 5 } })

Summary
C

• Use insertOne() and insertMany() to add data


od

• Use findOne() and find() to read data


• Use projections to control which fields are returned
eW

• Use .sort() and .limit() to customize results


• All code runs directly in MongoDB Compass shell
ith
H
ar
ry
Update and Delete Documents
MongoDB provides powerful methods to update or remove documents from a
collection.

This section covers:

• updateOne() , updateMany() , $set , $inc


• deleteOne() , deleteMany()
• replaceOne()
• Understanding ObjectId

Note: All code examples are for MongoDB Compass shell (mongosh).

Updating Documents
C

updateOne
od

Updates the first document that matches the filter.


eW

// Change Ali's course to Advanced MongoDB


ith

[Link](
{ name: 'Ali' },
H

{ $set: { course: 'Advanced MongoDB' } }


)
ar
ry

updateMany
Updates all documents that match the filter.

// Add 1 year to age of all enrolled students


[Link](
{ enrolled: true },
{ $inc: { age: 1 } }

// Update all MongoDB students to have a new teacher


[Link](
{ course: 'MongoDB' },
{ $set: { teacherId: ObjectId("507f1f77bcf86cd799439011") } }
)

Common Update Operators


• $set : Sets the value of a field
• $unset : Removes a field
• $inc : Increments a numeric field
• $push : Adds an item to an array
• $pull : Removes an item from an array
• $addToSet : Adds unique items to an array

Examples:
C
od

// Add a new grade to Sara's grades array


[Link](
eW

{ name: 'Sara' },
{ $push: { grades: 96 } }
)
ith

// Remove enrolled field from Ravi


H

[Link](
ar

{ name: 'Ravi' },
{ $unset: { enrolled: "" } }
ry

// Increment teacher's experience by 1


[Link](
{ name: 'Dr. Kumar' },
{ $inc: { experience: 1 } }
)

Replacing a Document

replaceOne
Replaces the entire document with a new one (except the _id).

[Link](
{ name: 'Ravi' },
{
name: 'Ravi Kumar',
age: 24,
course: 'Python',
enrolled: true,
teacherId: ObjectId("507f1f77bcf86cd799439012"),
grades: [80, 85, 82],
C

email: '[Link]@[Link]'
}
od

)
eW
ith

Deleting Documents
H

deleteOne
ar

Deletes the first matching document.


ry

// Delete a specific student


[Link]({ name: 'Kabir' })
deleteMany
Deletes all matching documents.

// Delete all students who are not enrolled


[Link]({ enrolled: false })

// Delete all students with low average grades


[Link]({
$expr: {
$lt: [{ $avg: "$grades" }, 75]
}
})

Working with ObjectId

Each document in MongoDB has a unique _id field of type ObjectId .

In MongoDB Compass, ObjectId is available globally:


C
od

// Find a student by _id


[Link]({
eW

_id: ObjectId("64bd2e183dd4e6402f10388f")
})
ith

// Update a teacher by _id


[Link](
H

{ _id: ObjectId("507f1f77bcf86cd799439011") },
{ $set: { office: "Room 301" } }
ar

)
ry
Practical Examples

Update Student’s Teacher

// Move all Express students to a different teacher


[Link](
{ course: 'Express' },
{ $set: {
teacherId: ObjectId("507f1f77bcf86cd799439012"),
course: 'Advanced Express'
}}
)

Bulk Grade Update

// Add bonus points to all students of a specific teacher

[Link](
{ teacherId: ObjectId("507f1f77bcf86cd799439011") },
{ $push: { grades: 5 } } // Add 5 bonus points
)
C
od
eW

Summary

• Use updateOne() or updateMany() with operators like $set , $inc , $push


ith

• Use replaceOne() to completely replace documents


H

• Use deleteOne() or deleteMany() to remove documents


ar

• ObjectId is globally available in MongoDB Compass


• Always verify your filters before running update/delete operations
ry
Query Operators and Filtering
MongoDB provides powerful operators to filter and search documents in flexible
ways.

In this section, you will learn how to use:

• Comparison operators ( $gt , $lt , $eq , $ne , $in , $nin )


• Logical operators ( $or , $and , $not , $nor )
• Array and embedded field queries
• Sorting and pagination

Note: All code examples are for MongoDB Compass shell (mongosh).

Comparison Operators
C

$gt, $gte, $lt, $lte


od

Find students older than 21:


eW

[Link]({ age: { $gt: 21 } })


ith

Find students aged between 18 and 25:


H
ar

[Link]({ age: { $gte: 18, $lte: 25 } })


ry

Find teachers with more than 5 years experience:

[Link]({ experience: { $gt: 5 } })


$eq, $ne
Find students who are not enrolled:

[Link]({ enrolled: { $ne: true } })

$in, $nin
Find students enrolled in either “MongoDB” or “[Link]”:

[Link]({ course: { $in: ['MongoDB', '[Link]'] } })

Find teachers NOT teaching Express or Python:

[Link]({ subject: { $nin: ['Express', 'Python'] } })

Logical Operators
C
od

$or
eW

Find students enrolled in “Python” or age less than 20:

[Link]({
ith

$or: [
{ course: 'Python' },
H

{ age: { $lt: 20 } }
ar

]
})
ry

$and (default behavior)


Find students aged above 20 and enrolled:
[Link]({

age: { $gt: 20 },
enrolled: true
})

You can also write it explicitly:

[Link]({
$and: [
{ age: { $gt: 20 } },
{ enrolled: true }
]
})

$not
Find students not enrolled in “[Link]”:

[Link]({
C

course: { $not: { $eq: '[Link]' } }


})
od
eW

Complex Query Example


Find enrolled students who are either: - Taking MongoDB with age > 21, OR -
ith

Taking [Link] with high grades (average > 90)


H

[Link]({
ar

enrolled: true,
$or: [
ry

{ course: 'MongoDB', age: { $gt: 21 } },


{
course: '[Link]',
$expr: { $gt: [{ $avg: "$grades" }, 90] }
}
]
})

Array Queries

Working with the grades array in our student documents:

Matching Array Elements


Find students who scored exactly 95 in any test:

[Link]({ grades: 95 })

$all - Multiple Values


Find students who scored both 90 and 95 at some point:
C

[Link]({
grades: { $all: [90, 95] }
od

})
eW

$size - Array Length


ith

Find students with exactly 3 grades recorded:


H

[Link]({
ar

grades: { $size: 3 }
})
ry

$elemMatch - Complex Array Conditions


Find students with at least one grade above 90:
[Link]({

grades: { $elemMatch: { $gt: 90 } }


})

Working with Average Grades


Find students with average grade above 85:

[Link]({
$expr: {
$gt: [{ $avg: "$grades" }, 85]
}
})

Sorting and Pagination

sort()
C
od

Sort students by age (descending):


eW

[Link]().sort({ age: -1 })

Sort by multiple fields:


ith
H

// Sort by course (ascending), then by age (descending)


[Link]().sort({ course: 1, age: -1 })
ar
ry

skip() and limit()


Get the first 3 students:

[Link]().limit(3)
Implement pagination (skip first 2, then get next 3):

[Link]().skip(2).limit(3)

Combined Example
Find top 3 performing MongoDB students:

[Link]({
course: 'MongoDB'
}).sort({
grades: -1
}).limit(3)

Advanced Queries with Teachers

Join-like Queries
C

Find all students taught by Dr. Kumar:


od
eW

// First, find Dr. Kumar's ID


[Link]({ name: 'Dr. Kumar' })
ith

// Then find all students with that teacherId


[Link]({
H

teacherId: ObjectId("507f1f77bcf86cd799439011")
})
ar
ry

Count Operations
Count students per course:

[Link]({ course: 'MongoDB' })


Count all enrolled students:

[Link]({ enrolled: true })

Summary

• Use comparison operators ( $gt , $lt , $in , etc.) for filtering


• Combine with logical operators ( $or , $and ) for complex queries
• Array operators ( $all , $size , $elemMatch ) for array fields
• Use .sort() , .skip() , and .limit() for result control
• All queries run directly in MongoDB Compass shell
C
od
eW
ith
H
ar
ry

You might also like