Week 14
Week 14
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
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
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
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);
}
getUserData();