Modern JavaScript
Explore the essential concepts and advanced techniques that power today's dynamic web applications.
Synchronous & Asynchronous Async/Await & Literals
API & HTTP Error Handling
Synchronous JavaScript
Synchronous JavaScript executes code sequentially, line by line. Each operation must complete Common Use Cases
before the next one begins, creating a predictable flow.
• Form validation: Ensuring all fields are correct before
submission.
[Link]("Task 1");
[Link]("Task 2"); • Simple calculations: Immediate results for basic arithmetic.
[Link]("Task 3"); • UI updates: Direct manipulation of the DOM for instant
visual feedback.
Key Characteristics
Blocking
Tasks run one after another, blocking further execution until completed.
Predictable
Execution order is guaranteed, simplifying debugging for linear tasks.
Asynchronous JavaScript
Asynchronous JavaScript enables long-running tasks to execute in the background without freezing the main thread, allowing other code to continue running
[Link]("Start");
Practical Applications
setTimeout(() => { • API calls: Fetching data from servers without freezing the UI.
[Link]("Async Task");
• Database operations: Querying databases in the background.
}, 2000);
• Timers and animations: Creating dynamic and responsive
[Link]("End");
user experiences.
• Loading large files: Downloading content while the user can
This example demonstrates how "Async Task" runs after a delay, without
blocking "End" from printing immediately. still interact.
Why Asynchronous?
Improved Responsiveness
Keeps the user interface interactive during lengthy operations.
Efficient Resource Use
Maximizes CPU utilization by not waiting idly for I/O operations.
Async / Await: Simplifying Asynchronicity
Async/Await is a modern JavaScript feature introduced in ES2017 that offers a more readable and synchronous-looking way to write asynchronous code, built on top of Promises.
1 2
Async Function Await Keyword
A function declared with async always returns a Promise. The await keyword can Pauses the execution of the async function until the Promise settles (resolves or
only be used inside async functions. rejects), and then resumes execution with the Promise's resolved value.
async function getData() {
const response = await fetch(url);
const data = await [Link]();
[Link](data);
}
Real-World Scenarios
Weather Applications Login Systems Interactive Dashboards
Fetching real-time weather data for display. Handling user authentication and fetching user profiles. Populating dashboards with dynamic data from
various sources.
Template Literals: Dynamic String Creation
Template literals provide a powerful way to create strings in JavaScript, offering enhanced readability and functionality over traditional string
concatenation. They are enclosed by backticks (``).
Embedded Expressions Multi-line Strings Tagged Templates
Allows embedding variables or expressions Supports multi-line strings without the need for Advanced feature allowing a function to parse
directly within the string using ${expression}. special escape characters (\n). the template literal for custom processing.
let name = "Ali";
let age = 22;
let message = `Name: ${name}, Age: ${age}`;
This makes string manipulation much cleaner and more intuitive.
Key Benefits on the Web
• Displaying API data: Easily format fetched data into user-friendly strings.
• Dynamic HTML generation: Constructing HTML elements and content on the fly.
• Custom messages and alerts: Creating personalized notifications.
• Internationalization: Simplifying translation by embedding variables.
API Integration with Fetch API
An API (Application Programming Interface) defines the rules for how software components should interact. The Fetch API in JavaScript
provides a modern and flexible interface for making network requests to interact with APIs.
fetch(url)
.then(response => [Link]())
.then(data => [Link](data));
Promise-Based Supports CORS
Fetch API returns Promises, allowing for chaining .then() Handles Cross-Origin Resource Sharing (CORS) policies for
and .catch() methods, or using async/await for cleaner secure cross-domain requests.
code.
Web Application Examples
• Weather applications: Retrieving current weather conditions from a server.
• Social media feeds: Populating timelines with posts and updates.
• E-commerce websites: Fetching product catalogs, prices, and customer reviews.
• Real-time chat applications: Sending and receiving messages instantly.
HTTP Request & Response Handling
HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the web. It defines how clients (like your browser) request information from servers and how servers respond.
Request
1 Sent from client to server, asking for a resource or action.
Response
2 Sent from server to client, containing the requested data or status.
Common HTTP Methods
GET POST
Retrieve data from the server. Send new data to the server.
PUT DELETE
Update existing data on the server. Remove data from the server.
XML & JSON: Data Interchange Formats
XML and JSON are two popular formats for structuring and exchanging data over the web. While XML is older and more verbose, JSON has become the de facto
standard due to its lightweight nature and ease of parsing in JavaScript.
XML (Extensible Markup Language) JSON (JavaScript Object Notation)
XML uses a tag-based structure, similar to HTML, to define data elements. JSON is a lightweight data-interchange format, inspired by JavaScript object
literal syntax.
<user>
<name>Ali</name> {
<age>22</age> "name": "Ali",
</user> "age": 22
}
• Self-describing and human-readable.
• • Easily parsed by JavaScript (and many other languages).
Widely used in enterprise applications and SOAP web services.
• Less verbose, leading to smaller file sizes and faster transmission.
• Dominant format for RESTful APIs.
JSON Handling
Converting a JSON response into a JavaScript object is straightforward:
const data = await [Link]();[Link]([Link]);
Try–Catch: Robust Error Handling
Error handling is crucial for building stable and reliable web applications. The try...catch statement in JavaScript allows you to gracefully manage runtime errors, preventing your
application from crashing and providing a better user experience.
Try Block Catch Block
Contains the code that might throw an error. If an error occurs here, execution Contains the code to be executed if an error occurs in the try block. It receives the
immediately jumps to the catch block. error object as an argument.
try {
const response = await fetch(url);
if (![Link]) {
throw new Error(`HTTP error! Status: ${[Link]}`);
}
const data = await [Link]();
[Link](data);
} catch (error) {
[Link]("Failed to fetch data:", [Link]);
// Display a user-friendly error message
}
Essential for Stability
• API calls: Handling network issues or invalid responses.
• Form submission: Validating user input and catching server errors.
• Network error handling: Providing fallbacks when resources are unavailable.
• Parsing JSON: Preventing errors from malformed data.