JavaScript Async and
await
"async and await make promises easier to
write"
What? async makes a function return a Promise
await makes a function wait for a Promise
The keyword async before a function makes the function return a promise:
Async
Syntax
How to
use?
Complete
example
The await keyword can only be used inside
an async function.
The await keyword makes the function pause the
Await execution and wait for a resolved promise before it
syntax continues:
Example
Example –
waiting for
a timeout
Module 8 - JavaScript
Error Handling
JavaScript error handling allows you
JavaScript to manage runtime errors in a clean
Errorhandlin and controlled way, so your
g application doesn’t crash
unexpectedly.
Syntax Errors – Mistakes in code syntax
(e.g., missing brackets).
Runtime Errors – Happen during
Types of execution (e.g., accessing an undefined
errors variable).
Logical Errors – Code runs but gives the
wrong result.
Handling parse error
Example
Handling call back errors
Example 2
Example –
custom
function
compariso
n
Promise: “Here’s a ticket. Wait over there. I’ll call
you when it’s ready.”
Async/Await: “Sit down. I’ll pause the story until
the result is ready, then continue.”
Module 9
Javascript local storage and API
JavaScript localStorage is a feature
that lets you store data in your
browser using key-value pairs.
What is The data stays saved even after you
local close the browser, so it can be used
storage? again when you open it later.
This helps keep track of things like
user preferences or state across
different sessions.
Origin-Bound Storage: Data is stored per domain
and is not shared across different origins.
Persistent Storage: It will be available until manually
cleared.
Storage Limit: The storage limit for cookies is 4KB,
Features which is much smaller compared to the 5MB limit for
localStorage.
No Automatic Transmission: Unlike cookies,
localStorage data is not sent with every HTTP request,
making it a more efficient option for client-side storage.
To store data in localStorage, use the
setItem() method. This method
accepts two arguments:
The key (a string), which is the
Storing identifier for the stored data.
data The value (also a string), which is the
data you want to store.
localStorage.setItem('key',
'value');
To retrieve the data you stored, use the
getItem() method.
This method takes the key as an argument
and returns the associated value.
Retrieving If the key does not exist, it returns null.
data
let value =
localStorage.getItem('key');
To remove a specific item from localStorage,
use the removeItem() method.
This method accepts the key of the item you
want to remove.
Removing
data
localStorage.removeItem('key');
If you want to clear all data stored in
localStorage, use the clear() method.
This will remove all key-value pairs stored in
the localStorage for the current domain.
Clearing
data
localStorage.clear()
;
You can check if a key exists in localStorage
by using getItem().
If the key doesn’t exist, getItem() will return
null.
Check if if (localStorage.getItem('username') !== null) {
key exist console.log('Username exists in localStorage');
} else {
console.log('Username does not exist in
localStorage');
}
Example
localStorage only stores data as strings.
If you need to store objects, arrays, or other
Storing complex data types, you must convert them
into a string format.
non-string
JSON.stringify() to convert an object into a
data JSON string, and JSON.parse() to convert it
back into an object.
Example
Review
Persistence: Data stored in localStorage remains
even after the browser is closed, which is useful
for retaining user preferences and session data.
Simple API: The API for using localStorage is
straightforward and easy to use.
Advantage Large Storage Capacity: localStorage allows
s you to store up to 5MB of data per domain in most
browsers.
No Server Interaction: Data is stored directly in
the client’s browser, so it doesn’t require any
server-side communication.
Security: Data stored in localStorage is not
encrypted, making it vulnerable to cross-site
scripting (XSS) attacks. Sensitive data like
passwords or tokens should not be stored in
localStorage.
Disadvanta Synchronous: localStorage is a synchronous
ges API, meaning it may block the main thread when
storing or retrieving large amounts of data.
Limited Capacity: The storage capacity
(around 5MB) might not be enough for larger
datasets.
JavaScript sessionStorage is a web
storage technique that stores data for the
duration of a page session.
The sessionStorage object lets you store
Session key/value pairs in the browser.
storage It allows setting, retrieving, and managing
data that persists only until the browser tab
or window is closed, ensuring data
accessibility within the same tab.
window.sessionStorage
;
Temporary Storage: Data is stored only for the
duration of the session.
Tab-Specific: Data is accessible only within the
same browser tab or window.
Simple API: Provides straightforward methods for
Features setting, getting, and removing items.
Persistent During Reloads: Data persists
across page reloads within the same session.
Storage Limit: Offers around 5MB of storage per
origin for session data.
Feature Local Storage 🕒 Session Storage
Lifespan Persists even after browser is closed Clears when tab or browser is closed
Storage Limit ~5–10 MB (depending on browser) ~5 MB (same as Local Storage)
Scope Shared across all tabs/windows of a domain Unique to each tab/window
Use Case Store data for long-term use Store data for temporary session
Example Data Login tokens, theme settings Form data, wizard progress
API Syntax localStorage.setItem('key', 'value') sessionStorage.setItem('key', 'value')
Auto Expiry ❌ Must be manually cleared ✅ Automatically cleared on tab/browser close
Accessible From Any tab of same origin Only within the tab that created it
Fetch data using API
•fetch() – to make the HTTP request
•JSON.parse() – to convert JSON text to a JavaScript object
fetch(url) is used to make a network
request.response.json() parses the response body
automatically.
JSON.parse() is used if you're manually handling raw
JSON strings.
1.User clicks the "Fetch User" button.
2.A fetch request is sent to https://jsonplaceholder.typicode.com/users/1.
process 3.JSON data is manually parsed using JSON.parse().
4.User details are displayed in the browser.
User types a number between 1 and 10.
fetch() is called to get that specific
Example user's data.
(api- JSON is fetched as text, then parsed
1.html) using JSON.parse().
User details (Name, Email, Phone, City)
are shown in the browser.
API stands for Application Programming
Interface.
In simple terms, it allows two systems to
communicate with each other. In web
API development, an API is often a URL (web
address) that you can use to:
Get data from a server (like weather, news, user
data, etc.)
Send data to a server (like submitting a form or
registering a user)
A weather app on our phone talks to a server
using an API to get real-time weather data.
You don’t need to build your own Google
Maps — you can use the Google Maps API to
Real-time show maps on your website.
example
APIs allow developers to separate:
Frontend (UI) — the part users see
Backend (server/database) — where data is stored
Task API Used
Check weather OpenWeather API
Login with Google Google OAuth API
Get movie info IMDb API
Translate text Google Translate API
Post to Instagram Instagram API
Get COVID-19 stats Government Health API
APIs use standard formats like JSON or XML,
so systems can share data easily—even if they're
built with different programming languages.
APIs allow websites and apps to get real-time
data.
Examples:
Stock prices
Train schedules
Live sports scores
https://jsonplaceholder.typicode.com/users fake
online REST API for testing and learning
purposes. It’s free and open to use.
It is not a real service — it just simulates
responses.
You can use it to practice fetch() without
needing to build your own backend or database.
Handling API
responses
Handling API responses
effectively in JavaScript is
crucial for building robust web
applications.
When using fetch(), it returns a
Promise that resolves to a
Response object.
fetch(url)
.then(response => {
// Step 1: Check if response is OK (status 200–
299)
// Step 2: Parse the response (usually JSON)
syntax })
.catch(error => {
// Handle network errors (e.g., no internet,
timeout)
});
Scenario How to Handle
Parse with .json() or
Response ✅ Status is OK (200–299)
JSON.parse()
scenarios Handle with custom error
❌ Status is 404 or 500
message
Use .catch() to handle
❌ Network Error
rejection
Tries to fetch a user with ID 9999 from a
placeholder API.
Example – The user doesn't exist → API returns 404.
api-2.html The script catches this and shows:🚫 User not
found (404)
ES-6 Features
Features ES6+ (ECMAScript 2015 and beyond)
let count = 10; // Mutable
Let and const name = "John"; //
const Immutable
Shorter syntax for functions.
// Traditional
function add(a, b) {
return a + b;
Arrow
}
Functions ()
=> {}
// Arrow
const add = (a, b) => a + b;
Use backticks `` to emconst user =
"Alice";
const greeting = `Hello, ${user}!`;
Template console.log(greeting); // Hello, Alice!
literals bed expressions easily.
Extract values from arrays and
objects.
// Object
const person = { name: "Sam", age:
30 };
Destructuri
const { name, age } = person;
ng
// Array
const [a, b] = [10, 20];
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
Default greet(); // Hello, Guest
Parameter greet("Anil"); // Hello, Anil
s
// Spread (expand)
Used to unpack values from an array or object
and expand them.
const arr1 = [1, 2];
Spread const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
and rest const student = { name: 'Geetha', age: 20 };
operators const updatedStudent = { ...student, age: 21, city:
'Chennai' };
console.log(updatedStudent);
// Output: { name: 'Geetha', age: 21, city: 'Chennai' }
// Rest (gather)
Used to collect remaining values into an array or object.
function sum(...nums) {
return nums.reduce((a, b) => a + b);
}
Rest
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(10, 20, 30, 40));
// Output: 100
Optional chaining allows you to safely access
a property of an object that might not exist,
without throwing an error.
Optional It helps you safely access deeply nested
chaining properties without having to check every level
for null or undefined.
It avoids runtime errors if a property doesn’t
exist.
const user = {
name: 'Geetha',
address: {
city: 'Chennai'
// No 'zipcode' property
Example – }
optional };
chaining console.log(user.address.zipcode); // ❌ undefined
console.log(user.contact.phone); // ❌ Error: Cannot read properties
of undefined
console.log(user?.address?.city); // ✅ Chennai
console.log(user?.address?.zipcode); // ✅ undefined (no error)
console.log(user?.contact?.phone); // ✅ undefined (no error)
They allow you to split your code into
multiple files (called modules) and reuse
functionality between them, making your
project:
Import /
Easier to manage
export
Cleaner to maintain
More reusable and testable
You can export:
variables
functions
classes
entire objects
math.js
Export export const PI = 3.14;
export function add(x, y) {
return x + y;
}
import { PI, add } from './math.js';
console.log(add(5, 10)); // 15
Greet.js
export default function greet(name) {
return `Hello, ${name}`;
}
Default
export import greet from './greet.js';
console.log(greet('Geetha')); // Hello, Geetha
import * as math from './math.js';
Import all console.log(math.PI); // 3.14
console.log(math.add(3, 4)); // 7
Overview of
Javascript
frameworks
JavaScript frameworks are pre-
written JavaScript code libraries
that help developers build
What? applications faster and easier by
providing structure and reusable
components.
Without Framework With Framework
Manual DOM Automatic UI updates
With and manipulation
without More code to write Pre-built
functions/components
framework Harder state Organized state control
management
No app structure Built-in project structure
Types of Front-end frameworks
JavaScript Backend frameworks
Framework
s
Framework Description
Developed by Meta. Component-
React (library)
based, fast, uses virtual DOM.
Full-fledged framework by
Frontend - Angular Google. Includes routing, forms,
HTTP services, etc.
Lightweight, progressive
Vue.js framework. Easy to learn and
flexible.
Compiles to vanilla JS. No virtual
Svelte
DOM. Extremely fast.
Run on the server and handle data, APIs, etc.
Backend -
Use Case Recommended
Want flexibility & huge
React
ecosystem
Need a complete solution Angular
Use case
Simple and easy to start Vue.js
Server-side rendering Next.js
Lightweight & fast Svelte
Server APIs Express.js or NestJS
Layer When to Use
Building rich UI/UX in the
Frontend
browser
Backend Creating APIs or server logic
SEO + frontend + backend in
Full-stack
one
Feature Purpose
Components Reusable building blocks
State Management Track and update data
Routing Navigate between pages
Key Control code execution
Features Lifecycle Hooks
timing
Templates Easier HTML generation
Data Binding Connect UI with JS logic
Project Description Concepts Used
Add, edit, delete, mark DOM, Arrays,
✅ To-Do List
tasks Events
✅ Calculator Basic calculator with UI Operators, DOM
✅ Digital Clock Shows current time live Date(), setInterval()
Increment/decrement
✅ Counter App Event Listeners
with buttons
Enter amount & tip % to Input handling,
Project ideas ✅ Tip Calculator
get total Math
✅ Palindrome Check if word/number is String/Array
Checker a palindrome methods
Button to change DOM, random
✅ Color Changer
background color colors
Next/previous slideshow Arrays, DOM
✅ Image Slider
of images manipulation
Project Key Concepts Features
Weather App
fetch, async/await City input + weather
(OpenWeather API)
🎲 Dice Game / Rock
Math, random logic Player vs Computer
Paper Scissors
🛒 Shopping Cart Arrays, localStorage Add/remove, total price
🧠 Quiz App Arrays, event handling Scores, multiple questions
📅 Static Calendar Date object, loops Highlights current day
🧾 Expense Tracker Forms, localStorage Add/delete, balance
🔍 Live Search Filter filter(), events Filter list as you type
🔐 Login/Register Form Validation, localStorage Basic fake auth
🎨 Theme Switcher
CSS, localStorage Button toggle
(Dark/Light)
📧 Email Validator Regex, form events Checks email format live