Advanced JavaScript
Advanced JavaScript
Welcome to the Advanced JavaScript Guide! This guide is designed for developers who
have a basic understanding of JavaScript and want to delve deeper into advanced
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
1
concepts. We'll cover complex topics, provide code samples, and include quizzes and
exercises to test your knowledge.
Advanced Functions 3
Closures 3
Currying 4
Higher-Order Functions 5
Asynchronous JavaScript 6
Promises 6
Async/Await 7
Object-Oriented Programming 8
Classes 8
Inheritance 9
Encapsulation 10
Prototypes and Inheritance 11
Prototypal Inheritance 11
Prototype Chain 12
Modern JavaScript Features 12
ES6+ Syntax 13
Modules 13
Destructuring 14
Advanced Array Methods 15
Map 15
Filter 15
Reduce 15
Error Handling and Debugging 16
Try...Catch 16
Throwing Errors 16
Debugging Techniques 17
JavaScript Design Patterns 18
Singleton Pattern 18
Module Pattern 19
Observer Pattern 19
Advanced DOM Manipulation 20
Virtual DOM 20
Event Delegation 21
Performance Optimization 21
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
2
Memory Management 21
Code Profiling 22
Conclusion 22
Additional Exercises 22
Advanced Functions
Functions are the building blocks of JavaScript. In this section, we'll explore advanced
concepts like closures, currying, and higher-order functions.
Closures
A closure is a function that has access to its own scope, the outer function's scope, and
the global scope.
Example:
function outerFunction() {
let outerVariable = 'I am outside!';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
Explanation:
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
3
Quiz Question
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
A. 1, 1
B. 1, 2
C. 2, 3
D. Undefined, Undefined
Answer: B. 1, 2
Currying
Example:
function multiply(a) {
return function (b) {
return a * b;
};
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
4
}
Exercise
Solution:
function add(a) {
return function (b) {
return function (c) {
return a + b + c;
};
};
}
console.log(add(1)(2)(3)); // Outputs: 6
Higher-Order Functions
Example:
function greet(name) {
return function (message) {
console.log(`${message}, ${name}!`);
};
}
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
5
const greetJohn = greet('John');
greetJohn('Hello'); // Outputs: Hello, John!
Quiz Question
Asynchronous JavaScript
JavaScript is single-threaded but can handle asynchronous operations through
callbacks, Promises, and async/await.
Promises
Example:
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
6
Exercise
E2: Create a Promise that rejects with an error message after 1 second.
Solution:
Async/Await
Example:
Quiz Question
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
7
Q3: What is the purpose of the await keyword?
Object-Oriented Programming
JavaScript supports object-oriented programming (OOP) through prototypes and
classes.
Classes
Example:
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, ${this.name}!`);
}
}
Exercise
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
8
E3: Create a Car class with properties make, model, and a method displayInfo.
Solution:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
displayInfo() {
console.log(`Car: ${this.make} ${this.model}`);
}
}
Inheritance
Inheritance allows a class to inherit properties and methods from another class.
Example:
class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name} eats.`);
}
}
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
9
class Dog extends Animal {
bark() {
console.log(`${this.name} barks.`);
}
}
Quiz Question
A. extends
B. implements
C. inherits
D. super
Answer: A. extends
Encapsulation
Example:
class BankAccount {
#balance;
constructor(initialBalance) {
this.#balance = initialBalance;
}
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
10
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
Prototypal Inheritance
Every object has a prototype object from which it inherits methods and properties.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
console.log(`Hello, ${this.name}!`);
};
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
11
const bob = new Person('Bob');
bob.greet(); // Outputs: Hello, Bob!
Quiz Question
A. Class-based inheritance
B. Prototypal inheritance
C. Interface-based inheritance
D. Multiple inheritance
Prototype Chain
Objects inherit properties and methods from their prototype, forming a chain.
Example:
console.log(bob.hasOwnProperty('name')); // true
console.log(bob.hasOwnProperty('greet')); // false
console.log('greet' in bob); // true
Explanation:
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
12
ES6+ Syntax
Example:
Modules
Exporting Module:
// math.js
export function add(a, b) {
return a + b;
}
Importing Module:
// main.js
import { add } from './math.js';
console.log(add(2, 3)); // Outputs: 5
Exercise
E4: Create a module that exports a function to calculate the factorial of a number.
Solution:
// factorial.js
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
13
export function factorial(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
// main.js
import { factorial } from './factorial.js';
console.log(factorial(5)); // Outputs: 120
Destructuring
Example:
Quiz Question
A. 1 2
B. 1 3
C. 2 3
D. Undefined
Answer: B. 1 3
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
14
Advanced Array Methods
Advanced methods provide powerful ways to manipulate arrays.
Map
Example:
Filter
Example:
Reduce
Example:
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
15
Exercise
Solution:
Try...Catch
Example:
try {
throw new Error('Something went wrong');
} catch (error) {
console.error(error.message); // Outputs: Something went wrong
}
Throwing Errors
Example:
function divide(a, b) {
if (b === 0) {
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
16
throw new Error('Divide by zero');
}
return a / b;
}
try {
divide(4, 0);
} catch (error) {
console.error(error.message); // Outputs: Divide by zero
}
Quiz Question
try {
console.log('Start');
throw 'An error';
} catch (e) {
console.log('Caught: ' + e);
} finally {
console.log('Finally block');
}
Debugging Techniques
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
17
● Breakpoints: Pause code execution at specific points.
● Console Logging: Output variable values to the console.
● Debugger Keyword: Triggers a breakpoint in the code.
Singleton Pattern
Example:
function createInstance() {
return new Object('I am the instance');
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
},
};
})();
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
18
Module Pattern
Example:
function privateMethod() {
console.log(privateVar);
}
return {
publicMethod: function () {
privateMethod();
},
};
})();
Observer Pattern
Example:
class Subject {
constructor() {
this.observers = [];
}
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
19
subscribe(fn) {
this.observers.push(fn);
}
notify(data) {
this.observers.forEach((fn) => fn(data));
}
}
subject.notify('Hello Observers');
// Outputs:
// Observer 1: Hello Observers
// Observer 2: Hello Observers
Exercise
Virtual DOM
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
20
Event Delegation
Example:
<ul id="parent-list">
<li id="post-1">Item 1</li>
<li id="post-2">Item 2</li>
<li id="post-3">Item 3</li>
</ul>
<script>
document.getElementById('parent-list').addEventListener('click',
function (e) {
if (e.target && e.target.nodeName === 'LI') {
console.log('List item ', e.target.id.replace('post-',
''), ' was clicked.');
}
});
</script>
Performance Optimization
Ensure your applications run smoothly.
Memory Management
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
21
● Nullifying variables that hold large data structures.
Code Profiling
Quiz Question
A. Unreferenced variables
B. Global variables
C. Closures
D. All of the above
Conclusion
You've reached the end of this advanced JavaScript guide. We've covered complex
topics like closures, asynchronous programming, object-oriented principles, design
patterns, and performance optimization. Continue practicing and exploring these
concepts to become a proficient JavaScript developer.
Additional Exercises
1. Closure Exercise: Write a function that maintains a private counter and has
methods to increment, decrement, and get the current value.
2. Async/Await Exercise: Create a function that fetches data from an API using
fetch and async/await.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
22
3. Design Pattern Exercise: Implement the Factory pattern to create different
types of objects based on input.
Learn more HTML, CSS, JavaScript Web Development at https://basescripts.com/ Laurence Svekis
23