0% found this document useful (0 votes)
21 views9 pages

Week 14

Full stack assessment 1

Uploaded by

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

Week 14

Full stack assessment 1

Uploaded by

Jangili Ajay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Week 14: Advanced JavaScript Concepts

1. ES6+ Features
ECMAScript 6 (ES6), also known as ECMAScript 2015, introduced significant
enhancements to JavaScript that improve its usability and efficiency. Below are key
features:
1.1 let and const
 let: Allows you to declare block-scoped variables. Unlike var, which is
function-scoped, let limits the variable's scope to the block in which it is
defined.
Example:
if (true) {
let x = 10; // x is scoped to this block
console.log(x); // Outputs: 10
}
console.log(x); // ReferenceError: x is not defined
 const: Similar to let, but the value assigned cannot be reassigned. This is useful
for defining constants.
Example:
const y = 20;
console.log(y); // Outputs: 20
// y = 30; // TypeError: Assignment to constant variable.
1.2 Template Literals
Template literals allow for easier string creation with embedded expressions and
multi-line strings using backticks (`).
Example:
const name = "John";
const greeting = `Hello, ${name}! Welcome to ES6.`;
console.log(greeting); // Outputs: Hello, John! Welcome to ES6.
Real-World Application: Sending personalized emails.
const userName = "Alice";
const signUpDate = "2024-10-19";
const emailContent = `Hi ${userName},\nWelcome! You signed up on $
{signUpDate}.`;
console.log(emailContent);
1.3 Destructuring Assignment
Destructuring allows you to unpack values from arrays or properties from objects into
distinct variables.
 Array Destructuring:Example:
const arr = [1, 2, 3];
const [a, b] = arr;
console.log(a); // Outputs: 1
console.log(b); // Outputs: 2
 Object Destructuring:Example:
const obj = { x: 1, y: 2 };
const { x, y } = obj;
console.log(x); // Outputs: 1
console.log(y); // Outputs: 2
1.4 Arrow Functions
Arrow functions provide a concise syntax for writing functions and lexically bind
the this value.
Example:
const add = (a, b) => a + b;
console.log(add(5, 3)); // Outputs: 8
// Single parameter example
const square = x => x * x;
console.log(square(4)); // Outputs: 16

Additional ES6 Features


 Rest and Spread Operators: These operators allow for more flexible function
arguments and array manipulations.
Rest Operator Example:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Outputs: 6
Spread Operator Example:
const obj1 = { name: "Alice" };
const obj2 = { age: 25 };
const combinedObj = { ...obj1, ...obj2 };
console.log(combinedObj); // Outputs: { name: 'Alice', age: 25 }
 Modules: ES6 introduced a standardized module system
using import and export, allowing better code organization.
Module Example:
// mathUtils.js
export function add(x, y) {
return x + y;
}
// app.js
import { add } from './mathUtils.js';
console.log(add(5,3)); // Outputs: 8

Synchronous vs. Asynchronous Programming in JavaScript

JavaScript is traditionally single-threaded, meaning it can only execute one task at a


time in a synchronous manner. However, JavaScript's event-driven model allows for
asynchronous programming, making it possible to perform tasks like handling events,
making HTTP requests, or reading from a file system without blocking the execution
of other tasks.

Synchronous Programming

In synchronous programming, tasks are executed one after another. The code is read
and executed line by line, and the next line cannot execute until the current line
finishes.
Example:
console.log("Task 1");
console.log("Task 2");
console.log("Task 3");

In this example, "Task 1" is logged first, followed by "Task 2" and "Task 3". The
output is sequential and predictable.

While synchronous execution is simple and easy to understand, it can cause problems
when dealing with long-running tasks. For example, if a task takes a long time (like
reading a file or making an HTTP request), the entire program is blocked until that
task finishes.

Asynchronous Programming

Asynchronous programming allows JavaScript to handle long-running tasks while


continuing to execute other code. Asynchronous functions can be thought of as tasks
that are delegated to the event loop, which handles them separately while other code
continues to execute.

Example:
console.log("Start");
setTimeout(() => {
console.log("Asynchronous Task");
}, 1000);
console.log("End");

Output:
Start
End
Asynchronous Task
In this example, the setTimeout function is asynchronous. Even though it's called
second, the code inside it executes after a 1000ms delay, while the rest of the code
continues to run.
3. Callbacks and Promises
Callbacks and promises are fundamental concepts for handling asynchronous
operations in JavaScript.
3.1 Callbacks
A callback is a function passed as an argument to another function and is executed at a
later time when an operation completes.
Example:
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData((data) => {
console.log(data); // Outputs: Data received (after one second)
});
Real-World Application of Callbacks
Callbacks are commonly used in event handling or when making API requests where
you want to perform actions after data retrieval.
3.2 Promises
Promises represent a value that may be available now or in the future or never. They
can be in one of three states: pending, fulfilled, or rejected.
Creating a Promise:
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
// reject("Error occurred"); // Uncomment to simulate an error.
}, 1000);
});
// Consuming a Promise
promise.then(data => {
console.log(data); // Outputs: Data received (after one second)
}).catch(error => {
console.error(error);
});
Real-World Application of Promises
Promises are often used in handling API responses where you might want to process
data once it's available.
Error Handling with Promises
You can handle errors in promises using .catch():
promise.catch(error => {
console.error('Fetch error:', error);
});
Comparison of Asynchronous Patterns
Feature Callbacks Promises Async/Await

Synchronous-like
Syntax Nested functions Chained .then() calls syntax

Difficult with multiple


Error Handling callbacks .catch() for errors Try/catch blocks

More readable than


Readability Can become hard to read callbacks Most readable

State No built-in state Managed via


Management management Pending, fulfilled, rejected async/await

4. Async/Await Syntax
The async/await syntax provides a way to work with promises that makes
asynchronous code easier to read and write.
Using Async/Await
 The async keyword is used before a function declaration to define an
asynchronous function.
 The await keyword can be used inside an async function to pause execution
until the promise settles.
Example:
async function fetchData() {
let data = await new Promise((resolve) => {
setTimeout(() => {
resolve("Data received");
}, 1000);
});
console.log(data);
}

fetchData(); // Outputs: Data received (after one second)


Error Handling with Async/Await
You can handle errors in async functions using try/catch blocks:
async function fetchData() {
try {
let data = await new Promise((resolve) => {
setTimeout(() => {
resolve("Data received");
}, 1000);
});
console.log(data);
} catch (error) {
console.error(error);
}
}

fetchData(); // Outputs: Data received (after one second)


Real-World Application of Async/Await
Async/await simplifies working with APIs by making the code look synchronous
while still being asynchronous:
async function getUserData() {
try {
const response = await fetch('https://api.example.com/user');
if (!response.ok) throw new Error('Network response was not ok');

const userData = await response.json();


console.log(userData);
} catch (error) {
console.error('Fetch error:', error);
}
}

getUserData();

5. Fetch API for Making HTTP Requests


The Fetch API provides a modern way to make network requests in JavaScript. It
returns promises and offers more powerful features than XMLHttpRequest.
Basic Fetch Example
To make a GET request using the Fetch API:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json(); // Parsing JSON response body.
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Using Async/Await with Fetch
You can also use async/await syntax with the Fetch API for cleaner code:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('Network response was not ok')
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch error:', error);
}
}
fetchData();
Exercises and Practice Problems
To reinforce learning about these concepts, consider the following exercises:
1. Create a Function Using Arrow Syntax:
 Write an arrow function that takes two numbers as parameters and
returns their product.
2. Use Destructuring Assignment:
 Given an object representing a book ({ title: "1984", author: "George
Orwell", yearPublished: "1949" }), destructure it into separate variables
for each property.
3. Implement Promises:
 Create a promise that resolves after two seconds with a message
"Promise resolved!" and log it when it resolves.
4. Fetch User Data:
 Write an async function that fetches user data from an API (e.g.,
JSONPlaceholder) and logs the user's name.
5. Error Handling with Async/Await:
 Modify your fetch user data function to handle errors gracefully using
try/catch blocks.

You might also like