11. Promises and Async/Await
Promises are used to handle asynchronous operations in JavaScript.
Promises
javascript
let promise = new Promise((resolve, reject) => {
let success = true; // Change to false to see the rejection
if (success) {
resolve("Promise resolved!");
} else {
reject("Promise rejected!");
}
});
promise.then((message) => {
console.log(message); // Outputs: Promise resolved!
}).catch((error) => {
console.error(error);
});
Async/Await
Async/Await makes it easier to work with promises.
javascript
async function fetchData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();
12. Classes
Classes in JavaScript are syntactic sugar over the existing prototype-based inheritance.
javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
let john = new Person('John', 30);
console.log(john.greet()); // Outputs: Hello, my name is John and I am 30 years old.
13. Modules
Modules in JavaScript allow you to break up your code into separate files and import/export functions, objects, or primitives.
Exporting
javascript
// file: myModule.js
export const name = 'Alice';
export function greet() {
return 'Hello!';
}
Importing
javascript
// file: main.js
import { name, greet } from './myModule.js';
console.log(name); // Outputs: Alice
console.log(greet()); // Outputs: Hello!
14. Error Handling
Error handling in JavaScript is done using try
, catch
, finally
, and throw
.
javascript
try {
let result = riskyOperation();
console.log(result);
} catch (error) {
console.error('Error:', error.message);
} finally {
console.log('Operation attempted');
}
function riskyOperation() {
throw new Error('Something went wrong!');
}
15. Higher-Order Functions
Higher-order functions are functions that operate on other functions, either by taking them as arguments or by returning them.
Example: map
javascript
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // Outputs: [2, 4, 6, 8, 10]
Example: filter
javascript
let numbers = [1, 2, 3, 4, 5];
let even = numbers.filter(function(num) {
return num % 2 === 0;
});
console.log(even); // Outputs: [2, 4]
16. Arrow Functions
Arrow functions provide a concise syntax for writing functions.
javascript
let add = (a, b) => a + b;
console.log(add(2, 3)); // Outputs: 5
let greet = name => `Hello, ${name}!`;
console.log(greet('Alice')); // Outputs: Hello, Alice!
17. Destructuring
Destructuring allows you to unpack values from arrays or properties from objects into distinct variables.
Array Destructuring
javascript
let [first, second, third] = [1, 2, 3];
console.log(first); // Outputs: 1
console.log(second); // Outputs: 2
console.log(third); // Outputs: 3
Object Destructuring
javascript
let person = {name: 'John', age: 30};
let {name, age} = person;
console.log(name); // Outputs: John
console.log(age); // Outputs: 30
18. Spread and Rest Operators
The spread operator allows an iterable to expand in places where zero or more arguments are expected.
Spread Operator
javascript
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5, 6];
console.log(newArr); // Outputs: [1, 2, 3, 4, 5, 6]
The rest operator allows you to represent an indefinite number of arguments as an array.
Rest Operator
javascript
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // Outputs: 6
console.log(sum(4, 5, 6, 7)); // Outputs: 22
19. Template Literals
Template literals allow you to embed expressions inside string literals using backticks `
.
javascript
let name = 'John';
let greeting = `Hello, ${name}!`;
console.log(greeting); // Outputs: Hello, John!
20. Fetch API
The Fetch API is used to make HTTP requests in JavaScript.
javascript
0 comments:
Post a Comment