Advanced JavaScript Concepts
Advanced JavaScript Concepts
5. Advanced JavaScript:
Asynchronous JavaScript:
Callbacks, Promises, async/await.
Fetch API: Making HTTP requests.
Local Storage & Session Storage: Storing data in the browser.
Classes: OOP concepts in JavaScript (class, constructor, extends).
Prototypes: Understanding prototype inheritance.
Here’s a detailed overview of the advanced JavaScript topics you've mentioned, along with
explanations and examples:
1. Asynchronous JavaScript
Asynchronous JavaScript allows you to execute code without blocking the execution of other code,
which is crucial for tasks like making network requests. Here are the main concepts:
a. Callbacks
A callback is a function passed as an argument to another function and is executed after a certain
event or operation completes.
Example:
javascript
function fetchData(callback) {
setTimeout(() => {
// Simulating a network request
const data = { id: 1, name: 'John Doe' };
callback(data);
}, 2000); // Delay of 2 seconds
}
fetchData((data) => {
console.log('Data received:', data);
});
b. Promises
A Promise represents a value that may be available now, or in the future, or never. It can be in one of
three states: pending, fulfilled, or rejected.
Example:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/10
javascript
fetchDataPromise()
.then((data) => console.log('Data received:', data))
.catch((error) => console.error('Error:', error));
c. async/await
`async/await` is syntactic sugar over Promises, making asynchronous code easier to read and write.
Example:
javascript
fetchDataAsync();
2. Fetch API
The Fetch API provides a modern way to make network requests. It returns a Promise that resolves to
the Response object representing the response to the request.
Example:
javascript
fetchUserData();
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/10
Both Local Storage and Session Storage allow you to store data in the browser. Local Storage persists
even after the browser is closed, while Session Storage is cleared when the page session ends.
Example:
javascript
// Local Storage
localStorage.setItem('username', 'JohnDoe');
const username = localStorage.getItem('username');
console.log('Username from Local Storage:', username);
// Session Storage
sessionStorage.setItem('sessionKey', 'sessionValue');
const sessionValue = sessionStorage.getItem('sessionKey');
console.log('Session Value:', sessionValue);
JavaScript supports object-oriented programming (OOP) through the use of classes. Classes can have
constructors and can extend other classes.
Example:
javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
}
}
introduce() {
super.introduce();
console.log(`I'm studying ${this.major}.`);
}
}
5. Prototypes
Prototypes in JavaScript allow you to implement inheritance. Every object has a prototype from which
it can inherit properties and methods.
Example:
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/10
javascript
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name); // Call the parent constructor
}
Summary
These advanced JavaScript concepts are essential for building modern web applications.
Understanding how to handle asynchronous operations, manage data storage, leverage OOP
principles, and use prototypes will significantly enhance your coding capabilities. If you have any
questions about specific topics or want to dive deeper into any of these areas, feel free to ask!
now make some questions for my improvement in JS coding and problem solving skills
Memory updated
Here are some questions designed to improve your JavaScript coding and problem-solving skills,
ranging from basic to advanced:
1. Basic Level
1. Write a function that takes an array of numbers and returns a new array containing only the even
numbers.
2. Create a function that accepts a string and returns the string reversed.
3. Write a function to find the factorial of a given number using both iterative and recursive
approaches.
4. Given a string, write a function to count the number of vowels in the string.
5. Create a function that takes two arguments and returns their sum. If only one argument is
provided, it should return a function that expects another argument and returns the sum.
2. Intermediate Level
1. Write a function to flatten a nested array (e.g., `[1, [2, [3, 4], 5]]` should become `[1, 2, 3,
4, 5]`).
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/10
2. Implement a `debounce` function in JavaScript, which ensures that a function is not called too
frequently.
3. Create a function that deep clones an object (handles nested objects and arrays).
4. Write a function that accepts an array of integers and returns the first duplicate number.
5. Using the `fetch` API, write a function that makes a GET request to an API endpoint and displays
the data in a list format.
3. Advanced Level
1. Write a function that converts a string into `camelCase`, `snake_case`, and `kebab-case`.
2. Create a function that memoizes another function to improve performance for repeated
calculations.
3. Build a simple promise-based wrapper around `setTimeout` to create a function called `delay`
that resolves after a given number of milliseconds.
4. Write a function that implements a simple pub/sub pattern for event handling.
5. Implement a function that checks if a given object matches the structure of another object
(useful for validating object schemas).
1. Create a class `Rectangle` that has properties for `width` and `height` and methods to calculate
the area and perimeter. Extend this class into a `Square` class.
2. Implement a class `BankAccount` with methods for `deposit`, `withdraw`, and `getBalance`, and
create a subclass `SavingsAccount` with an additional `interestRate` property.
3. Write a class that manages a simple in-memory database with methods for `addRecord`,
`removeRecord`, and `findRecord`.
5. Asynchronous JavaScript
1. Write a function that uses `async/await` to fetch user data from an API and handle errors
gracefully.
2. Create a function that makes multiple API requests in parallel and combines the results.
3. Write a function that reads data from local storage, processes it, and then updates the data in
session storage.
6. Coding Challenges
1. FizzBuzz: Write a function that prints numbers from 1 to 100. But for multiples of 3, print "Fizz";
for multiples of 5, print "Buzz"; and for multiples of both, print "FizzBuzz".
2. Two Sum Problem: Given an array of integers, return indices of the two numbers such that they
add up to a specific target.
3. Palindrome Checker: Write a function that checks if a given string is a palindrome (reads the
same backward as forward).
4. Anagram Detector: Create a function that takes two strings and returns `true` if they are
anagrams of each other.
5. Sorting Algorithm: Implement sorting algorithms like `bubble sort`, `selection sort`, or `merge
sort` and compare their performance.
These questions should give you a balanced mix of practice in coding, problem-solving, and
understanding advanced JavaScript concepts. Let me know if you need solutions or hints for any of
these!
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/10
now answer of them
Here are the answers to the JavaScript questions designed to improve your coding and problem-
solving skills:
1. Basic Level
javascript
function getEvenNumbers(arr) {
return arr.filter(num => num % 2 === 0);
}
console.log(getEvenNumbers([1, 2, 3, 4, 5])); // Output: [2, 4]
2. Reverse a String:
javascript
function reverseString(str) {
return str.split('').reverse().join('');
}
console.log(reverseString('hello')); // Output: 'olleh'
javascript
function factorialIterative(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorialIterative(5)); // Output: 120
Recursive:
javascript
function factorialRecursive(n) {
if (n === 0) return 1;
return n * factorialRecursive(n - 1);
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/10
}
console.log(factorialRecursive(5)); // Output: 120
javascript
function countVowels(str) {
const vowels = 'aeiouAEIOU';
return str.split('').filter(char => vowels.includes(char)).length;
}
console.log(countVowels('hello world')); // Output: 3
javascript
function sum(a, b) {
if (b !== undefined) {
return a + b;
} else {
return function(b) {
return a + b;
};
}
}
console.log(sum(2, 3)); // Output: 5
console.log(sum(2)(3)); // Output: 5
2. Intermediate Level
javascript
function flattenArray(arr) {
return arr.flat(Infinity);
}
console.log(flattenArray([1, [2, [3, 4], 5]])); // Output: [1, 2, 3, 4, 5]
2. Debounce Function:
javascript
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/10
const debouncedFunction = debounce(() => console.log('Debounced!'), 1000);
debouncedFunction();
javascript
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
const original = { a: 1, b: { c: 2 } };
const clone = deepClone(original);
console.log(clone); // Output: { a: 1, b: { c: 2 } }
javascript
function findFirstDuplicate(arr) {
const seen = new Set();
for (let num of arr) {
if (seen.has(num)) return num;
seen.add(num);
}
return null;
}
console.log(findFirstDuplicate([2, 3, 3, 1, 5])); // Output: 3
javascript
3. Advanced Level
javascript
function convertCases(str) {
const camelCase = str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, (match, index) =>
index === 0 ? match.toLowerCase() : match.toUpperCase()
).replace(/\s+/g, '');
const snake_case = str.toLowerCase().replace(/\s+/g, '_');
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/10
const kebabCase = str.toLowerCase().replace(/\s+/g, '-');
return { camelCase, snake_case, kebabCase };
}
console.log(convertCases('Hello World'));
// Output: { camelCase: 'helloWorld', snake_case: 'hello_world', kebabCase: 'hello-
world' }
2. Memoization Function:
javascript
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (!cache[key]) {
cache[key] = fn(...args);
}
return cache[key];
};
}
const memoizedFactorial = memoize(factorialRecursive);
console.log(memoizedFactorial(5)); // Output: 120
javascript
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
delay(2000).then(() => console.log('Executed after 2 seconds'));
javascript
class PubSub {
constructor() {
this.events = {};
}
subscribe(event, listener) {
if (!this.events[event]) this.events[event] = [];
this.events[event].push(listener);
}
publish(event, data) {
if (this.events[event]) {
this.events[event].forEach(listener => listener(data));
}
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/10
5. Object Structure Validator:
javascript
These answers should help you practice and understand the core concepts of JavaScript. Let me know
if you need further explanations or have more questions!
ChatGPT can make mistakes. Check important info.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/10