From 1fad7d739803ee86734555c07a7911216bceb566 Mon Sep 17 00:00:00 2001 From: solomon kassa <118729276+Solomonkassa@users.noreply.github.com> Date: Wed, 1 Apr 2026 18:15:54 +0300 Subject: [PATCH] Create README.md --- 00-getting-started/quizzes/README.md | 843 +++++++++++++++++++++++++++ 1 file changed, 843 insertions(+) create mode 100644 00-getting-started/quizzes/README.md diff --git a/00-getting-started/quizzes/README.md b/00-getting-started/quizzes/README.md new file mode 100644 index 0000000..20d9b0c --- /dev/null +++ b/00-getting-started/quizzes/README.md @@ -0,0 +1,843 @@ +# Advanced JavaScript Tutorial + +[](https://opensource.org/licenses/MIT) + +**A comprehensive guide to mastering JavaScript at an expert level.** +This tutorial covers advanced concepts, patterns, performance optimizations, and real-world techniques. Designed for developers with a solid foundation who want to elevate their JavaScript expertise. + +--- + +## Table of Contents + +1. [Prerequisites](#prerequisites) +2. [Core Engine Mechanics](#core-engine-mechanics) + - [Execution Context & Lexical Environment](#execution-context--lexical-environment) + - [Hoisting & Temporal Dead Zone](#hoisting--temporal-dead-zone) + - [Closures in Depth](#closures-in-depth) +3. [Prototypes & Inheritance Revisited](#prototypes--inheritance-revisited) + - [Prototype Chain & Object Creation](#prototype-chain--object-creation) + - [ES6 Classes Under the Hood](#es6-classes-under-the-hood) +4. [The `this` Keyword – Complete Guide](#the-this-keyword--complete-guide) + - [Binding Rules & Explicit Binding](#binding-rules--explicit-binding) + - [Arrow Functions vs Regular Functions](#arrow-functions-vs-regular-functions) +5. [Asynchronous Mastery](#asynchronous-mastery) + - [Event Loop & Task Queues](#event-loop--task-queues) + - [Promises – Advanced Patterns](#promises--advanced-patterns) + - [Async/Await – Best Practices & Error Handling](#asyncawait--best-practices--error-handling) + - [Async Iterators & Generators](#async-iterators--generators) + - [Web Workers & Multithreading](#web-workers--multithreading) +6. [Functional Programming in JavaScript](#functional-programming-in-javascript) + - [Pure Functions & Immutability](#pure-functions--immutability) + - [Currying, Partial Application, and Composition](#currying-partial-application-and-composition) + - [Functional Libraries (Ramda, Lodash/fp)](#functional-libraries-ramda-lodashfp) +7. [Metaprogramming](#metaprogramming) + - [Proxies and Reflect](#proxies-and-reflect) + - [Symbols – Hidden Properties](#symbols--hidden-properties) + - [Decorators (Proposal)](#decorators-proposal) +8. [Design Patterns for Scalable Apps](#design-patterns-for-scalable-apps) + - [Module & Revealing Module](#module--revealing-module) + - [Singleton & Dependency Injection](#singleton--dependency-injection) + - [Observer / Pub-Sub](#observer--pub-sub) + - [Factory & Builder](#factory--builder) + - [Mixin & Composition Over Inheritance](#mixin--composition-over-inheritance) +9. [Memory Management & Garbage Collection](#memory-management--garbage-collection) + - [Understanding Mark-and-Sweep](#understanding-mark-and-sweep) + - [Common Leaks & How to Avoid Them](#common-leaks--how-to-avoid-them) + - [WeakMap, WeakSet, and WeakRef](#weakmap-weakset-and-weakref) +10. [Performance Optimization Techniques](#performance-optimization-techniques) + - [Debouncing & Throttling](#debouncing--throttling) + - [Lazy Loading & Code Splitting](#lazy-loading--code-splitting) + - [Virtual DOM & Rendering Optimizations](#virtual-dom--rendering-optimizations) + - [Profiling with DevTools](#profiling-with-devtools) +11. [Security Best Practices](#security-best-practices) + - [XSS Prevention & Sanitization](#xss-prevention--sanitization) + - [CSRF & CORS](#csrf--cors) + - [Secure Coding in Node.js](#secure-coding-in-nodejs) +12. [Advanced APIs & Features](#advanced-apis--features) + - [Internationalization (Intl)](#internationalization-intl) + - [Web Components](#web-components) + - [Service Workers & PWAs](#service-workers--pwas) + - [Streams API](#streams-api) +13. [Node.js Deep Dive](#nodejs-deep-dive) + - [Event Loop in Node vs Browser](#event-loop-in-node-vs-browser) + - [Cluster & Child Processes](#cluster--child-processes) + - [Streams & Buffers](#streams--buffers) +14. [Testing Strategies](#testing-strategies) + - [Unit, Integration, and E2E Testing](#unit-integration-and-e2e-testing) + - [Mocking, Stubbing, and Spies](#mocking-stubbing-and-spies) + - [Testing Asynchronous Code](#testing-asynchronous-code) +15. [Tooling & Build Chains](#tooling--build-chains) + - [Babel Presets & Plugins](#babel-presets--plugins) + - [Webpack vs Vite – Deep Comparison](#webpack-vs-vite--deep-comparison) + - [ESLint, Prettier, and Husky](#eslint-prettier-and-husky) +16. [TypeScript Integration](#typescript-integration) + - [Advanced Types (Mapped, Conditional, Utility)](#advanced-types-mapped-conditional-utility) + - [Type Guards & Narrowing](#type-guards--narrowing) + - [Migrating JavaScript to TypeScript](#migrating-javascript-to-typescript) +17. [Resources & Further Reading](#resources--further-reading) + +--- + +## Prerequisites + +- Strong knowledge of JavaScript basics (ES6+ syntax, arrays, objects, functions). +- Familiarity with asynchronous patterns (callbacks, promises). +- Experience with Node.js and browser APIs (basic level). +- Understanding of HTML/CSS for frontend examples. + +--- + +## Core Engine Mechanics + +### Execution Context & Lexical Environment + +Every time JavaScript runs, it creates an **execution context** (global, function, or eval). Each context has: +- **Variable Environment**: stores variables and functions declared with `var`, `let`, `const`, and function declarations. +- **Lexical Environment**: used for resolving identifiers; includes outer references (scope chain). +- **`this` binding**. + +Example illustrating scope chain: + +```javascript +let a = 1; // global + +function outer() { + let b = 2; + function inner() { + let c = 3; + console.log(a + b + c); // 6 (looks up through scope chain) + } + inner(); +} +outer(); +``` + +### Hoisting & Temporal Dead Zone + +Hoisting moves declarations to the top. `var` variables are hoisted and initialized with `undefined`. `let`/`const` are hoisted but **not initialized** – accessing them before declaration throws a `ReferenceError` (Temporal Dead Zone). + +```javascript +console.log(x); // undefined +var x = 5; + +console.log(y); // ReferenceError: Cannot access 'y' before initialization +let y = 10; +``` + +Function declarations are fully hoisted; function expressions are not. + +### Closures in Depth + +A closure is a function that retains access to its lexical scope even when executed outside that scope. Closures are the foundation for many patterns: modules, currying, event handlers, and stateful functions. + +```javascript +function createCounter() { + let count = 0; + return { + increment: () => ++count, + decrement: () => --count, + value: () => count + }; +} +const counter = createCounter(); +counter.increment(); // 1 +counter.increment(); // 2 +console.log(counter.value()); // 2 +``` + +**Memory consideration**: Closures keep outer variables alive, which can cause memory leaks if not managed properly. + +--- + +## Prototypes & Inheritance Revisited + +### Prototype Chain & Object Creation + +Every JavaScript object has an internal `[[Prototype]]` property (accessible via `__proto__` or `Object.getPrototypeOf`). The prototype chain is used for property lookup. + +```javascript +const animal = { eats: true }; +const rabbit = { jumps: true }; +rabbit.__proto__ = animal; +console.log(rabbit.eats); // true (inherited) +``` + +**Constructor functions and `new`**: + +```javascript +function Person(name) { + this.name = name; +} +Person.prototype.greet = function() { + return `Hello, ${this.name}`; +}; +const alice = new Person('Alice'); +console.log(alice.greet()); // Hello, Alice +``` + +### ES6 Classes Under the Hood + +Classes are syntactic sugar but introduce subtle differences (e.g., methods are non-enumerable, strict mode enforced). + +```javascript +class Animal { + constructor(name) { + this.name = name; + } + speak() { + console.log(`${this.name} makes a noise.`); + } +} +class Dog extends Animal { + speak() { + console.log(`${this.name} barks.`); + } +} +``` + +Internally, `extends` sets up the prototype chain correctly: `Dog.prototype.__proto__ === Animal.prototype`. + +--- + +## The `this` Keyword – Complete Guide + +`this` is determined at call time. Four binding rules: + +1. **Default binding**: In non-strict mode, `this` is the global object (`window`/`global`). In strict mode, it's `undefined`. +2. **Implicit binding**: When a function is called as a method of an object, `this` is that object. +3. **Explicit binding**: Using `call`, `apply`, or `bind`. +4. **New binding**: When a function is called with `new`, `this` is the newly created object. + +**Arrow functions** do not have their own `this`; they capture `this` from the enclosing lexical scope. + +```javascript +const obj = { + name: 'Obj', + regular: function() { + console.log(this.name); + }, + arrow: () => console.log(this.name) +}; +obj.regular(); // 'Obj' +obj.arrow(); // undefined (lexical this from outer, which might be window) +``` + +**Explicit binding**: + +```javascript +function greet() { + console.log(`Hello, ${this.name}`); +} +const user = { name: 'Bob' }; +greet.call(user); // Hello, Bob +const boundGreet = greet.bind(user); +boundGreet(); // Hello, Bob +``` + +--- + +## Asynchronous Mastery + +### Event Loop & Task Queues + +JavaScript uses an event loop to handle asynchronous operations. The loop processes **macrotasks** (setTimeout, setInterval, I/O) and **microtasks** (promise callbacks, `queueMicrotask`, `MutationObserver`). + +- Microtasks are processed after each macrotask and before rendering. +- Promises use microtask queue. + +```javascript +console.log('start'); +setTimeout(() => console.log('timeout'), 0); +Promise.resolve().then(() => console.log('promise')); +console.log('end'); +// Output: start, end, promise, timeout +``` + +### Promises – Advanced Patterns + +- **Chaining**: Return a promise from `.then()` to flatten. +- **Combining**: `Promise.all`, `Promise.allSettled`, `Promise.race`, `Promise.any`. +- **Cancellation**: Not built-in, but can be emulated with AbortController. + +```javascript +const p1 = Promise.resolve(3); +const p2 = 42; +const p3 = new Promise((resolve, reject) => setTimeout(resolve, 100, 'foo')); +Promise.all([p1, p2, p3]).then(values => console.log(values)); // [3, 42, 'foo'] +``` + +### Async/Await – Best Practices & Error Handling + +`async` functions always return a promise. Use `try/catch` for error handling. + +```javascript +async function fetchData(url) { + try { + const response = await fetch(url); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + return await response.json(); + } catch (err) { + console.error('Fetch failed:', err); + throw err; // rethrow if needed + } +} +``` + +**Parallel execution** with `Promise.all` and `await`: + +```javascript +const [data1, data2] = await Promise.all([fetchData(url1), fetchData(url2)]); +``` + +### Async Iterators & Generators + +`Symbol.asyncIterator` allows asynchronous iteration over data streams. + +```javascript +async function* asyncGenerator() { + let i = 0; + while (i < 3) { + await new Promise(resolve => setTimeout(resolve, 100)); + yield i++; + } +} +(async () => { + for await (const num of asyncGenerator()) { + console.log(num); // 0, 1, 2 (with delays) + } +})(); +``` + +### Web Workers & Multithreading + +Web Workers run scripts in background threads, enabling parallel execution without blocking the UI. + +```javascript +// main.js +const worker = new Worker('worker.js'); +worker.postMessage({ cmd: 'start', data: [1, 2, 3] }); +worker.onmessage = e => console.log('Result:', e.data); + +// worker.js +self.onmessage = e => { + const result = e.data.data.reduce((a, b) => a + b, 0); + self.postMessage(result); +}; +``` + +**Shared Workers** and **Service Workers** extend these concepts for caching, offline, and communication. + +--- + +## Functional Programming in JavaScript + +### Pure Functions & Immutability + +Pure functions have no side effects and return the same output for the same input. Immutability avoids unintended mutations. + +```javascript +// Impure +let counter = 0; +function increment() { return ++counter; } + +// Pure +function add(x, y) { return x + y; } +``` + +### Currying, Partial Application, and Composition + +**Currying** transforms a function with multiple arguments into a sequence of single-argument functions. + +```javascript +const multiply = a => b => a * b; +const double = multiply(2); +console.log(double(5)); // 10 +``` + +**Composition**: combine functions left-to-right or right-to-left. + +```javascript +const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x); +const toUpper = s => s.toUpperCase(); +const exclaim = s => `${s}!`; +const shout = compose(exclaim, toUpper); +console.log(shout('hello')); // HELLO! +``` + +### Functional Libraries (Ramda, Lodash/fp) + +Libraries like Ramda provide auto-curried, data-last functions that play well with composition. + +```javascript +import R from 'ramda'; +const process = R.pipe(R.filter(R.propEq('active', true)), R.map(R.prop('name'))); +const users = [{ name: 'Alice', active: true }, { name: 'Bob', active: false }]; +console.log(process(users)); // ['Alice'] +``` + +--- + +## Metaprogramming + +### Proxies and Reflect + +**Proxy** allows interception of fundamental operations (get, set, delete, etc.). **Reflect** provides methods that mirror those operations. + +```javascript +const target = { message: 'Hello' }; +const handler = { + get(obj, prop) { + if (prop in obj) return obj[prop]; + return 'Property not found'; + }, + set(obj, prop, value) { + if (prop === 'age' && (typeof value !== 'number' || value < 0)) { + throw new TypeError('Age must be a positive number'); + } + obj[prop] = value; + return true; + } +}; +const proxy = new Proxy(target, handler); +console.log(proxy.message); // Hello +console.log(proxy.nonExistent); // Property not found +proxy.age = 30; // works +``` + +### Symbols – Hidden Properties + +Symbols are unique and can be used as property keys to avoid name collisions. + +```javascript +const id = Symbol('id'); +const user = { name: 'John', [id]: 123 }; +console.log(user[id]); // 123 +// Not enumerable in for...in loops +``` + +### Decorators (Proposal) + +Decorators are a Stage 3 proposal for annotating classes and methods. + +```javascript +function readonly(target, key, descriptor) { + descriptor.writable = false; + return descriptor; +} +class Example { + @readonly + method() { console.log('called'); } +} +``` + +--- + +## Design Patterns for Scalable Apps + +### Module & Revealing Module + +Encapsulation using IIFE or ES6 modules. + +```javascript +// ES6 module +export const privateVar = 'secret'; +export function publicMethod() { ... } +``` + +### Singleton & Dependency Injection + +Singleton ensures one instance; DI provides loose coupling. + +```javascript +class Database { + constructor() { + if (!Database.instance) Database.instance = this; + return Database.instance; + } +} +const db1 = new Database(); +const db2 = new Database(); +console.log(db1 === db2); // true +``` + +### Observer / Pub-Sub + +```javascript +class EventBus { + constructor() { this.events = {}; } + on(event, listener) { + (this.events[event] = this.events[event] || []).push(listener); + } + emit(event, data) { + (this.events[event] || []).forEach(fn => fn(data)); + } +} +``` + +### Factory & Builder + +```javascript +class Button { render() { ... } } +class ButtonFactory { + create(type) { + switch(type) { + case 'primary': return new PrimaryButton(); + case 'secondary': return new SecondaryButton(); + default: throw new Error('Unknown type'); + } + } +} +``` + +### Mixin & Composition Over Inheritance + +Mixins allow composing objects from multiple sources. + +```javascript +const canFly = { fly() { console.log('Flying!'); } }; +const canSwim = { swim() { console.log('Swimming!'); } }; +class Duck {} +Object.assign(Duck.prototype, canFly, canSwim); +const duck = new Duck(); +duck.fly(); // Flying! +duck.swim(); // Swimming! +``` + +--- + +## Memory Management & Garbage Collection + +### Understanding Mark-and-Sweep + +Modern JS engines use a **mark-and-sweep** garbage collector. It marks all reachable objects and then sweeps unmarked ones. + +### Common Leaks & How to Avoid Them + +- **Global variables**: Accidental globals are never collected. +- **Forgotten timers or callbacks**: Keep references alive. +- **Detached DOM elements**: Remove event listeners before removing elements. +- **Closures holding large data**: Release references when done. + +```javascript +function leak() { + const bigData = new Array(1000000); + window.addEventListener('resize', () => console.log(bigData[0])); // keeps bigData alive +} +// Fix: remove listener or set bigData = null when not needed +``` + +### WeakMap, WeakSet, and WeakRef + +`WeakMap` and `WeakSet` hold "weak" references to objects, allowing garbage collection if no other references exist. + +```javascript +let obj = { data: 'important' }; +const wm = new WeakMap(); +wm.set(obj, 'secret'); +obj = null; // the entry can be garbage collected +``` + +`WeakRef` (ES2021) allows holding a weak reference to an object, useful for caching. + +--- + +## Performance Optimization Techniques + +### Debouncing & Throttling + +Debounce delays execution until after a pause; throttle limits execution to once per interval. + +```javascript +function debounce(fn, delay) { + let timeout; + return (...args) => { + clearTimeout(timeout); + timeout = setTimeout(() => fn(...args), delay); + }; +} +function throttle(fn, limit) { + let inThrottle; + return (...args) => { + if (!inThrottle) { + fn(...args); + inThrottle = setTimeout(() => (inThrottle = false), limit); + } + }; +} +``` + +### Lazy Loading & Code Splitting + +Use dynamic imports to split code into chunks loaded on demand. + +```javascript +button.addEventListener('click', async () => { + const module = await import('./heavyModule.js'); + module.run(); +}); +``` + +### Virtual DOM & Rendering Optimizations + +Frameworks like React use virtual DOM to minimize actual DOM updates. Understand how to avoid unnecessary re-renders (e.g., `React.memo`, `useMemo`, `useCallback`). + +### Profiling with DevTools + +- **Performance tab**: Record runtime to identify bottlenecks. +- **Memory tab**: Take heap snapshots to detect leaks. +- **Coverage tab**: Find unused code. + +--- + +## Security Best Practices + +### XSS Prevention & Sanitization + +Never trust user input. Escape content before inserting into HTML. + +```javascript +// Bad +element.innerHTML = userInput; + +// Good +element.textContent = userInput; +// or use a sanitizer like DOMPurify +import DOMPurify from 'dompurify'; +element.innerHTML = DOMPurify.sanitize(userInput); +``` + +### CSRF & CORS + +- Use anti-CSRF tokens for state-changing requests. +- Configure CORS properly on the server (allow only trusted origins). + +### Secure Coding in Node.js + +- Avoid `eval` and `child_process.exec` with user input. +- Use `helmet` middleware for Express to set security headers. +- Keep dependencies updated (`npm audit`). + +--- + +## Advanced APIs & Features + +### Internationalization (Intl) + +`Intl` provides formatting for dates, numbers, and strings. + +```javascript +const number = 123456.789; +console.log(new Intl.NumberFormat('de-DE').format(number)); // 123.456,789 +console.log(new Intl.DateTimeFormat('en-US').format(new Date())); // 4/1/2026 +``` + +### Web Components + +Custom elements, Shadow DOM, and HTML templates. + +```javascript +class MyElement extends HTMLElement { + connectedCallback() { + this.attachShadow({ mode: 'open' }); + this.shadowRoot.innerHTML = `
Hello from Shadow DOM!
`; + } +} +customElements.define('my-element', MyElement); +``` + +### Service Workers & PWAs + +Service workers enable offline capabilities, push notifications, and background sync. + +```javascript +// service-worker.js +self.addEventListener('fetch', event => { + event.respondWith(caches.match(event.request).then(response => response || fetch(event.request))); +}); +``` + +### Streams API + +Handle large data progressively using readable, writable, and transform streams. + +```javascript +const stream = new ReadableStream({ + start(controller) { + controller.enqueue('Hello'); + controller.enqueue(' '); + controller.enqueue('World'); + controller.close(); + } +}); +const reader = stream.getReader(); +reader.read().then(({ value, done }) => console.log(value)); // 'Hello' +``` + +--- + +## Node.js Deep Dive + +### Event Loop in Node vs Browser + +Node uses **libuv** for its event loop. Phases: timers, pending callbacks, idle/prepare, poll, check, close callbacks. Microtasks are handled between phases. + +```javascript +setImmediate(() => console.log('setImmediate')); +setTimeout(() => console.log('setTimeout'), 0); +process.nextTick(() => console.log('nextTick')); +// Output: nextTick, setTimeout, setImmediate (order may vary based on timers phase) +``` + +### Cluster & Child Processes + +Use `cluster` to fork multiple workers for load balancing. + +```javascript +const cluster = require('cluster'); +const http = require('http'); +const numCPUs = require('os').cpus().length; + +if (cluster.isMaster) { + for (let i = 0; i < numCPUs; i++) cluster.fork(); + cluster.on('exit', (worker) => console.log(`Worker ${worker.process.pid} died`)); +} else { + http.createServer((req, res) => res.end('Hello')).listen(8000); +} +``` + +### Streams & Buffers + +Streams are efficient for processing large data. Types: Readable, Writable, Duplex, Transform. + +```javascript +const fs = require('fs'); +const readStream = fs.createReadStream('largeFile.txt'); +const writeStream = fs.createWriteStream('output.txt'); +readStream.pipe(writeStream); +``` + +--- + +## Testing Strategies + +### Unit, Integration, and E2E Testing + +- **Unit**: Jest, Mocha +- **Integration**: Supertest (for APIs) +- **E2E**: Cypress, Playwright + +### Mocking, Stubbing, and Spies + +Mock external dependencies to isolate tests. + +```javascript +// Using Jest +jest.mock('./api'); +import { fetchUser } from './api'; +fetchUser.mockResolvedValue({ id: 1 }); +``` + +### Testing Asynchronous Code + +Return promises or use `async/await` in tests. + +```javascript +test('async test', async () => { + const result = await asyncFunction(); + expect(result).toBe('success'); +}); +``` + +--- + +## Tooling & Build Chains + +### Babel Presets & Plugins + +Configure Babel to target specific environments. + +```json +{ + "presets": ["@babel/preset-env", "@babel/preset-react"], + "plugins": ["@babel/plugin-proposal-class-properties"] +} +``` + +### Webpack vs Vite – Deep Comparison + +- **Webpack**: Highly configurable, mature ecosystem. +- **Vite**: Faster dev server (ES modules), simpler config for modern builds. + +### ESLint, Prettier, and Husky + +Enforce code quality and consistency. + +```json +{ + "scripts": { + "lint": "eslint src", + "format": "prettier --write src", + "prepare": "husky install" + } +} +``` + +--- + +## TypeScript Integration + +### Advanced Types (Mapped, Conditional, Utility) + +```typescript +type Partial