Beginner's Guide to HTML Basics
Beginner's Guide to HTML Basics
What is HTML?
Web browsers (like Chrome, Firefox, Safari) read HTML code and display it as
websites.
• Knowing HTML helps you understand how websites work behind the scenes.
od
eW
Basic Terminology
ith
• Tag: Special keywords inside angle brackets like <p> or <h1> that define
ar
elements.
ry
<!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
Key Points
• Tags usually come in pairs: an opening tag <p> and a closing tag </p> .
H
• Indentation helps make code easier to read, but it’s not required.
ry
Basic HTML Structure
Every HTML document follows a basic structure. This structure tells the browser
how to read and display the content.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
C
<body>
od
</html>
eW
ith
1. <!DOCTYPE html>
ry
3. <head>...</head>
4. <title>...</title>
5. <body>...</body>
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
Headings in HTML
Example of Headings
C
📌 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
Example:
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
Complete Example
ar
ry
<!DOCTYPE html>
<html>
<head>
<title>Headings and Paragraphs</title>
</head>
<body>
<h1>My Blog</h1>
<h2>Introduction</h2>
Bold Text
• <strong> also means the text is important (for screen readers and SEO).
C
od
Italic Text
eW
• <em> gives extra emphasis and has meaning, especially for accessibility.
ar
ry
Underlined Text
Strikethrough Text
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
Tag Purpose
<u> Underline
<s> Strikethrough
<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:
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 is spaced.
If you want to preserve spaces and line breaks, use the <pre> tag.
Example:
<pre>
This is preformatted
text.
</pre>
Tip
Basic Syntax:
This creates a clickable link that takes you to the specified URL.
C
...
• Email Link:
• Phone Link:
C
od
• Visited: Purple
ar
Adding Images
Basic Syntax:
You can set the size of the image using width and height attributes.
Tip
Types of Lists
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
• Apples
ar
• Bananas
ry
• Oranges
Ordered List
<ol>
<li>Wake up</li>
<li>Brush teeth</li>
<li>Go to work</li>
</ol>
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
Nesting Lists
<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
<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>
Alice 24
Bob 30
Adding Borders
By default, tables have no border. Use the border attribute to add one.
<table border="1">
...
</table>
<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
What is a Form?
<form>
<!-- form elements go here -->
</form>
C
Use <input type="text"> to get a single line of text from the user.
eW
<form>
ith
<label for="name">Name:</label>
</form>
ar
<label for="password">Password:</label>
<input type="password" id="password" name="password">
Submit Button
Placeholder Text
C
You can show a hint inside the input using the placeholder attribute.
od
Complete Example
H
ar
<form>
<label for="email">Email:</label>
ry
<label for="pass">Password:</label>
<input type="password" id="pass" name="pass"><br><br>
<input type="submit" value="Login">
</form>
Tip
Radio Buttons
Use radio buttons when users need to select only one option from a group.
Checkboxes
ith
<label for="reading">Reading</label><br>
Use the <select> tag with <option> to let users pick one option from a
dropdown.
Use the <textarea> tag to let users type multiple lines of text.
eW
Tip
ar
ry
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.
• <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.
• <span>
• <a>
• <strong> , <em>
• <img>
• <code>
Example:
Summary
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
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
Some characters have special meaning in HTML (like < , > , & ).
To display these characters on a webpage, you need to use HTML entities.
Less than
C
< <
od
Registered symbol
ar
® ®
₹ ₹
<p>Price: ₹499</p>
Non-Breaking Space
Use to add extra space that the browser won’t collapse.
<p>Hello World</p>
C
Tip
od
• 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
Basic Example:
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
Audio Formats
ith
MP3 audio/mpeg
H
OGG
ar
audio/ogg
WAV
ry
audio/wav
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="[Link]" type="audio/ogg">
</audio>
Embedding Video
Basic Example:
Video Formats
eW
MP4 video/mp4
ith
WebM video/webm
H
OGG video/ogg
ar
<video controls>
<source src="movie.mp4" type="video/mp4">
<source src="[Link]" type="video/ogg">
</video>
Tip
What is an IFrame?
Basic Syntax
</iframe>
Attributes
Attribute Description
Security Note
od
Some websites may block iframe embedding for security reasons using headers
like X-Frame-Options .
eW
ith
Tip
H
• Always set appropriate width and height for better layout control.
ry
Using Meta Tags and SEO Basics
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.
1. Charset
C
<meta charset="UTF-8">
od
5. Author
SEO Basics
<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
Internal Links
Example:
...
H
External Links
Summary
H
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
Even if some tags are optional, it’s best to close them properly.
od
eW
<p>This is correct.</p>
ith
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.
<INPUT TYPE="TEXT">
C
Keep your HTML structured by grouping related elements together. Use comments
eW
to separate sections.
ith
Avoid putting CSS styles directly into HTML tags. Use external CSS files instead.
<!-- Avoid -->
Use tools like W3C HTML Validator to check for errors in your code.
✔ [Link]
✘ About Us!.html
C
od
eW
<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:
1. Inline CSS
ith
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>
[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>
If there are multiple rules targeting the same element, CSS uses the cascade to
decide which rule to apply. This depends on:
Example:
selector {
od
property: value;
}
eW
Example:
ith
p {
color: black;
H
font-size: 16px;
ar
}
ry
CSS Syntax
selector {
property: value;
Example:
C
h1 {
od
color: navy;
font-size: 32px;
eW
• h1 is the selector
ith
1. Element Selector
Selects all elements of a specific type.
p {
color: gray;
}
2. Class Selector
Selects elements with a specific class.
HTML:
CSS:
eW
.highlight {
background-color: yellow;
ith
}
H
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;
4. Universal Selector
Applies styles to all elements on the page.
* {
margin: 0;
padding: 0;
}
C
od
5. Grouping Selectors
ith
h1, h2, h3 {
ar
color: darkblue;
ry
HTML:
<div>
<p>This is a paragraph inside a div.</p>
</div>
CSS:
div p {
font-style: italic;
}
[Link] {
color: teal;
}
ith
Summary
ry
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
body {
ry
background-color: #f0f0f0;
}
• #000000 → black
• #ffffff → white
• #ff0000 → red
You can also use shorthand if all pairs are the same:
p {
color: rgb(255, 0, 0);
}
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
h2 {
color: hsl(240, 100%, 50%);
}
section {
background-color: hsla(120, 60%, 70%, 0.3);
}
C
od
eW
h1 {
color: navy; /* Text color */
ar
button {
color: blue;
border: 2px solid currentColor;
}
Summary
|---------------------------|
| Margin |
| |---------------------| |
| | Border | |
| | |---------------| | |
C
| | | Padding | | |
od
| | | |---------| | | |
| | | | Content | | | |
| | | |---------| | | |
eW
| | |---------------| | |
| |---------------------| |
|---------------------------|
ith
H
ar
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;
3. Border
The border around the padding and content.
4. Margin
ith
margin: 30px;
ar
ry
.box {
width: 300px;
height: 150px;
padding: 20px;
border: 5px solid gray;
margin: 40px;
}
By default, CSS uses content-box , where width and height apply only to the
od
* {
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
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
px
od
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
vw 1% of viewport width
vh 1% of viewport height
px (Pixels)
eW
p {
margin: 10px;
ith
}
H
% (Percentage)
div {
width: 80%;
}
Useful for making widths or heights relative to parent elements.
em vs rem
div {
font-size: 2em; /* 2 times the parent's font size */
}
html {
font-size: 16px;
}
h1 {
font-size: 2rem; /* 32px */
}
C
od
vw and vh
ith
.container {
H
}
ry
section {
width: calc(100% - 200px);
}
Best Practices
Summary
C
CSS units help control the size and spacing of elements. Choosing the right unit is
od
1. font-family
body {
font-family: Arial, sans-serif;
}
C
od
2. font-size
font-size: 36px;
}
p {
font-size: 1.2rem;
}
3. font-weight
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
em {
font-style: italic;
ry
}
5. text-align
h2 {
text-align: center;
}
6. line-height
p {
line-height: 1.6;
}
7. letter-spacing
eW
h1 {
H
letter-spacing: 2px;
}
ar
ry
8. word-spacing
word-spacing: 5px;
}
9. text-transform
.upper {
text-transform: uppercase;
}
.lower {
text-transform: lowercase;
}
.capitalize {
text-transform: capitalize;
C
}
od
eW
10. text-decoration
a {
text-decoration: none;
ar
}
ry
To use custom fonts, you can load them from Google Fonts.
HTML
CSS
body {
font-family: 'Roboto', sans-serif;
}
Summary
Typography affects the readability and tone of your website. Key things to
remember:
Background Properties
1. background-color
div {
background-color: lightblue;
}
C
od
eW
2. background-image
body {
H
background-image: url('[Link]');
ar
}
ry
4. background-size
5. background-position
od
background-position: center;
background-position: top right;
ith
6. background-attachment
ry
div {
background: url('[Link]') no-repeat center center / cover;
Border Properties
1. border-width
div {
border-width: 3px;
C
}
od
eW
2. border-style
border-style: dotted;
border-style: double;
ry
border-style: none;
3. border-color
border-color: darkgray;
4. Shorthand: border
div {
border: 2px solid #333;
}
5. Individual Sides
C
border-bottom: none;
border-left: 3px dotted green;
eW
ith
6. border-radius
H
button {
border-radius: 10px;
}
Summary
Padding vs Margin
padding Inside the element Between the content and the border
Padding
od
.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
Margin
.card {
margin: 30px;
}
C
od
Individual sides
ith
margin-top: 20px;
H
margin-right: 0;
ar
margin-bottom: 20px;
margin-left: auto;
ry
Shorthand
.container {
width: 500px;
margin: 0 auto;
}
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
1. block
div {
eW
display: block;
}
ith
H
2. inline
ar
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
• The element is not rendered, and does not take up any space.
.alert {
ith
display: none;
}
H
ar
Visual Example
Box 1
</div>
<div style="display: inline-block; width: 100px; background: lightblue;">
Box 2
</div>
nav {
display: block;
}
ith
nav a {
H
display: inline-block;
ar
padding: 10px;
}
ry
Summary
Value for
Description
Position
absolute
positioned ancestor
eW
sticky
scrolling
H
ar
1. static (Default)
ry
position: static;
}
You can’t move statically positioned elements with top , left , etc.
2. relative
.box {
position: relative;
top: 20px;
left: 10px;
3. absolute
eW
.parent {
position: relative;
ry
.child {
position: absolute;
top: 0;
right: 0;
}
4. fixed
.banner {
position: fixed;
top: 0;
left: 0;
width: 100%;
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;
}
.box {
position: absolute;
top: 50px;
left: 100px;
}
z-index
.modal {
position: absolute;
z-index: 100;
C
}
od
Summary
ith
Getting Started
.container {
display: flex;
}
C
od
Main Concepts
ith
Term Description
H
.container {
display: flex;
flex-direction: row; /* default */
flex-direction: row-reverse;
flex-direction: column;
flex-direction: column-reverse;
}
C
od
eW
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
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
.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;
}
.container {
gap: 20px;
.item {
H
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
Enabling Grid
.container {
display: grid;
}
structure:
H
.container {
ar
display: grid;
grid-template-columns: 200px 1fr 1fr;
ry
.container {
grid-template-columns: repeat(3, 1fr);
}
Grid Gap
.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;
}
grid-column: span 2;
}
.container {
display: grid;
grid-template-areas:
"header header"
"sidebar content"
"footer footer";
Auto-Placement
ry
.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">
.container {
display: grid;
grid-template-areas:
C
"header header"
od
"sidebar content"
"footer footer";
eW
.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
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
.container {
eW
padding: 20px;
font-size: 18px;
}
ith
.container {
ar
padding: 10px;
font-size: 16px;
ry
}
}
This approach ensures your layout adjusts smoothly as screen sizes change.
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 print {
body {
background: white;
color: black;
}
.no-print {
display: none;
}
}
C
Summary
--custom-name: value;
: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
body {
color: var(--primary-color);
font-size: var(--font-size);
}
:root {
--bg-color: white;
--text-color: black;
}
body {
C
background-color: var(--bg-color);
color: var(--text-color);
od
}
eW
.dark-theme {
--bg-color: #121212;
H
--text-color: #ffffff;
ar
}
ry
h1 {
color: var(--heading-color, blue);
}
Scoped Variables
.card {
--border-radius: 10px;
border-radius: var(--border-radius);
}
C
od
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;
}
Summary
1. CSS Transitions
Basic Syntax
selector {
transition: property duration timing-function delay;
}
C
od
ease-out , etc.)
Example
ry
.button {
background-color: blue;
color: white;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: green;
Shorthand vs Longhand
Shorthand:
Longhand:
transition-property: background-color;
transition-duration: 0.5s;
transition-timing-function: ease;
transition-delay: 0s;
C
od
2. CSS Animations
eW
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-duration
ar
animation-iteration-
Number of times to run (or infinite )
count
Looping Animations
.pulse {
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.1);
}
}
C
od
Transitions are great for hover and interactive effects. Animations are better for
more dynamic, self-running effects.
ith
.card {
ar
.card:hover {
transform: scale(1.05);
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
.card {
animation: fadeIn 1s ease;
}
Summary
1. transform Property
Syntax:
selector {
transform: function(value);
}
C
2. Types of Transformations
H
a. translate()
ar
ry
.box {
transform: translateX(50px); /* Move 50px to the right */
}
Other variations:
b. rotate()
.box {
transform: rotate(45deg); /* Rotate 45 degrees */
}
transform: rotate(-45deg);
C
c. scale()
od
.box {
transform: scale(1.5); /* Increase size by 1.5x */
ith
}
H
d. skew()
Individual axis:
• skewX(20deg)
• skewY(10deg)
e. matrix()
3. Transform Origin
By default, transforms are applied relative to the center of the element. You can
C
.box {
eW
transform: rotate(45deg);
transform-origin: top left;
}
ith
H
ar
.box {
transform: translateX(100px) rotate(30deg) scale(1.2);
}
The order matters: transforms are applied from left to right.
Example:
.box {
transform: rotateY(45deg);
transform-style: preserve-3d;
}
Summary
C
Rotates element
eW
rotate()
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:
Why JavaScript?
od
<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<script>
[Link]("JavaScript is working!");
</script>
</body>
</html>
<body>
<h1>Hello</h1>
<script src="[Link]"></script>
</body>
C
</html>
od
// [Link]
eW
[Link]("Hello JavaScript");
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
eW
multi-line comment
*/
ith
H
Summary
ar
What is a Variable?
No Yes Yes
eW
const
let score = 0;
score = 10;
// pi = 3.14; Error
Avoid var
null null
ith
undefined undefined
H
bigint 12345678901234567890n
ar
symbol Symbol("id")
ry
Type Example
Array [1, 2, 3]
Function function() {}
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;
typeof Operator
Summary
eW
• typeof is useful but not perfect (e.g., typeof null === "object" ).
H
ar
ry
Naming Variables in JavaScript
let name;
let _count;
let $price;
Invalid example:
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
Good Examples
Bad Examples
ith
When naming variables that store true or false , use prefixes like is , has , or
can to make their intent clear:
let isLoggedIn = 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
+ 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
2. Assignment Operators
= 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
4. Logical Operators
Example:
5. Ternary Operator
Summary
H
Basic Syntax
if (condition) {
// code to run if condition is true
} else {
// code to run if condition is false
C
}
od
eW
Example
ith
} else {
[Link]("You are a minor.");
}
if-else-if Ladder
} else {
[Link]("Grade: F");
}
Nested if Statements
C
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)
Summary
Creating an Object
let person = {
name: "Alice",
age: 30,
isEmployed: true
};
C
od
[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:
[Link] = 31;
person["name"] = "Bob";
[Link] = "Delhi";
person["hobby"] = "Reading";
Deleting Properties
delete [Link];
C
od
[Link]([Link]("city")); // true
H
ar
Nested Objects
let student = {
name: "John",
address: {
city: "Mumbai",
pin: 400001
}
};
[Link]([Link]); // "Mumbai"
C
od
let user = {
H
name: "Sara",
greet: function () {
ar
}
};
name: "Sara",
greet() {
[Link]("Hello, " + [Link]);
}
};
Summary
1. for Loop
Syntax
Example
C
[Link](i); // prints 0, 1, 2, 3, 4
}
eW
2. while Loop
Syntax
while (condition) {
Example
let count = 0;
while (count < 3) {
[Link](count); // prints 0, 1, 2
count++;
}
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
Syntax
Example
5. for...in Loop
C
od
Syntax
eW
Example
ry
JavaScript runs code from top to bottom, but you can control the flow using:
}
H
The first condition that is true will run, others will be skipped.
ar
ry
2. switch Statement
switch (day) {
case "Monday":
[Link]("Start of the week");
break;
case "Friday":
[Link]("End of the week");
break;
default:
[Link]("Midweek day");
}
3. Loops
C
a. for Loop
eW
}
ar
b. while Loop
ry
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++;
Example:
od
eW
}
H
ar
Summary
ry
break Statement
The break statement is used to exit a loop prematurely, before the loop condition
evaluates to false.
Syntax
break;
}
[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;
}
[Link](i);
}
C
Output:
od
1
eW
3
5
7
ith
9
H
Use Cases
ar
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
function greet() {
[Link]("Hello, JavaScript!");
}
function greetUser(name) {
[Link]("Hello, " + name);
ar
}
ry
function add(a, b) {
return a + b;
}
4. Function Expressions
sayHi();
eW
[Link](square(4)); // 16
One-liner version (if only returning a value):
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
Summary
ry
1. Creating Arrays
You can mix data types, but it’s better to keep arrays consistent.
[Link]("yellow");
[Link]();
C
[Link]();
eW
[Link]("pink");
H
ar
ry
5. Looping Through Arrays
[Link](fruits[i]);
}
Method Description
Example:
Summary
eW
easier.
H
[Link]("yellow");
[Link]();
[Link]();
od
[Link]("pink");
H
ar
ry
Looping Through Arrays
}
C
[Link](doubled); // [2, 4, 6]
ar
ry
Example:
C
od
[Link]([Link]("John")); // 2
[Link]([Link](" - ")); // Ali - Sara - John
ith
H
Summary
ar
ry
What is a String?
In JavaScript, strings are written inside single quotes, double quotes, or backticks.
All three are valid, but backticks ( ` ) are useful for string interpolation (covered
later).
C
od
Declaring Strings
eW
String Length
ry
You can check how many characters are in a string using the .length property.
[Link](text);
String Indexing
C
Using + operator:
Summary
Template literals are enclosed in backticks ( ` ) and can contain placeholders for
variables or expressions, which are wrapped in ${} .
This is line 2
This is line 3`;
eW
[Link](multiline);
ith
Summary
H
All string methods return a new string or value. The original string remains
unchanged.
1. length
[Link]([Link]()); // "ALI"
[Link]([Link]()); // "ali"
ar
ry
3. trim()
4. includes()
[Link]([Link]("a")); // 1
eW
[Link]([Link]("a")); // 5
ith
H
8. substring(start, end)
9. replace(old, new)
od
Note: Only the first match is replaced. To replace all, use a regular expression
with /g .
ar
ry
11. charAt(index)
12. repeat(count)
od
Summary
ry
Method Description
Introduction
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
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>
The browser parses the above HTML and creates a tree-like structure:
• document
• html
• head
• title
• body
• h1
• p
C
od
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
• window
• document
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
You don’t usually need to reference window explicitly, because it’s the default
context:
H
ar
The document object is a property of the window and serves as the main entry
point to the web page’s DOM.
Property Description
Example
eW
<!DOCTYPE html>
<html>
<head>
ith
<body>
ar
<h1>Hello World</h1>
<script>
ry
• 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
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
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.
2. innerHTML
H
<p id="demo">Hello</p>
3. value
The value property is used to get or set the value of form elements such as
<input> , <textarea> , and <select> .
4. style
C
You can change the inline style of an element using the style property.
od
eW
[Link] = "20px";
[Link] = "#f0f0f0";
ar
Property Purpose
Example:
[Link]("src", "[Link]");
ry
2. Removing Attributes
3. Adding Classes
Example:
<div id="box"></div>
[Link]("active");
[Link]("highlight", "shadow"); // Multiple classes
od
eW
4. Removing Classes
ith
[Link]("highlight");
ry
5. Toggling Classes
if ([Link]("active")) {
[Link]("The box is active");
}
Summary
Task Method
1. Creating Elements
Example:
[Link]("id", "dynamicDiv");
[Link]("box", "highlight");
ith
H
ar
2. Appending Elements
ry
<div id="container"></div>
3. Prepending Elements
[Link](heading);
od
eW
4. Removing Elements
ith
[Link](newDiv);
b) [Link]() (directly on the element)
Summary
Task Method
• Clicking a button
• Pressing a key
• Submitting a form
• Hovering over an element
• Scrolling the page
Events make your web pages interactive. They allow users to engage with your
C
1. click
H
});
3. submit
});
});
[Link]('mouseout', () => {
H
[Link] = '';
ar
});
ry
Example:
[Link]('h1').addEventListener('click', () => {
[Link]('Heading clicked!');
});
Summary
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 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.
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
Child clicked
Parent clicked
This shows that the event bubbles from the child to the parent.
Stopping Event Bubbling
[Link]();
});
• 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
});
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:
Syntax
});
od
This method tells the browser not to perform the default action associated with
eW
the event.
By default, submitting a form reloads the page. You can prevent this to handle
ry
<form id="myForm">
<input type="text" />
<button type="submit">Submit</button>
</form>
[Link]();
[Link]('Navigation prevented');
od
});
eW
In special cases, you might want to keep a checkbox from changing state:
H
[Link]();
[Link]('Checkbox toggle prevented');
});
When Not to Use preventDefault()
Summary
Key Features
Basic Syntax
C
od
// Set item
[Link]('key', 'value');
eW
// Get item
ith
// Remove item
H
[Link]('key');
ar
[Link]();
Example: Storing and Retrieving Data
[Link]('username', '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
};
if ([Link]('theme')) {
ar
[Link]('Theme is set');
}
ry
Use Cases
Limitations
Summary
What is JSON?
"name": "Harry",
"age": 25,
"skills": ["JavaScript", "Python"]
}
C
od
const user = {
name: 'Harry',
age: 25
};
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
try {
const data = [Link](badJSONString);
} catch (error) {
[Link]('Invalid JSON:', [Link]);
}
Summary
Types of Errors
Syntax:
eW
try {
// Code that may throw an error
} catch (error) {
ith
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');
}
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
try {
[Link]('invalid JSON');
} catch (error) {
[Link]([Link]); // SyntaxError
[Link]([Link]); // Unexpected token i in JSON
}
Best Practices
Summary
eW
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
clearTimeout(timeoutId);
setInterval() : Run Code Repeatedly
Syntax
setInterval(callback, interval);
Example
setInterval(() => {
[Link]('Runs every second');
}, 1000);
Canceling an Interval
Use clearInterval() to stop the repetition.
C
od
}, 1000);
ith
setTimeout(() => {
clearInterval(intervalId);
[Link]('Interval stopped');
H
}, 5000);
ar
ry
Use Cases
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
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.
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
• 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
[Link] is a runtime environment that lets you run JavaScript on the server, not
just in the browser.
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.
Displaying content, UI
Use case Storing data, handling logic
interaction
H
Limited (sandboxed)
resources network)
ry
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.
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
3. After installation, [Link] and npm will be available globally on your system.
ry
After installation, open a terminal (Command Prompt, Terminal, or shell) and check
the versions:
node -v
npm -v
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:
Summary
• 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.
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
touch [Link]
[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
node [Link]
ar
[Link] now supports watch mode natively (from version 18 and above)
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
Summary
ar
Open your terminal and create a new folder for your project:
mkdir my-node-app
cd my-node-app
Run the following command to create a [Link] file, which keeps track of
your project settings and dependencies:
eW
npm init -y
ith
Create a new file named [Link] (or any name you prefer):
touch [Link]
Open [Link] in your code editor and add the following code:
This creates a basic HTTP server that responds with “Hello, World!” to every
request.
node [Link]
If everything is set up correctly, you should see this message in the terminal:
ith
H
Open your web browser and visit [Link] You should see “Hello,
ry
World!” displayed.
Summary
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);
Example: [Link]
od
eW
// [Link]
function add(a, b) {
return a + b;
ith
}
H
[Link] = { add };
ar
// [Link]
ry
[Link](3000);
Summary
C
[Link] modules keep code organized, reusable, and maintainable. Whether you’re
od
1. CommonJS
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
Example:
// [Link]
export function add(a, b) {
return a + b;
}
// [Link]
import { add } from './[Link]';
[Link](add(2, 3));
Key Differences
require ,
Syntax import , export
od
[Link]
.js
extension "module"
Loading
ith
Synchronous Asynchronous
style
H
Top-level
Not supported Supported
await
ry
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.
This is known as the Module Wrapper Function. Because of this, your [Link] file
C
__filename
H
[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
require
module
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.
Synchronous Code
[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
[Link]("A");
setTimeout(() => {
[Link]("B");
}, 1000);
[Link]("C");
// Output:
// A
// C
// B (after about 1 second)
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
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
Summary
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.
With callbacks, things can quickly become hard to read and maintain, especially
when we have to wait for multiple things.
doTask1(function (result1) {
C
});
});
});
ith
This kind of nested code becomes difficult to manage. Promises solve this by
H
});
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
});
Let’s create a Promise that waits for 2 seconds and then resolves.
C
function waitTwoSeconds() {
od
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.
doTask1()
.then(function (result1) {
C
return doTask2(result1);
od
})
.then(function (result2) {
eW
return doTask3(result2);
})
.then(function (result3) {
ith
.catch(function (error) {
[Link]("Something failed", error);
ar
});
ry
• 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.
What is async ?
}
od
greet().then(function (message) {
eW
[Link](message); // "Hello"
});
ith
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
function waitTwoSeconds() {
return new Promise(function (resolve) {
setTimeout(function () {
resolve("Waited for 2 seconds");
}, 2000);
});
}
[Link]("End");
}
C
runTask();
od
Output:
eW
Start
Waited for 2 seconds
ith
End
H
ar
ry
[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.
function fakeTask(fail) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (fail) {
C
} else {
resolve("Task completed");
eW
}
}, 1000);
});
ith
}
H
} catch (error) {
[Link]("Caught error:", error);
}
}
run();
Summary
What is async ?
}
od
greet().then(function (message) {
eW
[Link](message); // "Hello"
});
ith
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
function waitTwoSeconds() {
return new Promise(function (resolve) {
setTimeout(function () {
resolve("Waited for 2 seconds");
}, 2000);
});
}
[Link]("End");
}
C
runTask();
od
Output:
eW
Start
Waited for 2 seconds
ith
End
H
ar
ry
[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.
function fakeTask(fail) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (fail) {
C
} else {
resolve("Task completed");
eW
}
}, 1000);
});
ith
}
H
} catch (error) {
[Link]("Caught error:", error);
}
}
run();
Summary
This might sound confusing at first, but once you see it in action, it becomes very
easy to understand.
function greet(name) {
H
}
ry
function processUser(callback) {
const userName = "Harry";
callback(userName);
}
processUser(greet);
function showMessage() {
[Link]("This runs after 2 seconds");
C
}
od
setTimeout(showMessage, 2000);
eW
Output:
H
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
setTimeout(function () {
[Link]("Hello after 1 second");
}, 1000);
[Link]("btn").addEventListener("click", function () {
[Link]("Button clicked");
});
C
Summary
ith
• 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]?
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.
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
• 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:
[Link](3000, () => {
H
Project Setup
mkdir express-intro
cd express-intro
npm init -y
1. Install Express:
eW
[Link]('Welcome to [Link]!');
});
node [Link]
[Link]
od
What is Routing?
In [Link], routes define the logic for what should happen when a user visits a
particular URL.
});
od
Route Parameters
Route parameters are named segments of the URL prefixed with a colon ( : ). They
allow you to capture values from the URL.
});
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
Introduction
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
Conclusion
C
applications where data structure may evolve over time or performance at scale is
critical.
eW
ith
H
ar
ry
Setting Up MongoDB
On Windows
1. Go to MongoDB Community Download Center.
mongod
C
od
MongoDB Atlas is the easiest way to get started without installing anything.
mongodb+srv://<username>:<password>@[Link]/myDatabase?
eW
retryWrites=true&w=majority
ith
mongodb://localhost:27017
You can:
await [Link]();
const db = [Link]('test');
eW
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.
• 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.
Before we start, let’s create a school database with students and teachers. Run this
in MongoDB Compass:
eW
[Link]([
ar
{
_id: ObjectId("507f1f77bcf86cd799439011"),
ry
experience: 8
},
{
_id: ObjectId("507f1f77bcf86cd799439013"),
name: 'Ms. Patel',
subject: 'Express',
experience: 3
}
])
{
od
name: 'Sara',
age: 20,
eW
course: '[Link]',
enrolled: true,
teacherId: ObjectId("507f1f77bcf86cd799439012"),
ith
},
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
[Link]({
name: 'Priya',
age: 19,
ith
course: 'MongoDB',
enrolled: true,
H
teacherId: ObjectId("507f1f77bcf86cd799439011"),
ar
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
find
ry
[Link]({})
Projections
Other Options
C
od
Limiting Results
eW
[Link]().limit(3)
ith
Sorting Results
H
[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 })
Summary
C
Note: All code examples are for MongoDB Compass shell (mongosh).
Updating Documents
C
updateOne
od
[Link](
{ name: 'Ali' },
H
updateMany
Updates all documents that match the filter.
Examples:
C
od
{ name: 'Sara' },
{ $push: { grades: 96 } }
)
ith
[Link](
ar
{ name: 'Ravi' },
{ $unset: { enrolled: "" } }
ry
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
_id: ObjectId("64bd2e183dd4e6402f10388f")
})
ith
{ _id: ObjectId("507f1f77bcf86cd799439011") },
{ $set: { office: "Room 301" } }
ar
)
ry
Practical Examples
[Link](
{ teacherId: ObjectId("507f1f77bcf86cd799439011") },
{ $push: { grades: 5 } } // Add 5 bonus points
)
C
od
eW
Summary
Note: All code examples are for MongoDB Compass shell (mongosh).
Comparison Operators
C
$in, $nin
Find students enrolled in either “MongoDB” or “[Link]”:
Logical Operators
C
od
$or
eW
[Link]({
ith
$or: [
{ course: 'Python' },
H
{ age: { $lt: 20 } }
ar
]
})
ry
age: { $gt: 20 },
enrolled: true
})
[Link]({
$and: [
{ age: { $gt: 20 } },
{ enrolled: true }
]
})
$not
Find students not enrolled in “[Link]”:
[Link]({
C
[Link]({
ar
enrolled: true,
$or: [
ry
Array Queries
[Link]({ grades: 95 })
[Link]({
grades: { $all: [90, 95] }
od
})
eW
[Link]({
ar
grades: { $size: 3 }
})
ry
[Link]({
$expr: {
$gt: [{ $avg: "$grades" }, 85]
}
})
sort()
C
od
[Link]().sort({ age: -1 })
[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)
Join-like Queries
C
teacherId: ObjectId("507f1f77bcf86cd799439011")
})
ar
ry
Count Operations
Count students per course:
Summary