diff --git a/QUICKSTART.md b/QUICKSTART.md new file mode 100644 index 00000000..465ae434 --- /dev/null +++ b/QUICKSTART.md @@ -0,0 +1,202 @@ +# Quick Start Guide + +copilot/create-templates-for-concepts +Get started with the 33 JavaScript concepts templates in minutes! šŸš€ + +## What You'll Learn + +This repository helps you master 33 fundamental JavaScript concepts through hands-on practice with ready-to-use templates. + +## Getting Started in 3 Steps + +### Step 1: Clone or Download + +```bash +# Clone the repository +git clone https://github.com/QTechDevelopment/33-js-concepts.git + +# Navigate to the directory +cd 33-js-concepts +``` + +### Step 2: Choose Your Starting Point + +**New to JavaScript?** Start with Concept 1: +```bash +cd templates +node 01-call-stack.js +``` + +**Want to practice a specific concept?** Pick from the list: +- `01-call-stack.js` - Understanding function execution +- `02-primitive-types.js` - JavaScript data types +- `06-scope.js` - Variable scope and closures +- `21-closures.js` - Advanced closure patterns +- `25-promises.js` - Async programming +- ... and 28 more! + +### Step 3: Start Learning + +Open any template in your favorite editor and: + +1. **Read** the concept explanation at the top +2. **Study** the examples provided +3. **Complete** the practice exercises (marked with `// TODO:`) +4. **Experiment** by modifying the code +5. **Run** your changes: `node .js` + +## Example Workflow + +```bash +# Copy a template to work on +cp templates/01-call-stack.js my-practice.js + +# Edit it in your editor +code my-practice.js # or vim, nano, etc. + +# Run it +node my-practice.js + +# Experiment and learn! +``` + +## What's in Each Template? + +Every template includes: + +āœ… **Clear Explanation** - What the concept is and why it matters +āœ… **Multiple Examples** - From basic to advanced usage +āœ… **Practice Exercises** - Hands-on coding challenges +āœ… **Common Pitfalls** - Mistakes to avoid +āœ… **Best Practices** - How to use the concept correctly +āœ… **Notes & Tips** - Key takeaways + +## Learning Path + +### For Beginners (Start Here!) +1. Call Stack (01) +2. Primitive Types (02) +3. Value Types and Reference Types (03) +4. Scope (06) +5. Closures (21) + +### For Intermediate Developers +1. Prototype Inheritance (17) +2. this, call, apply, bind (15) +3. Promises (25) +4. async/await (26) +5. Design Patterns (31) + +### For Advanced Developers +1. Event Loop (09) +2. JavaScript Engines (11) +3. Big O Notation (28) +4. Algorithms (29) +5. Currying and Composition (32) + +## Need More Help? + +- šŸ“– **Detailed Documentation**: See [templates/README.md](./templates/README.md) +- šŸ“š **Articles & Videos**: Check the main [README.md](./README.md) for curated resources +- šŸ› **Issues**: [Open an issue](https://github.com/QTechDevelopment/33-js-concepts/issues) on GitHub +- šŸ’¬ **Discussions**: Join the community discussions + +## Tips for Success + +1. **Practice Daily**: Spend 30 minutes each day on one concept +2. **Type It Out**: Don't copy-paste, type the code yourself +3. **Break Things**: Try to break the code to understand boundaries +4. **Teach Others**: Explain concepts to solidify your understanding +5. **Build Projects**: Apply concepts in real projects + +## Quick Commands Reference + +```bash +# Run any template +node templates/01-call-stack.js + +# List all templates +ls templates/*.js + +# Run multiple templates +for file in templates/0{1..5}*.js; do node "$file"; done + +# Search for a specific concept +grep -r "closures" templates/ +``` + +## What's Next? + +After completing the templates: + +1. ⭐ Star this repository if you find it helpful +2. šŸ”„ Share it with other developers +3. šŸ¤ Contribute improvements (see [CONTRIBUTING.md](./CONTRIBUTING.md)) +4. šŸš€ Build something awesome with your new skills! + + +**Happy Learning!** šŸŽ‰ + +Remember: The best way to learn is by doing. Don't just read the templates - code along, experiment, and most importantly, have fun! +## šŸš€ Get Started in 3 Steps + +### Step 1: Clone the Repository +```bash +git clone https://github.com/leonardomso/33-js-concepts.git +cd 33-js-concepts +``` + +### Step 2: Start the Server +```bash +node server.js +``` + +Or using npm: +```bash +npm start +``` + +### Step 3: Open Your Browser +Navigate to: **http://localhost:3000** + +That's it! šŸŽ‰ + +## šŸŽÆ What You Can Do + +- **Browse Concepts**: Click on any of the 33 JavaScript concepts in the sidebar +- **Search**: Use the search box to quickly find specific topics +- **Write Code**: Modify the example code in the editor +- **Run Code**: Click the "ā–¶ Run Code" button (or press Ctrl/Cmd + Enter) +- **See Results**: View the console output below the editor +- **Reset**: Click "↻ Reset" to restore the original example +- **Clear**: Click "šŸ—‘ļø Clear" to start with a blank editor + +## šŸŽ“ Learning Tips + +1. Start with **Concept #1 (Call Stack)** and work your way through +2. Modify the example code to experiment +3. Try breaking things to understand error messages +4. Create your own examples for each concept +5. Use the console output to debug and learn + +## ⚔ Keyboard Shortcuts + +- `Ctrl/Cmd + Enter` - Run the code +- `Tab` - Insert 4 spaces (in the editor) + +## šŸ”§ Requirements + +- Node.js installed on your system +- A modern web browser (Chrome, Firefox, Safari, Edge) + +## šŸ“± Mobile Friendly + +The interface is fully responsive and works on mobile devices too! + +## šŸ†˜ Need Help? + +- Check the [README.md](README.md) for more detailed information +- Visit the [main repository](https://github.com/leonardomso/33-js-concepts) for resources +- Open an issue if you encounter any problems + +Happy Learning! šŸŽ‰ master diff --git a/README.md b/README.md index 924a02f7..9c2002c5 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,11 @@

Introduction • +copilot/create-templates-for-concepts + Templates • + Quick Start • + Interactive Learning • +master Community • Table of Contents • License @@ -24,6 +29,73 @@ This repository was created with the intention of helping developers master their concepts in JavaScript. It is not a requirement, but a guide for future studies. It is based on an article written by Stephen Curtis and you can read it [here](https://medium.com/@stephenthecurt/33-fundamentals-every-javascript-developer-should-know-13dd720a90d1). +copilot/create-templates-for-concepts +## Templates + +šŸŽÆ **NEW!** We now provide [hands-on templates](./templates) for each of the 33 concepts! + +Each template includes: +- āœ… Clear explanations and examples +- āœ… Practice exercises to test your understanding +- āœ… Common pitfalls to avoid +- āœ… Best practices and tips + +**[šŸ‘‰ Get Started with Templates](./templates/README.md)** + +Perfect for: +- Beginners learning JavaScript fundamentals +- Developers wanting to practice specific concepts +- Anyone preparing for technical interviews +- Teachers looking for structured learning materials + +## šŸŽ® Interactive Learning + +**NEW!** Now you can learn and test JavaScript concepts interactively! We've added a plug-and-play GUI that lets you: + +- šŸ“š Browse all 33 JavaScript concepts in an organized list +- šŸ’» Write and test code in a live editor +- šŸ” Search for specific concepts +- ā–¶ļø Execute JavaScript code directly in your browser +- šŸ“‹ See real-time console output +- šŸŽÆ Learn by doing with pre-loaded examples + +### Getting Started with the Interactive GUI + +1. **Clone this repository:** + ```bash + git clone https://github.com/leonardomso/33-js-concepts.git + cd 33-js-concepts + ``` + +2. **Start the local server:** + ```bash + node server.js + ``` + + Or using npm: + ```bash + npm start + ``` + +3. **Open your browser:** + Navigate to `http://localhost:3000` to start learning! + +### Features + +- ✨ **Clean, Modern Interface**: Beautiful UI with smooth interactions +- šŸ”„ **Live Code Editor**: Write and test JavaScript code instantly +- šŸ“± **Responsive Design**: Works on desktop, tablet, and mobile +- šŸŽØ **Syntax-Friendly**: Comfortable code editing experience +- šŸš€ **Zero Dependencies**: Pure HTML, CSS, and JavaScript - no build tools needed +- ⚔ **Instant Feedback**: See your code results immediately +- šŸŽ“ **Educational Examples**: Each concept comes with working code examples + +### Keyboard Shortcuts + +- `Ctrl/Cmd + Enter` - Run code +- `Tab` - Insert 4 spaces in editor +master + ## Community Feel free to submit a PR by adding a link to your own recaps or reviews. If you want to translate the repo into your native language, please feel free to do so. diff --git a/package.json b/package.json index 588446b6..5cad3689 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,8 @@ }, "homepage": "https://github.com/leonardomso/33#readme", "scripts": { + "start": "node server.js", + "dev": "node server.js", "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { diff --git a/public/app.js b/public/app.js new file mode 100644 index 00000000..9ad83b3f --- /dev/null +++ b/public/app.js @@ -0,0 +1,248 @@ +// State management +let currentConcept = null; +let originalCode = ''; + +// DOM elements +const conceptsList = document.getElementById('conceptsList'); +const conceptTitle = document.getElementById('conceptTitle'); +const conceptDescription = document.getElementById('conceptDescription'); +const codeEditor = document.getElementById('codeEditor'); +const output = document.getElementById('output'); +const searchInput = document.getElementById('searchInput'); +const runBtn = document.getElementById('runBtn'); +const clearBtn = document.getElementById('clearBtn'); +const resetBtn = document.getElementById('resetBtn'); +const clearOutputBtn = document.getElementById('clearOutputBtn'); + +// Initialize the application +function init() { + renderConceptsList(); + setupEventListeners(); + + // Load first concept by default + if (conceptsData.length > 0) { + selectConcept(conceptsData[0].id); + } +} + +// Render the concepts list +function renderConceptsList(filter = '') { + conceptsList.innerHTML = ''; + + const filteredConcepts = conceptsData.filter(concept => + concept.title.toLowerCase().includes(filter.toLowerCase()) + ); + + filteredConcepts.forEach(concept => { + const li = document.createElement('li'); + li.innerHTML = ` + ${concept.id} + ${concept.title} + `; + li.addEventListener('click', () => selectConcept(concept.id)); + + if (currentConcept && currentConcept.id === concept.id) { + li.classList.add('active'); + } + + conceptsList.appendChild(li); + }); +} + +// Select and load a concept +function selectConcept(conceptId) { + const concept = conceptsData.find(c => c.id === conceptId); + if (!concept) return; + + currentConcept = concept; + originalCode = concept.example; + + // Update UI + conceptTitle.textContent = `${concept.id}. ${concept.title}`; + conceptDescription.textContent = concept.description; + codeEditor.value = concept.example; + + // Clear output + clearOutput(); + + // Update active state in list + renderConceptsList(searchInput.value); + + // Scroll to top of content + window.scrollTo({ top: 0, behavior: 'smooth' }); +} + +// Setup event listeners +function setupEventListeners() { + // Search functionality + searchInput.addEventListener('input', (e) => { + renderConceptsList(e.target.value); + }); + + // Run code button + runBtn.addEventListener('click', runCode); + + // Clear editor button + clearBtn.addEventListener('click', () => { + codeEditor.value = ''; + clearOutput(); + }); + + // Reset to original code + resetBtn.addEventListener('click', () => { + if (originalCode) { + codeEditor.value = originalCode; + clearOutput(); + } + }); + + // Clear output button + clearOutputBtn.addEventListener('click', clearOutput); + + // Keyboard shortcuts + document.addEventListener('keydown', (e) => { + // Ctrl/Cmd + Enter to run code + if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { + e.preventDefault(); + runCode(); + } + }); + + // Allow Tab key in textarea + codeEditor.addEventListener('keydown', (e) => { + if (e.key === 'Tab') { + e.preventDefault(); + const start = codeEditor.selectionStart; + const end = codeEditor.selectionEnd; + + codeEditor.value = codeEditor.value.substring(0, start) + + ' ' + + codeEditor.value.substring(end); + + codeEditor.selectionStart = codeEditor.selectionEnd = start + 4; + } + }); +} + +// Run the code in the editor +function runCode() { + const code = codeEditor.value.trim(); + + if (!code) { + addOutput('No code to execute', 'error'); + return; + } + + clearOutput(); + + // Capture console output + const originalConsole = { + log: console.log, + error: console.error, + warn: console.warn, + info: console.info + }; + + const logs = []; + + // Override console methods + console.log = (...args) => { + const message = args.map(arg => formatValue(arg)).join(' '); + logs.push({ type: 'log', message }); + originalConsole.log(...args); + }; + + console.error = (...args) => { + const message = args.map(arg => formatValue(arg)).join(' '); + logs.push({ type: 'error', message }); + originalConsole.error(...args); + }; + + console.warn = (...args) => { + const message = args.map(arg => formatValue(arg)).join(' '); + logs.push({ type: 'warn', message }); + originalConsole.warn(...args); + }; + + console.info = (...args) => { + const message = args.map(arg => formatValue(arg)).join(' '); + logs.push({ type: 'info', message }); + originalConsole.info(...args); + }; + + try { + // Execute the code + const result = eval(code); + + // Display logs + logs.forEach(log => { + addOutput(log.message, log.type); + }); + + // If there's a return value and no logs, display it + if (result !== undefined && logs.length === 0) { + addOutput(`=> ${formatValue(result)}`, 'success'); + } + + // If no output at all + if (logs.length === 0 && result === undefined) { + addOutput('Code executed successfully (no output)', 'success'); + } + + } catch (error) { + addOutput(`Error: ${error.message}`, 'error'); + console.error(error); + } finally { + // Restore console methods + console.log = originalConsole.log; + console.error = originalConsole.error; + console.warn = originalConsole.warn; + console.info = originalConsole.info; + } +} + +// Format values for display +function formatValue(value) { + if (value === null) return 'null'; + if (value === undefined) return 'undefined'; + if (typeof value === 'string') return value; + if (typeof value === 'function') return value.toString(); + if (typeof value === 'symbol') return value.toString(); + + try { + return JSON.stringify(value, null, 2); + } catch (e) { + return String(value); + } +} + +// Add output to the console +function addOutput(message, type = 'log') { + const outputDiv = document.getElementById('output'); + + // Remove empty state + outputDiv.classList.remove('empty'); + + const logEntry = document.createElement('div'); + logEntry.className = `log ${type}`; + logEntry.textContent = message; + + outputDiv.appendChild(logEntry); + + // Auto-scroll to bottom + outputDiv.scrollTop = outputDiv.scrollHeight; +} + +// Clear the output console +function clearOutput() { + output.innerHTML = ''; + output.classList.add('empty'); + output.textContent = 'Run your code to see output here...'; +} + +// Initialize the application when DOM is ready +if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', init); +} else { + init(); +} diff --git a/public/concepts-data.js b/public/concepts-data.js new file mode 100644 index 00000000..13ddfcfb --- /dev/null +++ b/public/concepts-data.js @@ -0,0 +1,1762 @@ +const conceptsData = [ + { + id: 1, + title: "Call Stack", + description: "The call stack is a mechanism that the JavaScript interpreter uses to keep track of function execution. It follows the Last In, First Out (LIFO) principle.", + example: `// Understanding Call Stack +function first() { + console.log('First function'); + second(); + console.log('First function ends'); +} + +function second() { + console.log('Second function'); + third(); + console.log('Second function ends'); +} + +function third() { + console.log('Third function'); +} + +// Call the first function +first(); + +// The call stack executes functions in order: +// 1. first() is pushed to stack +// 2. second() is pushed to stack +// 3. third() is pushed to stack +// 4. third() completes and pops off +// 5. second() completes and pops off +// 6. first() completes and pops off` + }, + { + id: 2, + title: "Primitive Types", + description: "JavaScript has 7 primitive data types: string, number, bigint, boolean, undefined, symbol, and null.", + example: `// Primitive Types in JavaScript +console.log('String:', typeof "Hello"); +console.log('Number:', typeof 42); +console.log('BigInt:', typeof 9007199254740991n); +console.log('Boolean:', typeof true); +console.log('Undefined:', typeof undefined); +console.log('Symbol:', typeof Symbol('id')); +console.log('Null:', typeof null); // Known bug - returns 'object' + +// Primitives are immutable +let str = "hello"; +str[0] = "H"; // This doesn't work +console.log('String after attempt to modify:', str); + +// Creating primitives +const num = 100; +const bool = false; +const sym = Symbol('unique'); +console.log('Created primitives:', num, bool, sym);` + }, + { + id: 3, + title: "Value Types and Reference Types", + description: "Value types (primitives) are copied by value, while reference types (objects, arrays) are copied by reference.", + example: `// Value Types (Primitives) +let a = 10; +let b = a; // Copy by value +b = 20; +console.log('a:', a); // 10 (unchanged) +console.log('b:', b); // 20 + +// Reference Types (Objects) +let obj1 = { name: 'John' }; +let obj2 = obj1; // Copy by reference +obj2.name = 'Jane'; +console.log('obj1.name:', obj1.name); // 'Jane' (changed!) +console.log('obj2.name:', obj2.name); // 'Jane' + +// Arrays are also reference types +let arr1 = [1, 2, 3]; +let arr2 = arr1; +arr2.push(4); +console.log('arr1:', arr1); // [1, 2, 3, 4] +console.log('arr2:', arr2); // [1, 2, 3, 4] + +// To copy by value, use spread operator or other methods +let obj3 = { ...obj1 }; +obj3.name = 'Bob'; +console.log('obj1.name:', obj1.name); // 'Jane' (unchanged) +console.log('obj3.name:', obj3.name); // 'Bob'` + }, + { + id: 4, + title: "Implicit, Explicit, Nominal, Structuring and Duck Typing", + description: "Different ways JavaScript performs type conversion and type checking.", + example: `// Implicit Type Coercion +console.log('5' + 5); // '55' (string concatenation) +console.log('5' - 5); // 0 (numeric subtraction) +console.log(true + 1); // 2 (boolean to number) + +// Explicit Type Conversion +console.log(Number('42')); // 42 +console.log(String(42)); // '42' +console.log(Boolean(0)); // false +console.log(Boolean(1)); // true + +// Duck Typing - "If it walks like a duck..." +function quack(duck) { + if (duck.quack) { + duck.quack(); + } +} + +const realDuck = { + quack: () => console.log('Quack!') +}; + +const fakeDuck = { + quack: () => console.log('I can quack too!') +}; + +quack(realDuck); +quack(fakeDuck);` + }, + { + id: 5, + title: "== vs === vs typeof", + description: "Understanding equality operators and type checking in JavaScript.", + example: `// == (loose equality) vs === (strict equality) +console.log('5' == 5); // true (type coercion) +console.log('5' === 5); // false (no type coercion) + +console.log(null == undefined); // true +console.log(null === undefined); // false + +console.log(0 == false); // true +console.log(0 === false); // false + +// typeof operator +console.log(typeof 42); // 'number' +console.log(typeof 'hello'); // 'string' +console.log(typeof true); // 'boolean' +console.log(typeof undefined); // 'undefined' +console.log(typeof {}); // 'object' +console.log(typeof []); // 'object' (arrays are objects) +console.log(typeof null); // 'object' (historical bug) +console.log(typeof function(){}); // 'function' + +// Best practices +const value = '5'; +if (value === '5') { + console.log('Always use === for comparison'); +}` + }, + { + id: 6, + title: "Function Scope, Block Scope and Lexical Scope", + description: "Understanding different types of scope in JavaScript.", + example: `// Function Scope (var) +function functionScope() { + var x = 10; + if (true) { + var x = 20; // Same variable + console.log('Inside if:', x); // 20 + } + console.log('Outside if:', x); // 20 +} +functionScope(); + +// Block Scope (let and const) +function blockScope() { + let y = 10; + if (true) { + let y = 20; // Different variable + console.log('Inside if:', y); // 20 + } + console.log('Outside if:', y); // 10 +} +blockScope(); + +// Lexical Scope +function outer() { + const outerVar = 'I am outer'; + + function inner() { + console.log(outerVar); // Accesses outer scope + } + + inner(); +} +outer(); + +// Global scope +const globalVar = 'I am global'; +function accessGlobal() { + console.log(globalVar); +} +accessGlobal();` + }, + { + id: 7, + title: "Expression vs Statement", + description: "Expressions produce values, statements perform actions.", + example: `// Expressions - produce a value +const sum = 5 + 10; // Expression +console.log('Expression result:', sum); + +const isTrue = (5 > 3); // Expression +console.log('Boolean expression:', isTrue); + +// Statement - performs an action +if (isTrue) { + console.log('This is a statement'); +} + +// Function Expression +const add = function(a, b) { + return a + b; +}; +console.log('Function expression:', add(5, 3)); + +// Function Statement (Declaration) +function multiply(a, b) { + return a * b; +} +console.log('Function statement:', multiply(5, 3)); + +// IIFE (Immediately Invoked Function Expression) +(function() { + console.log('IIFE executed!'); +})(); + +// Ternary operator (expression) +const result = (10 > 5) ? 'Greater' : 'Smaller'; +console.log('Ternary result:', result);` + }, + { + id: 8, + title: "IIFE, Modules and Namespaces", + description: "Patterns for organizing and encapsulating JavaScript code.", + example: `// IIFE (Immediately Invoked Function Expression) +(function() { + const private = 'I am private'; + console.log('IIFE executed with private variable'); +})(); + +// Module Pattern +const myModule = (function() { + let privateVar = 'I am private'; + + return { + publicMethod: function() { + console.log('Public method accessing:', privateVar); + }, + setPrivate: function(value) { + privateVar = value; + } + }; +})(); + +myModule.publicMethod(); +myModule.setPrivate('New value'); +myModule.publicMethod(); + +// Namespace Pattern +const MyApp = MyApp || {}; +MyApp.utilities = { + formatDate: function(date) { + return date.toISOString(); + }, + log: function(message) { + console.log('[MyApp]', message); + } +}; + +MyApp.utilities.log('Namespace pattern example'); + +// Modern ES6 Module (simulation) +const Calculator = { + add: (a, b) => a + b, + subtract: (a, b) => a - b +}; + +console.log('Calculator.add(10, 5):', Calculator.add(10, 5));` + }, + { + id: 9, + title: "Message Queue and Event Loop", + description: "Understanding how JavaScript handles asynchronous operations.", + example: `// Event Loop demonstration +console.log('1. Start'); + +setTimeout(() => { + console.log('3. Timeout callback (from message queue)'); +}, 0); + +Promise.resolve().then(() => { + console.log('2. Promise callback (from microtask queue)'); +}); + +console.log('4. End'); + +// The output order demonstrates: +// 1. Synchronous code runs first +// 2. Microtasks (Promises) run before macrotasks +// 3. Macrotasks (setTimeout) run last + +// More complex example +console.log('\\n--- Complex Example ---'); +console.log('A'); + +setTimeout(() => console.log('B'), 0); + +Promise.resolve() + .then(() => console.log('C')) + .then(() => console.log('D')); + +console.log('E'); + +// Order: A, E, C, D, B` + }, + { + id: 10, + title: "setTimeout, setInterval and requestAnimationFrame", + description: "Timing functions in JavaScript for delayed and repeated execution.", + example: `// setTimeout - executes once after delay +console.log('setTimeout example:'); +const timeoutId = setTimeout(() => { + console.log('Executed after 1 second'); +}, 1000); + +// You can cancel it +// clearTimeout(timeoutId); + +// setInterval - executes repeatedly +console.log('\\nsetInterval example:'); +let count = 0; +const intervalId = setInterval(() => { + count++; + console.log('Interval execution:', count); + if (count >= 3) { + clearInterval(intervalId); + console.log('Interval stopped'); + } +}, 500); + +// requestAnimationFrame - for smooth animations +console.log('\\nrequestAnimationFrame example:'); +let frame = 0; +function animate() { + frame++; + console.log('Animation frame:', frame); + if (frame < 3) { + requestAnimationFrame(animate); + } +} +// Uncomment to see animation (may be performance intensive) +// requestAnimationFrame(animate); + +console.log('\\nNote: Timers are asynchronous and non-blocking');` + }, + { + id: 11, + title: "JavaScript Engines", + description: "JavaScript engines (like V8, SpiderMonkey) parse and execute JavaScript code.", + example: `// JavaScript Engine optimizations +console.log('JavaScript Engine Concepts:'); + +// 1. JIT (Just-In-Time) Compilation +function hotFunction(n) { + // This function will be optimized if called frequently + return n * n; +} + +console.log('Calling hot function:', hotFunction(5)); + +// 2. Inline Caching +const obj = { x: 1, y: 2 }; +console.log('Property access:', obj.x); // Engine caches property location + +// 3. Hidden Classes +class Point { + constructor(x, y) { + this.x = x; // Properties added in same order + this.y = y; // create same hidden class + } +} + +const p1 = new Point(1, 2); +const p2 = new Point(3, 4); +console.log('Points created with same hidden class'); + +// 4. Garbage Collection +let temp = { data: 'temporary' }; +temp = null; // Now eligible for garbage collection +console.log('Object dereferenced for GC'); + +// Engine-specific features +console.log('\\nEngine info available through:'); +console.log('- Performance API'); +console.log('- Memory management'); +console.log('- Optimization hints');` + }, + { + id: 12, + title: "Bitwise Operators, Type Arrays and Array Buffers", + description: "Low-level operations for binary data manipulation.", + example: `// Bitwise Operators +console.log('Bitwise AND:', 5 & 1); // 0101 & 0001 = 0001 (1) +console.log('Bitwise OR:', 5 | 1); // 0101 | 0001 = 0101 (5) +console.log('Bitwise XOR:', 5 ^ 1); // 0101 ^ 0001 = 0100 (4) +console.log('Bitwise NOT:', ~5); // ~0101 = 1010 (-6) +console.log('Left shift:', 5 << 1); // 0101 << 1 = 1010 (10) +console.log('Right shift:', 5 >> 1); // 0101 >> 1 = 0010 (2) + +// Practical uses +function isEven(n) { + return (n & 1) === 0; +} +console.log('\\n5 is even?', isEven(5)); // false +console.log('8 is even?', isEven(8)); // true + +// Typed Arrays +const buffer = new ArrayBuffer(16); // 16 bytes +const int32View = new Int32Array(buffer); +int32View[0] = 42; +console.log('\\nTyped Array value:', int32View[0]); + +// Different views of same buffer +const int8View = new Int8Array(buffer); +console.log('Int8 view of first byte:', int8View[0]); + +// Use cases: binary data, image processing, WebGL +console.log('\\nTyped Arrays are useful for:'); +console.log('- Binary file handling'); +console.log('- Graphics processing'); +console.log('- Audio processing');` + }, + { + id: 13, + title: "DOM and Layout Trees", + description: "The Document Object Model and how browsers render web pages.", + example: `// DOM Manipulation examples +console.log('DOM Concepts (browser environment):'); + +// DOM Tree structure +console.log('Document structure:'); +console.log('- Document (root)'); +console.log(' - HTML'); +console.log(' - Head'); +console.log(' - Body'); + +// Layout/Render Tree +console.log('\\nLayout Tree includes:'); +console.log('- Visible elements only'); +console.log('- Computed styles'); +console.log('- Position and size'); + +// Critical Rendering Path +console.log('\\nRendering steps:'); +console.log('1. Parse HTML -> DOM Tree'); +console.log('2. Parse CSS -> CSSOM Tree'); +console.log('3. Combine -> Render Tree'); +console.log('4. Layout (reflow)'); +console.log('5. Paint'); +console.log('6. Composite'); + +// Performance tips +console.log('\\nOptimization tips:'); +console.log('- Minimize reflows (batch DOM changes)'); +console.log('- Use document fragments'); +console.log('- Avoid forced synchronous layouts'); +console.log('- Use CSS transforms for animations'); + +// This code works in browser console: +// document.createElement('div') +// document.querySelector('.class') +// element.classList.add('active')` + }, + { + id: 14, + title: "Factories and Classes", + description: "Different patterns for creating objects in JavaScript.", + example: `// Factory Function +function createPerson(name, age) { + return { + name: name, + age: age, + greet: function() { + console.log(\`Hello, I'm \${this.name}\`); + } + }; +} + +const person1 = createPerson('Alice', 30); +person1.greet(); + +// Class (ES6+) +class Person { + constructor(name, age) { + this.name = name; + this.age = age; + } + + greet() { + console.log(\`Hello, I'm \${this.name}\`); + } + + static species() { + return 'Homo Sapiens'; + } +} + +const person2 = new Person('Bob', 25); +person2.greet(); +console.log('Species:', Person.species()); + +// Constructor Function (Old way) +function Animal(name) { + this.name = name; +} + +Animal.prototype.speak = function() { + console.log(\`\${this.name} makes a sound\`); +}; + +const dog = new Animal('Dog'); +dog.speak(); + +console.log('\\nFactory vs Class:'); +console.log('Factory: More flexible, no "new" keyword'); +console.log('Class: Better inheritance, familiar syntax');` + }, + { + id: 15, + title: "this, call, apply and bind", + description: "Understanding the 'this' keyword and methods to control its context.", + example: `// 'this' in different contexts +const obj = { + name: 'Object', + regularFunc: function() { + console.log('Regular function this:', this.name); + }, + arrowFunc: () => { + console.log('Arrow function this:', this.name); + } +}; + +obj.regularFunc(); // 'Object' +obj.arrowFunc(); // undefined (lexical this) + +// call() - invokes function with specific 'this' and arguments +function greet(greeting, punctuation) { + console.log(\`\${greeting}, \${this.name}\${punctuation}\`); +} + +const person = { name: 'Alice' }; +greet.call(person, 'Hello', '!'); + +// apply() - like call but takes array of arguments +greet.apply(person, ['Hi', '?']); + +// bind() - creates new function with bound 'this' +const boundGreet = greet.bind(person); +boundGreet('Hey', '.'); + +// Practical example +const button = { + clicked: 0, + click: function() { + this.clicked++; + console.log('Button clicked:', this.clicked, 'times'); + } +}; + +button.click(); +button.click(); + +// Binding for callbacks +setTimeout(button.click.bind(button), 100);` + }, + { + id: 16, + title: "new, Constructor, instanceof and Instances", + description: "Object creation and type checking in JavaScript.", + example: `// Constructor function +function Car(make, model) { + this.make = make; + this.model = model; +} + +Car.prototype.display = function() { + console.log(\`\${this.make} \${this.model}\`); +}; + +// Using 'new' keyword +const car1 = new Car('Toyota', 'Camry'); +car1.display(); + +// What 'new' does: +// 1. Creates new empty object +// 2. Sets prototype +// 3. Binds 'this' to new object +// 4. Returns the object + +// instanceof operator +console.log('\\ninstanceof checks:'); +console.log('car1 instanceof Car:', car1 instanceof Car); +console.log('car1 instanceof Object:', car1 instanceof Object); +console.log('car1 instanceof Array:', car1 instanceof Array); + +// ES6 Class example +class Animal { + constructor(name) { + this.name = name; + } +} + +const dog = new Animal('Rex'); +console.log('\\ndog instanceof Animal:', dog instanceof Animal); + +// Multiple instances +const car2 = new Car('Honda', 'Civic'); +console.log('\\nMultiple instances:'); +console.log('car1 !== car2:', car1 !== car2); +console.log('Both are Car instances:', + car1 instanceof Car && car2 instanceof Car);` + }, + { + id: 17, + title: "Prototype Inheritance and Prototype Chain", + description: "JavaScript's prototypal inheritance system.", + example: `// Prototype chain +const animal = { + eats: true, + walk() { + console.log('Animal walks'); + } +}; + +const rabbit = Object.create(animal); +rabbit.jumps = true; + +console.log('rabbit.eats:', rabbit.eats); // Inherited +console.log('rabbit.jumps:', rabbit.jumps); // Own property + +// Prototype chain lookup +console.log('\\nPrototype chain:'); +console.log('rabbit -> animal -> Object.prototype -> null'); + +// Constructor and prototype +function Dog(name) { + this.name = name; +} + +Dog.prototype.bark = function() { + console.log(\`\${this.name} barks!\`); +}; + +const dog1 = new Dog('Rex'); +const dog2 = new Dog('Max'); + +dog1.bark(); +dog2.bark(); + +// Shared prototype +console.log('\\nShared prototype:'); +console.log('dog1.bark === dog2.bark:', dog1.bark === dog2.bark); + +// Inheritance with classes +class Animal { + constructor(name) { + this.name = name; + } + speak() { + console.log(\`\${this.name} makes a sound\`); + } +} + +class Cat extends Animal { + speak() { + console.log(\`\${this.name} meows\`); + } +} + +const cat = new Cat('Whiskers'); +cat.speak();` + }, + { + id: 18, + title: "Object.create and Object.assign", + description: "Methods for object creation and property copying.", + example: `// Object.create() - creates object with specified prototype +const personPrototype = { + greet() { + console.log(\`Hello, I'm \${this.name}\`); + } +}; + +const person = Object.create(personPrototype); +person.name = 'Alice'; +person.greet(); + +console.log('\\nPrototype chain:'); +console.log('person.__proto__ === personPrototype:', + Object.getPrototypeOf(person) === personPrototype); + +// Object.assign() - copies properties +const target = { a: 1, b: 2 }; +const source = { b: 3, c: 4 }; + +const result = Object.assign(target, source); +console.log('\\nObject.assign result:', result); +console.log('target modified:', target); + +// Shallow copy +const original = { x: 1, nested: { y: 2 } }; +const copy = Object.assign({}, original); + +copy.x = 10; +copy.nested.y = 20; + +console.log('\\nShallow copy behavior:'); +console.log('original.x:', original.x); // 1 (not changed) +console.log('original.nested.y:', original.nested.y); // 20 (changed!) + +// Merging objects +const obj1 = { a: 1 }; +const obj2 = { b: 2 }; +const obj3 = { c: 3 }; + +const merged = Object.assign({}, obj1, obj2, obj3); +console.log('\\nMerged object:', merged); + +// Modern alternative: spread operator +const spread = { ...obj1, ...obj2, ...obj3 }; +console.log('Spread operator:', spread);` + }, + { + id: 19, + title: "map, reduce, filter", + description: "Essential array methods for functional programming.", + example: `// map() - transforms each element +const numbers = [1, 2, 3, 4, 5]; +const doubled = numbers.map(n => n * 2); +console.log('map - doubled:', doubled); + +const users = [ + { name: 'Alice', age: 25 }, + { name: 'Bob', age: 30 } +]; +const names = users.map(user => user.name); +console.log('map - names:', names); + +// filter() - selects elements that pass test +const evens = numbers.filter(n => n % 2 === 0); +console.log('\\nfilter - evens:', evens); + +const adults = users.filter(user => user.age >= 18); +console.log('filter - adults:', adults); + +// reduce() - reduces to single value +const sum = numbers.reduce((acc, n) => acc + n, 0); +console.log('\\nreduce - sum:', sum); + +const product = numbers.reduce((acc, n) => acc * n, 1); +console.log('reduce - product:', product); + +// Chaining methods +const result = numbers + .filter(n => n > 2) + .map(n => n * 2) + .reduce((acc, n) => acc + n, 0); +console.log('\\nChained result:', result); + +// Real-world example +const cart = [ + { item: 'Book', price: 10, qty: 2 }, + { item: 'Pen', price: 2, qty: 5 } +]; + +const total = cart + .map(item => item.price * item.qty) + .reduce((sum, cost) => sum + cost, 0); +console.log('\\nCart total:', total);` + }, + { + id: 20, + title: "Pure Functions, Side Effects, State Mutation and Event Propagation", + description: "Functional programming concepts and their importance.", + example: `// Pure Function - same input, same output, no side effects +function purePure(x, y) { + return x + y; +} +console.log('Pure function:', purePure(2, 3)); // Always 5 + +// Impure Function - has side effects +let total = 0; +function impure(x) { + total += x; // Modifies external state + return total; +} +console.log('Impure function:', impure(5)); // 5 +console.log('Impure function:', impure(5)); // 10 (different!) + +// Avoiding State Mutation +const original = [1, 2, 3]; + +// Mutating (bad) +// original.push(4); + +// Non-mutating (good) +const newArray = [...original, 4]; +console.log('\\nOriginal unchanged:', original); +console.log('New array:', newArray); + +// Object immutability +const person = { name: 'Alice', age: 25 }; + +// Mutating (bad) +// person.age = 26; + +// Non-mutating (good) +const updatedPerson = { ...person, age: 26 }; +console.log('\\nOriginal person:', person); +console.log('Updated person:', updatedPerson); + +// Benefits of pure functions: +console.log('\\nPure function benefits:'); +console.log('- Easy to test'); +console.log('- Predictable'); +console.log('- Cacheable'); +console.log('- Parallelizable'); +console.log('- Easy to reason about');` + }, + { + id: 21, + title: "Closures", + description: "A closure gives you access to an outer function's scope from an inner function.", + example: `// Basic closure +function outer() { + const message = 'Hello'; + + function inner() { + console.log(message); // Accesses outer scope + } + + return inner; +} + +const closureFunc = outer(); +closureFunc(); // Still has access to 'message' + +// Practical example: Counter +function createCounter() { + let count = 0; // Private variable + + return { + increment() { + count++; + console.log('Count:', count); + }, + decrement() { + count--; + console.log('Count:', count); + }, + getCount() { + return count; + } + }; +} + +const counter = createCounter(); +counter.increment(); // 1 +counter.increment(); // 2 +counter.decrement(); // 1 +console.log('Current count:', counter.getCount()); + +// Function factory +function multiplier(factor) { + return function(number) { + return number * factor; + }; +} + +const double = multiplier(2); +const triple = multiplier(3); + +console.log('\\ndouble(5):', double(5)); // 10 +console.log('triple(5):', triple(5)); // 15 + +// Module pattern with closure +const calculator = (function() { + let result = 0; + + return { + add: (n) => { result += n; return result; }, + subtract: (n) => { result -= n; return result; }, + getResult: () => result + }; +})(); + +console.log('\\nCalculator add(10):', calculator.add(10));` + }, + { + id: 22, + title: "High Order Functions", + description: "Functions that operate on other functions, either by taking them as arguments or returning them.", + example: `// Higher-order function that takes a function +function repeat(n, action) { + for (let i = 0; i < n; i++) { + action(i); + } +} + +console.log('Repeat example:'); +repeat(3, (i) => console.log(\`Iteration \${i}\`)); + +// Higher-order function that returns a function +function greaterThan(n) { + return (m) => m > n; +} + +const greaterThan10 = greaterThan(10); +console.log('\\ngreaterThan10(11):', greaterThan10(11)); // true +console.log('greaterThan10(9):', greaterThan10(9)); // false + +// Built-in higher-order functions +const numbers = [1, 2, 3, 4, 5]; + +const doubled = numbers.map(n => n * 2); +console.log('\\nmap (HOF):', doubled); + +const filtered = numbers.filter(n => n > 2); +console.log('filter (HOF):', filtered); + +// Function composition +function compose(f, g) { + return function(x) { + return f(g(x)); + }; +} + +const add1 = x => x + 1; +const times2 = x => x * 2; + +const add1ThenTimes2 = compose(times2, add1); +console.log('\\nComposed function(5):', add1ThenTimes2(5)); // (5+1)*2 = 12 + +// Practical example: Array sorting +const users = [ + { name: 'Charlie', age: 30 }, + { name: 'Alice', age: 25 }, + { name: 'Bob', age: 35 } +]; + +const sortedByAge = users.sort((a, b) => a.age - b.age); +console.log('\\nSorted by age:', sortedByAge.map(u => u.name));` + }, + { + id: 23, + title: "Recursion", + description: "A function that calls itself until it reaches a base case.", + example: `// Basic recursion: Factorial +function factorial(n) { + // Base case + if (n <= 1) return 1; + // Recursive case + return n * factorial(n - 1); +} + +console.log('factorial(5):', factorial(5)); // 120 + +// Fibonacci sequence +function fibonacci(n) { + if (n <= 1) return n; + return fibonacci(n - 1) + fibonacci(n - 2); +} + +console.log('\\nFibonacci sequence:'); +for (let i = 0; i < 8; i++) { + console.log(\`fib(\${i}) = \${fibonacci(i)}\`); +} + +// Sum of array +function sumArray(arr) { + if (arr.length === 0) return 0; + return arr[0] + sumArray(arr.slice(1)); +} + +console.log('\\nsumArray([1,2,3,4]):', sumArray([1, 2, 3, 4])); + +// Countdown +function countdown(n) { + if (n < 0) return; + console.log(n); + countdown(n - 1); +} + +console.log('\\nCountdown from 5:'); +countdown(5); + +// Nested object traversal +function findValue(obj, key) { + if (obj[key] !== undefined) { + return obj[key]; + } + for (let k in obj) { + if (typeof obj[k] === 'object') { + const result = findValue(obj[k], key); + if (result !== undefined) return result; + } + } + return undefined; +} + +const data = { a: { b: { c: 'found!' } } }; +console.log('\\nNested search:', findValue(data, 'c'));` + }, + { + id: 24, + title: "Collections and Generators", + description: "Advanced iteration patterns including Sets, Maps, and Generator functions.", + example: `// Set - unique values +const set = new Set([1, 2, 3, 3, 4]); +console.log('Set:', Array.from(set)); // [1, 2, 3, 4] + +set.add(5); +set.delete(2); +console.log('Set has 3:', set.has(3)); +console.log('Set size:', set.size); + +// Map - key-value pairs +const map = new Map(); +map.set('name', 'Alice'); +map.set('age', 25); +map.set(1, 'number key'); + +console.log('\\nMap get name:', map.get('name')); +console.log('Map size:', map.size); + +// Iterate over Map +console.log('\\nMap entries:'); +for (let [key, value] of map) { + console.log(\`\${key}: \${value}\`); +} + +// Generator function +function* numberGenerator() { + yield 1; + yield 2; + yield 3; +} + +console.log('\\nGenerator:'); +const gen = numberGenerator(); +console.log(gen.next()); // { value: 1, done: false } +console.log(gen.next()); // { value: 2, done: false } + +// Infinite generator +function* infiniteSequence() { + let i = 0; + while (true) { + yield i++; + } +} + +console.log('\\nInfinite generator (first 5):'); +const infinite = infiniteSequence(); +for (let i = 0; i < 5; i++) { + console.log(infinite.next().value); +} + +// Generator with fibonacci +function* fibonacciGen() { + let [a, b] = [0, 1]; + while (true) { + yield a; + [a, b] = [b, a + b]; + } +} + +console.log('\\nFibonacci generator (first 7):'); +const fib = fibonacciGen(); +for (let i = 0; i < 7; i++) { + console.log(fib.next().value); +}` + }, + { + id: 25, + title: "Promises", + description: "Objects representing the eventual completion or failure of an asynchronous operation.", + example: `// Creating a Promise +const promise = new Promise((resolve, reject) => { + const success = true; + + if (success) { + resolve('Promise resolved!'); + } else { + reject('Promise rejected!'); + } +}); + +promise + .then(result => console.log(result)) + .catch(error => console.log(error)); + +// Simulating async operation +function delay(ms) { + return new Promise(resolve => { + setTimeout(() => resolve(\`Waited \${ms}ms\`), ms); + }); +} + +console.log('\\nAsync delay:'); +delay(1000).then(result => console.log(result)); + +// Chaining promises +Promise.resolve(5) + .then(x => x * 2) + .then(x => x + 3) + .then(x => console.log('Chained result:', x)); // 13 + +// Promise.all - wait for all +const promises = [ + Promise.resolve(1), + Promise.resolve(2), + Promise.resolve(3) +]; + +Promise.all(promises) + .then(results => console.log('\\nPromise.all:', results)); + +// Promise.race - first to complete +Promise.race([ + delay(100).then(() => 'fast'), + delay(200).then(() => 'slow') +]).then(result => console.log('\\nPromise.race:', result)); + +// Error handling +Promise.reject('Error occurred') + .catch(error => console.log('\\nCaught error:', error)) + .finally(() => console.log('Cleanup in finally')); + +console.log('\\nPromises are non-blocking!');` + }, + { + id: 26, + title: "async/await", + description: "Syntactic sugar over Promises for writing asynchronous code that looks synchronous.", + example: `// async function always returns a Promise +async function basicAsync() { + return 'Hello from async'; +} + +basicAsync().then(result => console.log(result)); + +// await pauses execution until Promise resolves +async function waitExample() { + console.log('\\nStart waiting...'); + + const result = await new Promise(resolve => { + setTimeout(() => resolve('Waited!'), 1000); + }); + + console.log(result); + console.log('Done waiting!'); +} + +waitExample(); + +// Error handling with try/catch +async function withErrorHandling() { + try { + const result = await Promise.reject('Error!'); + console.log(result); + } catch (error) { + console.log('\\nCaught error:', error); + } +} + +withErrorHandling(); + +// Multiple awaits +async function sequential() { + console.log('\\nSequential execution:'); + const result1 = await Promise.resolve('First'); + console.log(result1); + const result2 = await Promise.resolve('Second'); + console.log(result2); +} + +sequential(); + +// Parallel execution +async function parallel() { + console.log('\\nParallel execution:'); + const [result1, result2] = await Promise.all([ + Promise.resolve('First'), + Promise.resolve('Second') + ]); + console.log(result1, result2); +} + +parallel(); + +// Real-world pattern +async function fetchUserData(userId) { + try { + // Simulated API call + const user = await Promise.resolve({ + id: userId, + name: 'Alice' + }); + console.log('\\nFetched user:', user); + return user; + } catch (error) { + console.error('Failed to fetch user:', error); + } +} + +fetchUserData(1);` + }, + { + id: 27, + title: "Data Structures", + description: "Fundamental ways to organize and store data efficiently.", + example: `// Array - ordered collection +const array = [1, 2, 3, 4, 5]; +console.log('Array:', array); +console.log('Access by index:', array[2]); + +// Stack - LIFO (Last In, First Out) +class Stack { + constructor() { + this.items = []; + } + push(item) { this.items.push(item); } + pop() { return this.items.pop(); } + peek() { return this.items[this.items.length - 1]; } + isEmpty() { return this.items.length === 0; } +} + +const stack = new Stack(); +stack.push(1); +stack.push(2); +console.log('\\nStack peek:', stack.peek()); // 2 +console.log('Stack pop:', stack.pop()); // 2 + +// Queue - FIFO (First In, First Out) +class Queue { + constructor() { + this.items = []; + } + enqueue(item) { this.items.push(item); } + dequeue() { return this.items.shift(); } + front() { return this.items[0]; } + isEmpty() { return this.items.length === 0; } +} + +const queue = new Queue(); +queue.enqueue('A'); +queue.enqueue('B'); +console.log('\\nQueue front:', queue.front()); // 'A' +console.log('Queue dequeue:', queue.dequeue()); // 'A' + +// Linked List +class Node { + constructor(data) { + this.data = data; + this.next = null; + } +} + +class LinkedList { + constructor() { + this.head = null; + } + append(data) { + const newNode = new Node(data); + if (!this.head) { + this.head = newNode; + return; + } + let current = this.head; + while (current.next) { + current = current.next; + } + current.next = newNode; + } +} + +const list = new LinkedList(); +list.append(1); +list.append(2); +console.log('\\nLinked list created'); + +// Hash Table (Map) +const hashTable = new Map(); +hashTable.set('key1', 'value1'); +console.log('\\nHash table:', hashTable.get('key1'));` + }, + { + id: 28, + title: "Expensive Operation and Big O Notation", + description: "Understanding algorithm complexity and performance.", + example: `// O(1) - Constant time +function constantTime(arr) { + return arr[0]; // Always takes same time +} +console.log('O(1) example:', constantTime([1, 2, 3])); + +// O(n) - Linear time +function linearTime(arr) { + let sum = 0; + for (let i = 0; i < arr.length; i++) { + sum += arr[i]; + } + return sum; +} +console.log('O(n) example:', linearTime([1, 2, 3, 4, 5])); + +// O(n²) - Quadratic time +function quadraticTime(arr) { + const pairs = []; + for (let i = 0; i < arr.length; i++) { + for (let j = 0; j < arr.length; j++) { + pairs.push([arr[i], arr[j]]); + } + } + return pairs.length; +} +console.log('O(n²) example:', quadraticTime([1, 2, 3])); + +// O(log n) - Logarithmic time +function binarySearch(arr, target) { + let left = 0; + let right = arr.length - 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (arr[mid] === target) return mid; + if (arr[mid] < target) left = mid + 1; + else right = mid - 1; + } + return -1; +} +console.log('\\nO(log n) binary search:', + binarySearch([1, 2, 3, 4, 5], 3)); + +// Performance comparison +console.log('\\nComplexity comparison:'); +console.log('O(1) < O(log n) < O(n) < O(n log n) < O(n²) < O(2ⁿ)'); + +// Space complexity +console.log('\\nSpace complexity:'); +console.log('O(1): Constant space'); +console.log('O(n): Linear space (e.g., copying array)'); + +// Practical tips +console.log('\\nOptimization tips:'); +console.log('- Avoid nested loops when possible'); +console.log('- Use hash tables for O(1) lookups'); +console.log('- Use binary search on sorted data');` + }, + { + id: 29, + title: "Algorithms", + description: "Common algorithms and problem-solving techniques.", + example: `// Sorting: Bubble Sort +function bubbleSort(arr) { + const n = arr.length; + for (let i = 0; i < n - 1; i++) { + for (let j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; + } + } + } + return arr; +} + +console.log('Bubble Sort:', bubbleSort([64, 34, 25, 12, 22])); + +// Searching: Binary Search +function binarySearch(arr, target) { + let left = 0; + let right = arr.length - 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (arr[mid] === target) return mid; + if (arr[mid] < target) left = mid + 1; + else right = mid - 1; + } + return -1; +} + +console.log('\\nBinary Search:', + binarySearch([1, 2, 3, 4, 5], 3)); + +// Recursion: Quick Sort +function quickSort(arr) { + if (arr.length <= 1) return arr; + + const pivot = arr[arr.length - 1]; + const left = arr.filter((x, i) => x < pivot && i < arr.length - 1); + const right = arr.filter((x, i) => x >= pivot && i < arr.length - 1); + + return [...quickSort(left), pivot, ...quickSort(right)]; +} + +console.log('Quick Sort:', quickSort([3, 6, 8, 10, 1, 2, 1])); + +// Finding max/min +function findMax(arr) { + return Math.max(...arr); +} + +console.log('\\nFind Max:', findMax([1, 5, 3, 9, 2])); + +// Reverse string +function reverseString(str) { + return str.split('').reverse().join(''); +} + +console.log('Reverse String:', reverseString('hello')); + +// Check palindrome +function isPalindrome(str) { + const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, ''); + return cleaned === cleaned.split('').reverse().join(''); +} + +console.log('\\nIs Palindrome "racecar":', isPalindrome('racecar')); + +// FizzBuzz +function fizzBuzz(n) { + for (let i = 1; i <= n; i++) { + if (i % 15 === 0) console.log('FizzBuzz'); + else if (i % 3 === 0) console.log('Fizz'); + else if (i % 5 === 0) console.log('Buzz'); + else console.log(i); + } +} + +console.log('\\nFizzBuzz to 15:'); +fizzBuzz(15);` + }, + { + id: 30, + title: "Inheritance, Polymorphism and Code Reuse", + description: "Object-oriented programming principles in JavaScript.", + example: `// Inheritance with classes +class Animal { + constructor(name) { + this.name = name; + } + + speak() { + console.log(\`\${this.name} makes a sound\`); + } +} + +class Dog extends Animal { + constructor(name, breed) { + super(name); // Call parent constructor + this.breed = breed; + } + + speak() { + console.log(\`\${this.name} barks\`); + } + + fetch() { + console.log(\`\${this.name} fetches the ball\`); + } +} + +const dog = new Dog('Rex', 'German Shepherd'); +dog.speak(); // Polymorphism - overridden method +dog.fetch(); + +// Polymorphism example +class Cat extends Animal { + speak() { + console.log(\`\${this.name} meows\`); + } +} + +const animals = [ + new Dog('Rex', 'Husky'), + new Cat('Whiskers'), + new Animal('Generic') +]; + +console.log('\\nPolymorphism in action:'); +animals.forEach(animal => animal.speak()); + +// Composition over inheritance +const canEat = { + eat() { + console.log(\`\${this.name} is eating\`); + } +}; + +const canWalk = { + walk() { + console.log(\`\${this.name} is walking\`); + } +}; + +function createPerson(name) { + return Object.assign( + { name }, + canEat, + canWalk + ); +} + +const person = createPerson('Alice'); +person.eat(); +person.walk(); + +console.log('\\nOOP Principles:'); +console.log('- Inheritance: reuse parent class code'); +console.log('- Polymorphism: same interface, different implementations'); +console.log('- Encapsulation: hide internal details'); +console.log('- Abstraction: hide complexity');` + }, + { + id: 31, + title: "Design Patterns", + description: "Common solutions to recurring problems in software design.", + example: `// 1. Singleton Pattern +const Singleton = (function() { + let instance; + + function createInstance() { + return { data: 'I am the instance' }; + } + + return { + getInstance: function() { + if (!instance) { + instance = createInstance(); + } + return instance; + } + }; +})(); + +const instance1 = Singleton.getInstance(); +const instance2 = Singleton.getInstance(); +console.log('Singleton:', instance1 === instance2); // true + +// 2. Factory Pattern +function createVehicle(type) { + if (type === 'car') { + return { type: 'car', wheels: 4 }; + } else if (type === 'bike') { + return { type: 'bike', wheels: 2 }; + } +} + +const car = createVehicle('car'); +console.log('\\nFactory created:', car); + +// 3. Observer Pattern +class Subject { + constructor() { + this.observers = []; + } + + subscribe(observer) { + this.observers.push(observer); + } + + notify(data) { + this.observers.forEach(observer => observer(data)); + } +} + +const subject = new Subject(); +subject.subscribe(data => console.log('Observer 1:', data)); +subject.subscribe(data => console.log('Observer 2:', data)); +subject.notify('Event occurred!'); + +// 4. Module Pattern +const Calculator = (function() { + let result = 0; + + return { + add: (x) => { result += x; return result; }, + subtract: (x) => { result -= x; return result; }, + getResult: () => result + }; +})(); + +console.log('\\nModule pattern:', Calculator.add(10)); + +// 5. Decorator Pattern +function Coffee() { + this.cost = function() { return 5; }; +} + +function withMilk(coffee) { + const cost = coffee.cost(); + coffee.cost = function() { return cost + 2; }; +} + +const coffee = new Coffee(); +console.log('\\nCoffee cost:', coffee.cost()); +withMilk(coffee); +console.log('Coffee with milk:', coffee.cost());` + }, + { + id: 32, + title: "Partial Applications, Currying, Compose and Pipe", + description: "Advanced functional programming techniques.", + example: `// Currying - transforms f(a,b,c) into f(a)(b)(c) +function curry(fn) { + return function curried(...args) { + if (args.length >= fn.length) { + return fn.apply(this, args); + } + return function(...args2) { + return curried.apply(this, args.concat(args2)); + } + }; +} + +const add = (a, b, c) => a + b + c; +const curriedAdd = curry(add); + +console.log('Currying:'); +console.log('curriedAdd(1)(2)(3):', curriedAdd(1)(2)(3)); +console.log('curriedAdd(1, 2)(3):', curriedAdd(1, 2)(3)); + +// Partial Application +function multiply(a, b, c) { + return a * b * c; +} + +function partial(fn, ...fixedArgs) { + return function(...remainingArgs) { + return fn(...fixedArgs, ...remainingArgs); + }; +} + +const double = partial(multiply, 2); +console.log('\\nPartial: double(3, 4):', double(3, 4)); // 2 * 3 * 4 = 24 + +// Compose - right to left +const compose = (...fns) => x => + fns.reduceRight((acc, fn) => fn(acc), x); + +const add1 = x => x + 1; +const times2 = x => x * 2; +const square = x => x * x; + +const composed = compose(square, times2, add1); +console.log('\\nCompose (5+1)*2²:', composed(5)); // ((5+1)*2)² = 144 + +// Pipe - left to right +const pipe = (...fns) => x => + fns.reduce((acc, fn) => fn(acc), x); + +const piped = pipe(add1, times2, square); +console.log('Pipe ((5+1)*2)²:', piped(5)); // ((5+1)*2)² = 144 + +// Real-world example +const data = [1, 2, 3, 4, 5]; + +const filterEven = arr => arr.filter(x => x % 2 === 0); +const sumArray = arr => arr.reduce((a, b) => a + b, 0); +const multiplyBy3 = x => x * 3; + +const process = pipe( + filterEven, + sumArray, + multiplyBy3 +); + +console.log('\\nPipeline result:', process(data)); // (2+4)*3 = 18` + }, + { + id: 33, + title: "Clean Code", + description: "Best practices for writing readable, maintainable code.", + example: `// 1. Meaningful Names +// Bad +const d = new Date(); +// Good +const currentDate = new Date(); + +// 2. Function should do one thing +// Bad +function processUserData(user) { + // validates, saves, and sends email +} +// Good +function validateUser(user) { /* ... */ } +function saveUser(user) { /* ... */ } +function sendWelcomeEmail(user) { /* ... */ } + +// 3. Small functions +function calculateTotal(items) { + return items.reduce((sum, item) => sum + item.price, 0); +} +console.log('Small function example:', + calculateTotal([{price: 10}, {price: 20}])); + +// 4. DRY (Don't Repeat Yourself) +function greet(name) { + return \`Hello, \${name}!\`; +} +console.log('\\n' + greet('Alice')); +console.log(greet('Bob')); + +// 5. Comments for why, not what +// Why: Performance optimization for large datasets +const useOptimizedAlgorithm = true; + +// 6. Error handling +function divide(a, b) { + if (b === 0) { + throw new Error('Division by zero'); + } + return a / b; +} + +try { + console.log('\\nDivision:', divide(10, 2)); +} catch (error) { + console.error('Error:', error.message); +} + +// 7. Consistent formatting +const user = { + name: 'Alice', + age: 25, + email: 'alice@example.com' +}; + +// 8. Single Responsibility +class User { + constructor(name) { + this.name = name; + } + + getName() { + return this.name; + } +} + +console.log('\\nClean code principles:'); +console.log('- Meaningful names'); +console.log('- Single responsibility'); +console.log('- DRY principle'); +console.log('- Small focused functions'); +console.log('- Proper error handling'); +console.log('- Clear and simple');` + } +]; diff --git a/public/index.html b/public/index.html new file mode 100644 index 00000000..c2e176a6 --- /dev/null +++ b/public/index.html @@ -0,0 +1,65 @@ + + + + + + 33 JavaScript Concepts - Interactive Learning + + + +

+
+

šŸš€ 33 JavaScript Concepts

+

Learn and Test JavaScript Concepts Interactively

+
+
+ +
+
+ + +
+
+

Select a concept to get started

+

+
+ +
+
+

šŸ’» Code Editor

+
+ + + +
+
+ +
+ +
+
+

šŸ“‹ Console Output

+ +
+
+
+
+
+
+ +
+
+

Built with ā¤ļø for JavaScript learners | View on GitHub

+
+
+ + + + + diff --git a/public/styles.css b/public/styles.css new file mode 100644 index 00000000..e9369b9c --- /dev/null +++ b/public/styles.css @@ -0,0 +1,357 @@ +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +:root { + --primary-color: #0066cc; + --secondary-color: #f0f0f0; + --text-color: #333; + --border-color: #ddd; + --success-color: #28a745; + --error-color: #dc3545; + --bg-dark: #1e1e1e; + --sidebar-width: 300px; +} + +body { + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; + color: var(--text-color); + line-height: 1.6; + background: #f5f5f5; +} + +.container { + max-width: 1400px; + margin: 0 auto; + padding: 0 20px; +} + +header { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + color: white; + padding: 2rem 0; + box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); +} + +header h1 { + font-size: 2.5rem; + margin-bottom: 0.5rem; +} + +header p { + font-size: 1.2rem; + opacity: 0.9; +} + +main { + padding: 2rem 0; +} + +.layout { + display: flex; + gap: 2rem; + min-height: calc(100vh - 250px); +} + +.sidebar { + width: var(--sidebar-width); + background: white; + border-radius: 8px; + padding: 1.5rem; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); + height: fit-content; + position: sticky; + top: 2rem; +} + +.sidebar h2 { + font-size: 1.3rem; + margin-bottom: 1rem; + color: var(--primary-color); +} + +.search-box { + margin-bottom: 1rem; +} + +.search-box input { + width: 100%; + padding: 0.75rem; + border: 2px solid var(--border-color); + border-radius: 6px; + font-size: 0.95rem; + transition: border-color 0.3s; +} + +.search-box input:focus { + outline: none; + border-color: var(--primary-color); +} + +.concepts-list { + list-style: none; + max-height: 600px; + overflow-y: auto; +} + +.concepts-list li { + padding: 0.75rem; + margin-bottom: 0.5rem; + border-radius: 6px; + cursor: pointer; + transition: all 0.3s; + border-left: 3px solid transparent; +} + +.concepts-list li:hover { + background: var(--secondary-color); + border-left-color: var(--primary-color); +} + +.concepts-list li.active { + background: #e3f2fd; + border-left-color: var(--primary-color); + font-weight: 600; +} + +.concepts-list li .concept-number { + display: inline-block; + width: 30px; + height: 30px; + line-height: 30px; + text-align: center; + background: var(--primary-color); + color: white; + border-radius: 50%; + margin-right: 0.5rem; + font-size: 0.85rem; + font-weight: bold; +} + +.content { + flex: 1; + background: white; + border-radius: 8px; + padding: 2rem; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); +} + +.concept-info { + margin-bottom: 2rem; + padding-bottom: 1.5rem; + border-bottom: 2px solid var(--secondary-color); +} + +.concept-info h2 { + color: var(--primary-color); + margin-bottom: 1rem; + font-size: 1.8rem; +} + +.concept-info p { + color: #666; + font-size: 1.05rem; + line-height: 1.8; +} + +.editor-section { + margin-bottom: 2rem; +} + +.editor-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 1rem; +} + +.editor-header h3 { + font-size: 1.3rem; + color: var(--text-color); +} + +.editor-actions { + display: flex; + gap: 0.5rem; +} + +.code-editor { + width: 100%; + min-height: 300px; + padding: 1rem; + font-family: 'Courier New', Consolas, Monaco, monospace; + font-size: 0.95rem; + border: 2px solid var(--border-color); + border-radius: 6px; + background: #f8f9fa; + resize: vertical; + line-height: 1.5; +} + +.code-editor:focus { + outline: none; + border-color: var(--primary-color); +} + +.output-section { + margin-top: 2rem; +} + +.output-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 1rem; +} + +.output-header h3 { + font-size: 1.3rem; + color: var(--text-color); +} + +.output { + background: var(--bg-dark); + color: #f8f8f2; + padding: 1rem; + border-radius: 6px; + min-height: 150px; + max-height: 400px; + overflow-y: auto; + font-family: 'Courier New', Consolas, Monaco, monospace; + font-size: 0.9rem; + line-height: 1.6; + white-space: pre-wrap; + word-wrap: break-word; +} + +.output.empty { + display: flex; + align-items: center; + justify-content: center; + color: #666; + font-style: italic; +} + +.output .log { + margin-bottom: 0.5rem; + padding: 0.25rem 0; +} + +.output .log.error { + color: #ff6b6b; +} + +.output .log.success { + color: #51cf66; +} + +.output .log.info { + color: #74c0fc; +} + +.btn { + padding: 0.6rem 1.2rem; + border: none; + border-radius: 6px; + font-size: 0.95rem; + cursor: pointer; + transition: all 0.3s; + font-weight: 600; +} + +.btn-primary { + background: var(--primary-color); + color: white; +} + +.btn-primary:hover { + background: #0052a3; + transform: translateY(-2px); + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); +} + +.btn-secondary { + background: var(--secondary-color); + color: var(--text-color); +} + +.btn-secondary:hover { + background: #e0e0e0; +} + +.btn-small { + padding: 0.4rem 0.8rem; + font-size: 0.85rem; + background: #dc3545; + color: white; +} + +.btn-small:hover { + background: #c82333; +} + +footer { + background: #2c3e50; + color: white; + padding: 1.5rem 0; + text-align: center; + margin-top: 2rem; +} + +footer a { + color: #74c0fc; + text-decoration: none; +} + +footer a:hover { + text-decoration: underline; +} + +/* Scrollbar styles */ +.concepts-list::-webkit-scrollbar, +.output::-webkit-scrollbar { + width: 8px; +} + +.concepts-list::-webkit-scrollbar-track, +.output::-webkit-scrollbar-track { + background: #f1f1f1; + border-radius: 4px; +} + +.concepts-list::-webkit-scrollbar-thumb, +.output::-webkit-scrollbar-thumb { + background: #888; + border-radius: 4px; +} + +.concepts-list::-webkit-scrollbar-thumb:hover, +.output::-webkit-scrollbar-thumb:hover { + background: #555; +} + +/* Responsive design */ +@media (max-width: 968px) { + .layout { + flex-direction: column; + } + + .sidebar { + width: 100%; + position: static; + } + + .concepts-list { + max-height: 400px; + } + + header h1 { + font-size: 2rem; + } + + header p { + font-size: 1rem; + } +} diff --git a/server.js b/server.js new file mode 100644 index 00000000..61961f8b --- /dev/null +++ b/server.js @@ -0,0 +1,61 @@ +const http = require('http'); +const fs = require('fs'); +const path = require('path'); + +const PORT = process.env.PORT || 3000; + +// MIME types for different file extensions +const mimeTypes = { + '.html': 'text/html', + '.css': 'text/css', + '.js': 'text/javascript', + '.json': 'application/json', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.gif': 'image/gif', + '.svg': 'image/svg+xml', + '.ico': 'image/x-icon' +}; + +// Create HTTP server +const server = http.createServer((req, res) => { + // Default to index.html for root path + let filePath = req.url === '/' ? '/index.html' : req.url; + filePath = path.join(__dirname, 'public', filePath); + + // Get file extension + const extname = path.extname(filePath); + const contentType = mimeTypes[extname] || 'text/plain'; + + // Read and serve the file + fs.readFile(filePath, (err, content) => { + if (err) { + if (err.code === 'ENOENT') { + // File not found + res.writeHead(404, { 'Content-Type': 'text/html' }); + res.end('

404 - File Not Found

', 'utf-8'); + } else { + // Server error + res.writeHead(500); + res.end(`Server Error: ${err.code}`, 'utf-8'); + } + } else { + // Success + res.writeHead(200, { 'Content-Type': contentType }); + res.end(content, 'utf-8'); + } + }); +}); + +// Start the server +server.listen(PORT, () => { + console.log('='.repeat(60)); + console.log('šŸš€ 33 JavaScript Concepts - Interactive Learning Platform'); + console.log('='.repeat(60)); + console.log(`\nāœ… Server is running on:`); + console.log(` - Local: http://localhost:${PORT}`); + console.log(` - Network: http://127.0.0.1:${PORT}`); + console.log(`\nšŸ“š Ready to explore JavaScript concepts!`); + console.log(`\nāŒØļø Press Ctrl+C to stop the server\n`); + console.log('='.repeat(60)); +}); diff --git a/templates/01-call-stack.js b/templates/01-call-stack.js new file mode 100644 index 00000000..f51e8134 --- /dev/null +++ b/templates/01-call-stack.js @@ -0,0 +1,150 @@ +/** + * ========================================== + * CONCEPT 1: CALL STACK + * ========================================== + * + * The call stack is a mechanism that the JavaScript interpreter uses to keep track + * of function execution. It follows the Last In, First Out (LIFO) principle. + * + * Key Points: + * - Functions are added to the stack when called + * - Functions are removed from the stack when they return + * - Stack overflow occurs when the stack size limit is exceeded + */ + +// ========================================== +// EXAMPLE 1: Basic Call Stack +// ========================================== + +function firstFunction() { + console.log('First function called'); + secondFunction(); + console.log('First function finished'); +} + +function secondFunction() { + console.log('Second function called'); + thirdFunction(); + console.log('Second function finished'); +} + +function thirdFunction() { + console.log('Third function called'); +} + +// Uncomment to run: +// firstFunction(); + +// Call Stack Order: +// 1. firstFunction() is pushed +// 2. secondFunction() is pushed +// 3. thirdFunction() is pushed +// 4. thirdFunction() is popped +// 5. secondFunction() is popped +// 6. firstFunction() is popped + +// ========================================== +// EXAMPLE 2: Stack Overflow +// ========================================== + +function recursiveFunction() { + // This will cause a stack overflow error + // recursiveFunction(); +} + +// Uncomment to see stack overflow (don't run this): +// recursiveFunction(); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Trace the call stack + * Determine the order of console.log outputs + */ +function exercise1() { + console.log('1'); + exercise1Helper(); + console.log('4'); +} + +function exercise1Helper() { + console.log('2'); + console.log('3'); +} + +// TODO: Before running, predict the output order +// Uncomment to test: +// exercise1(); + +/** + * Exercise 2: Create a function that demonstrates call stack depth + * Write a function that counts how deep the call stack can go before overflow + */ +function countStackDepth() { + let depth = 0; + + function recurse() { + depth++; + try { + recurse(); + } catch (e) { + console.log(`Stack depth reached: ${depth}`); + } + } + + // TODO: Implement this safely + // Hint: Use try-catch to prevent actual overflow +} + +/** + * Exercise 3: Debug the call stack + * The following function has a logical error. Use your understanding + * of the call stack to identify and fix it. + */ +function calculate(num) { + if (num <= 0) return 0; + return num + calculate(num - 1); +} + +// TODO: Test this function and verify it works correctly +// Uncomment to test: +// console.log(calculate(5)); // Should return 15 (5+4+3+2+1) + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: Infinite recursion + * Always ensure recursive functions have a proper base case + */ +function badRecursion(n) { + // Missing base case! + // return badRecursion(n - 1); +} + +/** + * Pitfall 2: Forgetting function execution context + * Remember that each function call creates a new execution context + */ +function pitfall2Example() { + let counter = 0; + + function increment() { + counter++; + } + + increment(); + increment(); + console.log(counter); // What will this output? +} + +// ========================================== +// NOTES +// ========================================== +// - The call stack has a size limit (varies by browser/environment) +// - Stack overflow errors occur when limit is exceeded +// - Debugging tools show the current call stack +// - Understanding the call stack helps debug complex code diff --git a/templates/02-primitive-types.js b/templates/02-primitive-types.js new file mode 100644 index 00000000..24546d67 --- /dev/null +++ b/templates/02-primitive-types.js @@ -0,0 +1,227 @@ +/** + * ========================================== + * CONCEPT 2: PRIMITIVE TYPES + * ========================================== + * + * JavaScript has 7 primitive data types: + * 1. String + * 2. Number + * 3. BigInt + * 4. Boolean + * 5. Undefined + * 6. Null + * 7. Symbol + * + * Primitives are immutable and stored by value. + */ + +// ========================================== +// EXAMPLE 1: String +// ========================================== + +const stringExample = 'Hello, World!'; +const stringWithTemplate = `Template literal: ${stringExample}`; + +console.log(typeof stringExample); // 'string' + +// Strings are immutable +let str = 'hello'; +str[0] = 'H'; // This doesn't change the string +console.log(str); // Still 'hello' + +// ========================================== +// EXAMPLE 2: Number +// ========================================== + +const integer = 42; +const float = 3.14; +const negative = -10; +const infinity = Infinity; +const notANumber = NaN; + +console.log(typeof integer); // 'number' +console.log(typeof NaN); // 'number' (surprising!) + +// Number precision +console.log(0.1 + 0.2); // 0.30000000000000004 +console.log(0.1 + 0.2 === 0.3); // false! + +// ========================================== +// EXAMPLE 3: BigInt +// ========================================== + +const bigInt = 9007199254740991n; +const anotherBigInt = BigInt(9007199254740991); + +console.log(typeof bigInt); // 'bigint' + +// BigInt operations +const result = bigInt + 1n; +// Note: Cannot mix BigInt with regular numbers +// const mixed = bigInt + 1; // TypeError! + +// ========================================== +// EXAMPLE 4: Boolean +// ========================================== + +const isTrue = true; +const isFalse = false; + +console.log(typeof isTrue); // 'boolean' + +// Truthy and Falsy values +// Falsy: false, 0, '', null, undefined, NaN +// Everything else is truthy + +if (0) { + console.log('This will not run'); +} + +if ('hello') { + console.log('This will run'); +} + +// ========================================== +// EXAMPLE 5: Undefined +// ========================================== + +let undefinedVariable; +console.log(undefinedVariable); // undefined +console.log(typeof undefinedVariable); // 'undefined' + +function noReturn() { + // No return statement +} +console.log(noReturn()); // undefined + +// ========================================== +// EXAMPLE 6: Null +// ========================================== + +const nullValue = null; +console.log(nullValue); // null +console.log(typeof nullValue); // 'object' (this is a known bug in JavaScript!) + +// null vs undefined +console.log(null == undefined); // true +console.log(null === undefined); // false + +// ========================================== +// EXAMPLE 7: Symbol +// ========================================== + +const symbol1 = Symbol('description'); +const symbol2 = Symbol('description'); + +console.log(typeof symbol1); // 'symbol' +console.log(symbol1 === symbol2); // false (each symbol is unique) + +// Symbols are often used as unique property keys +const obj = { + [symbol1]: 'value1' +}; + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Identify the type + * For each value, write what typeof will return + */ +function exercise1() { + const values = [ + 42, + 'hello', + true, + undefined, + null, + Symbol('test'), + 10n, + NaN, + Infinity + ]; + + // TODO: Use typeof to check each value + // Which ones might surprise you? +} + +/** + * Exercise 2: Type coercion + * Predict the output of these comparisons + */ +function exercise2() { + console.log(1 == '1'); // ? + console.log(1 === '1'); // ? + console.log(true == 1); // ? + console.log(false == 0); // ? + console.log(null == undefined); // ? + console.log(null === undefined); // ? +} + +/** + * Exercise 3: Immutability + * Demonstrate that primitives are immutable + */ +function exercise3() { + let num = 5; + let numCopy = num; + numCopy = 10; + + // TODO: What is the value of num? + console.log(num); // ? + + // TODO: Explain why this behavior occurs +} + +/** + * Exercise 4: Create a function that checks if a value is a primitive + */ +function isPrimitive(value) { + // TODO: Implement this function + // Return true if value is a primitive, false otherwise + // Hint: typeof and checking for null +} + +// Test cases: +// console.log(isPrimitive(42)); // true +// console.log(isPrimitive('hello')); // true +// console.log(isPrimitive({})); // false +// console.log(isPrimitive([])); // false +// console.log(isPrimitive(null)); // true + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: typeof null returns 'object' + */ +console.log(typeof null); // 'object' - This is a bug that can't be fixed! + +/** + * Pitfall 2: NaN is not equal to itself + */ +console.log(NaN === NaN); // false +console.log(Number.isNaN(NaN)); // Use this instead + +/** + * Pitfall 3: Floating point arithmetic + */ +console.log(0.1 + 0.2 === 0.3); // false +// Use methods like toFixed() or compare with epsilon + +/** + * Pitfall 4: String numbers + */ +console.log('5' + 3); // '53' (concatenation) +console.log('5' - 3); // 2 (coercion to number) + +// ========================================== +// NOTES +// ========================================== +// - Primitives are immutable (cannot be changed) +// - Primitives are compared by value +// - Objects (including arrays and functions) are NOT primitives +// - typeof is useful but has quirks (null, NaN) +// - Use === for strict equality checks diff --git a/templates/03-value-reference-types.js b/templates/03-value-reference-types.js new file mode 100644 index 00000000..37fc5c33 --- /dev/null +++ b/templates/03-value-reference-types.js @@ -0,0 +1,272 @@ +/** + * ========================================== + * CONCEPT 3: VALUE TYPES AND REFERENCE TYPES + * ========================================== + * + * Value Types (Primitives): Stored directly, copied by value + * Reference Types (Objects): Stored as reference, copied by reference + * + * Key Difference: + * - Primitives: Each variable holds its own copy + * - Objects: Variables hold references to the same object + */ + +// ========================================== +// EXAMPLE 1: Value Types (Primitives) +// ========================================== + +let a = 10; +let b = a; // b gets a COPY of a's value + +b = 20; + +console.log(a); // 10 (unchanged) +console.log(b); // 20 + +// Each variable has its own independent value + +// ========================================== +// EXAMPLE 2: Reference Types (Objects) +// ========================================== + +let obj1 = { name: 'Alice' }; +let obj2 = obj1; // obj2 gets a REFERENCE to the same object + +obj2.name = 'Bob'; + +console.log(obj1.name); // 'Bob' (changed!) +console.log(obj2.name); // 'Bob' + +// Both variables point to the same object in memory + +// ========================================== +// EXAMPLE 3: Arrays (Reference Type) +// ========================================== + +let arr1 = [1, 2, 3]; +let arr2 = arr1; // Reference copy + +arr2.push(4); + +console.log(arr1); // [1, 2, 3, 4] (modified!) +console.log(arr2); // [1, 2, 3, 4] + +// ========================================== +// EXAMPLE 4: Copying Objects (Shallow Copy) +// ========================================== + +// Using spread operator +let original = { x: 1, y: 2 }; +let copy = { ...original }; + +copy.x = 10; + +console.log(original.x); // 1 (unchanged) +console.log(copy.x); // 10 + +// Using Object.assign +let anotherCopy = Object.assign({}, original); + +// ========================================== +// EXAMPLE 5: Deep vs Shallow Copy +// ========================================== + +// Shallow copy - nested objects still share references +let nested = { + a: 1, + b: { + c: 2 + } +}; + +let shallowCopy = { ...nested }; +shallowCopy.b.c = 20; + +console.log(nested.b.c); // 20 (changed!) + +// Deep copy - all levels are independent +let deepCopy = JSON.parse(JSON.stringify(nested)); +deepCopy.b.c = 100; + +console.log(nested.b.c); // 20 (unchanged) + +// ========================================== +// EXAMPLE 6: Function Parameters +// ========================================== + +// Primitives passed by value +function modifyPrimitive(num) { + num = 100; +} + +let x = 10; +modifyPrimitive(x); +console.log(x); // 10 (unchanged) + +// Objects passed by reference +function modifyObject(obj) { + obj.value = 100; +} + +let myObj = { value: 10 }; +modifyObject(myObj); +console.log(myObj.value); // 100 (changed!) + +// But reassigning the parameter doesn't affect the original +function reassignObject(obj) { + obj = { value: 100 }; +} + +let anotherObj = { value: 10 }; +reassignObject(anotherObj); +console.log(anotherObj.value); // 10 (unchanged!) + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Predict the output + */ +function exercise1() { + let a = { x: 1 }; + let b = a; + let c = { x: 1 }; + + console.log(a === b); // ? + console.log(a === c); // ? + + // TODO: Explain why these comparisons produce these results +} + +/** + * Exercise 2: Fix the bug + * The following function should not modify the original array + */ +function doubleValues(arr) { + // BUG: This modifies the original array + for (let i = 0; i < arr.length; i++) { + arr[i] = arr[i] * 2; + } + return arr; +} + +// TODO: Fix this function to not modify the original +function doubleValuesFixed(arr) { + // Your code here +} + +// Test: +// let numbers = [1, 2, 3]; +// let doubled = doubleValuesFixed(numbers); +// console.log(numbers); // Should still be [1, 2, 3] +// console.log(doubled); // Should be [2, 4, 6] + +/** + * Exercise 3: Implement a deep clone function + */ +function deepClone(obj) { + // TODO: Implement deep cloning without JSON.parse/stringify + // Handle objects, arrays, and primitives + // Bonus: Handle dates, functions, and circular references +} + +/** + * Exercise 4: Understanding equality + */ +function exercise4() { + const obj1 = { a: 1 }; + const obj2 = { a: 1 }; + const obj3 = obj1; + + // TODO: Predict and test these comparisons + console.log(obj1 == obj2); // ? + console.log(obj1 === obj2); // ? + console.log(obj1 === obj3); // ? + + // How would you check if two objects have the same properties? +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: Thinking spread operator creates deep copies + */ +let nested1 = { a: 1, b: { c: 2 } }; +let nested2 = { ...nested1 }; +nested2.b.c = 20; +console.log(nested1.b.c); // 20 - nested objects still share reference! + +/** + * Pitfall 2: Comparing objects by value instead of reference + */ +console.log({ a: 1 } === { a: 1 }); // false - different references +console.log([1, 2] === [1, 2]); // false - different references + +/** + * Pitfall 3: JSON.parse/stringify limitations + */ +let objWithFunction = { + func: function() { return 1; }, + date: new Date(), + undef: undefined +}; +let cloned = JSON.parse(JSON.stringify(objWithFunction)); +console.log(cloned); +// Lost: function, undefined +// Changed: Date becomes string + +/** + * Pitfall 4: Modifying function parameters + */ +function addProperty(obj) { + obj.newProp = 'added'; // Modifies the original! +} + +let myObject = { prop: 'value' }; +addProperty(myObject); +console.log(myObject); // { prop: 'value', newProp: 'added' } + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. Use const for object references to prevent reassignment + */ +const config = { setting: true }; +// config = {}; // Error! +config.setting = false; // OK - modifying properties is allowed + +/** + * 2. Create copies when you need to modify + */ +function processArray(arr) { + const copy = [...arr]; + // Work with copy instead of original + return copy; +} + +/** + * 3. Use Object.freeze for immutability + */ +const immutable = Object.freeze({ value: 1 }); +// immutable.value = 2; // Silently fails in non-strict mode + +/** + * 4. Consider using libraries for deep cloning + */ +// lodash: _.cloneDeep(obj) +// Or structuredClone() in modern JavaScript + +// ========================================== +// NOTES +// ========================================== +// - Primitives are compared by value +// - Objects are compared by reference +// - Understand the difference to avoid bugs +// - Be careful with nested objects +// - Use appropriate cloning techniques +// - Consider immutability for complex applications diff --git a/templates/04-type-coercion.js b/templates/04-type-coercion.js new file mode 100644 index 00000000..2c837bc4 --- /dev/null +++ b/templates/04-type-coercion.js @@ -0,0 +1,313 @@ +/** + * ========================================== + * CONCEPT 4: IMPLICIT, EXPLICIT, NOMINAL, STRUCTURING AND DUCK TYPING + * ========================================== + * + * Type Coercion and Type Systems in JavaScript: + * - Implicit Coercion: Automatic type conversion + * - Explicit Coercion: Manual type conversion + * - Nominal Typing: Types by name (not used in JS) + * - Structural Typing: Types by structure (TypeScript) + * - Duck Typing: "If it walks like a duck..." + */ + +// ========================================== +// EXAMPLE 1: Implicit Coercion +// ========================================== + +// String coercion +console.log('5' + 3); // '53' - number to string +console.log('5' - 3); // 2 - string to number +console.log('5' * '2'); // 10 - both strings to numbers + +// Boolean coercion +if ('hello') { + console.log('Truthy string'); // Runs +} + +if (0) { + console.log('This will not run'); // 0 is falsy +} + +// Equality coercion +console.log(5 == '5'); // true - type coercion +console.log(5 === '5'); // false - no coercion + +// ========================================== +// EXAMPLE 2: Explicit Coercion +// ========================================== + +// To String +const num = 123; +const str1 = String(num); // '123' +const str2 = num.toString(); // '123' +const str3 = '' + num; // '123' (implicit but intentional) + +// To Number +const str = '123'; +const num1 = Number(str); // 123 +const num2 = parseInt(str); // 123 +const num3 = parseFloat('123.45'); // 123.45 +const num4 = +str; // 123 (unary plus operator) + +// To Boolean +const bool1 = Boolean(1); // true +const bool2 = Boolean(0); // false +const bool3 = Boolean('hello'); // true +const bool4 = !!('hello'); // true (double negation) + +// ========================================== +// EXAMPLE 3: Falsy Values +// ========================================== + +const falsyValues = [ + false, + 0, + -0, + 0n, + '', + null, + undefined, + NaN +]; + +falsyValues.forEach(value => { + if (!value) { + console.log(`${value} is falsy`); + } +}); + +// Everything else is truthy! +console.log(!![]); // true (empty array is truthy!) +console.log(!!{}); // true (empty object is truthy!) +console.log(!!'false'); // true (string 'false' is truthy!) + +// ========================================== +// EXAMPLE 4: Duck Typing +// ========================================== + +// "If it walks like a duck and quacks like a duck..." +function processAnimal(animal) { + if (typeof animal.speak === 'function') { + animal.speak(); + } +} + +const dog = { + name: 'Buddy', + speak() { + console.log('Woof!'); + } +}; + +const cat = { + name: 'Whiskers', + speak() { + console.log('Meow!'); + } +}; + +processAnimal(dog); // Works! +processAnimal(cat); // Works! + +// Duck typing: We don't care about the type, just the interface + +// ========================================== +// EXAMPLE 5: Type Checking Patterns +// ========================================== + +// typeof operator +console.log(typeof 42); // 'number' +console.log(typeof 'hello'); // 'string' +console.log(typeof true); // 'boolean' +console.log(typeof undefined); // 'undefined' +console.log(typeof null); // 'object' (quirk!) +console.log(typeof {}); // 'object' +console.log(typeof []); // 'object' (quirk!) +console.log(typeof function() {}); // 'function' + +// instanceof operator +console.log([] instanceof Array); // true +console.log({} instanceof Object); // true +console.log(new Date() instanceof Date); // true + +// Array.isArray() +console.log(Array.isArray([])); // true +console.log(Array.isArray({})); // false + +// Object.prototype.toString +function getType(value) { + return Object.prototype.toString.call(value).slice(8, -1); +} + +console.log(getType([])); // 'Array' +console.log(getType({})); // 'Object' +console.log(getType(null)); // 'Null' + +// ========================================== +// EXAMPLE 6: Strict vs Loose Equality +// ========================================== + +// Loose equality (==) with type coercion +console.log(1 == '1'); // true +console.log(true == 1); // true +console.log(false == 0); // true +console.log(null == undefined); // true +console.log('' == 0); // true + +// Strict equality (===) without coercion +console.log(1 === '1'); // false +console.log(true === 1); // false +console.log(false === 0); // false +console.log(null === undefined); // false +console.log('' === 0); // false + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Predict the output + */ +function exercise1() { + console.log('10' + 20); // ? + console.log('10' - 20); // ? + console.log(true + true); // ? + console.log(true + false); // ? + console.log('5' * '5'); // ? + console.log('hello' - 1); // ? +} + +/** + * Exercise 2: Create a strict type checking function + */ +function strictTypeCheck(value, type) { + // TODO: Implement strict type checking + // Should return true if value is exactly of the given type + // Handle: 'string', 'number', 'boolean', 'object', 'array', 'null', 'undefined' +} + +// Test cases: +// console.log(strictTypeCheck('hello', 'string')); // true +// console.log(strictTypeCheck(123, 'number')); // true +// console.log(strictTypeCheck([], 'array')); // true +// console.log(strictTypeCheck(null, 'null')); // true +// console.log(strictTypeCheck({}, 'object')); // true + +/** + * Exercise 3: Implement a safe coercion function + */ +function safeToNumber(value) { + // TODO: Convert value to number safely + // Return null if conversion is not valid + // Handle edge cases like NaN, Infinity +} + +/** + * Exercise 4: Duck typing exercise + * Create a function that works with any object that has certain methods + */ +function createLogger(output) { + // TODO: output should have a write() method + // If it doesn't, throw an error + // Use duck typing to check +} + +// Test with different "ducks": +// const consoleOutput = { write: (msg) => console.log(msg) }; +// const arrayOutput = { write: (msg) => arr.push(msg) }; + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: Truthy/Falsy confusion + */ +const users = []; +if (users) { + console.log('Has users'); // Runs even though array is empty! +} + +// Better: +if (users.length > 0) { + console.log('Has users'); +} + +/** + * Pitfall 2: NaN comparisons + */ +console.log(NaN == NaN); // false +console.log(NaN === NaN); // false +// Use Number.isNaN() instead + +/** + * Pitfall 3: Object to primitive coercion + */ +console.log([1, 2] + [3, 4]); // '1,23,4' (both converted to strings) +console.log({} + []); // Different results in different contexts! + +/** + * Pitfall 4: String concatenation vs addition + */ +console.log(1 + 2 + '3'); // '33' +console.log('1' + 2 + 3); // '123' + +/** + * Pitfall 5: typeof null + */ +console.log(typeof null); // 'object' - historical bug +// Check null explicitly: value === null + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. Use === instead of == + */ +// Always use strict equality unless you have a specific reason not to + +/** + * 2. Be explicit about type conversions + */ +const explicitConversion = String(123); // Good +const implicitConversion = 123 + ''; // Unclear intent + +/** + * 3. Check types before operations + */ +function safeDivide(a, b) { + if (typeof a !== 'number' || typeof b !== 'number') { + throw new TypeError('Both arguments must be numbers'); + } + if (b === 0) { + throw new Error('Cannot divide by zero'); + } + return a / b; +} + +/** + * 4. Use TypeScript for larger projects + */ +// TypeScript provides static type checking and prevents many coercion issues + +/** + * 5. Validate user input + */ +function processUserInput(input) { + // Always validate and sanitize user input + const normalized = String(input).trim(); + // ... process normalized input +} + +// ========================================== +// NOTES +// ========================================== +// - JavaScript is dynamically typed +// - Type coercion can be helpful but also dangerous +// - Use === for equality checks +// - Understand truthy/falsy values +// - Duck typing is common in JavaScript +// - Consider TypeScript for type safety +// - Always validate external data diff --git a/templates/05-equality-comparison.js b/templates/05-equality-comparison.js new file mode 100644 index 00000000..1ac7b67e --- /dev/null +++ b/templates/05-equality-comparison.js @@ -0,0 +1,248 @@ +/** + * ========================================== + * CONCEPT 5: == vs === vs typeof + * ========================================== + * + * Understanding equality operators and type checking: + * - == (loose equality): performs type coercion + * - === (strict equality): no type coercion + * - typeof: returns string describing the type + */ + +// ========================================== +// EXAMPLE 1: Loose Equality (==) +// ========================================== + +console.log(5 == 5); // true +console.log(5 == '5'); // true (type coercion) +console.log(true == 1); // true +console.log(false == 0); // true +console.log(null == undefined); // true +console.log('' == 0); // true +console.log([1] == 1); // true + +// ========================================== +// EXAMPLE 2: Strict Equality (===) +// ========================================== + +console.log(5 === 5); // true +console.log(5 === '5'); // false (different types) +console.log(true === 1); // false +console.log(false === 0); // false +console.log(null === undefined); // false +console.log('' === 0); // false + +// ========================================== +// EXAMPLE 3: typeof Operator +// ========================================== + +// Primitives +console.log(typeof 42); // 'number' +console.log(typeof 'hello'); // 'string' +console.log(typeof true); // 'boolean' +console.log(typeof undefined); // 'undefined' +console.log(typeof Symbol('id')); // 'symbol' +console.log(typeof 123n); // 'bigint' + +// Objects +console.log(typeof {}); // 'object' +console.log(typeof []); // 'object' (arrays are objects) +console.log(typeof null); // 'object' (known bug!) +console.log(typeof function() {}); // 'function' + +// ========================================== +// EXAMPLE 4: Special Cases +// ========================================== + +// NaN +console.log(NaN == NaN); // false +console.log(NaN === NaN); // false +console.log(Object.is(NaN, NaN)); // true +console.log(Number.isNaN(NaN)); // true (recommended) + +// -0 vs +0 +console.log(-0 == 0); // true +console.log(-0 === 0); // true +console.log(Object.is(-0, 0)); // false + +// null and undefined +console.log(null == undefined); // true +console.log(null === undefined); // false +console.log(typeof null); // 'object' +console.log(typeof undefined); // 'undefined' + +// ========================================== +// EXAMPLE 5: Object.is() +// ========================================== + +// Object.is() is similar to === but handles special cases better +console.log(Object.is(5, 5)); // true +console.log(Object.is(5, '5')); // false +console.log(Object.is(NaN, NaN)); // true (unlike ===) +console.log(Object.is(-0, 0)); // false (unlike ===) + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Predict the results + */ +function exercise1() { + console.log('0' == 0); // ? + console.log('0' === 0); // ? + console.log([] == false); // ? + console.log([] === false); // ? + console.log('' == false); // ? + console.log('' === false); // ? +} + +/** + * Exercise 2: Create a type checking utility + */ +function getDetailedType(value) { + // TODO: Return accurate type for any value + // Handle: primitives, null, arrays, objects, functions, dates, regex, etc. +} + +// Test cases: +// console.log(getDetailedType([])); // 'array' +// console.log(getDetailedType(null)); // 'null' +// console.log(getDetailedType(new Date())); // 'date' + +/** + * Exercise 3: Implement a safe equality check + */ +function safeEquals(a, b, strict = true) { + // TODO: Implement equality check with option for strict or loose + // Handle NaN specially (NaN should equal NaN) +} + +/** + * Exercise 4: Find the bugs + */ +function hasBugs() { + // Bug 1 + if (typeof value == 'undefined') { // value is not defined! + console.log('Value is undefined'); + } + + // Bug 2 + const arr = []; + if (arr) { // Always truthy, even if empty + console.log('Array has items'); + } + + // Bug 3 + const num = '123'; + if (typeof num == 'number') { // This is false! + console.log('Is a number'); + } + + // TODO: Fix these bugs +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: Array and object equality + */ +console.log([] == []); // false +console.log([] === []); // false +console.log({} == {}); // false +// Objects compare by reference, not value! + +/** + * Pitfall 2: typeof null + */ +if (typeof value === 'object') { + // This includes null! + // value.property; // Could throw error if value is null +} + +// Better: +if (value !== null && typeof value === 'object') { + // Safe to access properties +} + +/** + * Pitfall 3: typeof arrays + */ +const arr = []; +console.log(typeof arr); // 'object', not 'array' +// Use Array.isArray(arr) instead + +/** + * Pitfall 4: Truthy/falsy with == + */ +console.log('false' == false); // false +console.log('false' == true); // false +// String 'false' is truthy! + +/** + * Pitfall 5: Comparing with true/false + */ +const value = 'hello'; +if (value == true) { // false - don't do this! + console.log('Not what you expect'); +} + +// Better: +if (value) { // Use truthiness + console.log('Value is truthy'); +} + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. Always use === unless you have a specific reason + */ +const goodComparison = (x === y); +const badComparison = (x == y); // Avoid + +/** + * 2. Check for null and undefined explicitly + */ +if (value === null || value === undefined) { + // Handle null/undefined +} +// Or use nullish coalescing +const result = value ?? 'default'; + +/** + * 3. Use appropriate type checking methods + */ +Array.isArray(value); // For arrays +Number.isNaN(value); // For NaN +value === null; // For null +typeof value === 'string'; // For strings + +/** + * 4. Be careful with typeof + */ +function safeTypeCheck(value) { + if (value === null) return 'null'; + if (Array.isArray(value)) return 'array'; + return typeof value; +} + +/** + * 5. Use Object.is() for special cases + */ +function areValuesSame(a, b) { + return Object.is(a, b); // Handles NaN and -0/+0 correctly +} + +// ========================================== +// NOTES +// ========================================== +// - Prefer === over == +// - typeof has quirks (null, arrays) +// - Objects compare by reference +// - NaN is special (not equal to itself) +// - Use appropriate checking methods for each type +// - Object.is() is most precise but less common diff --git a/templates/06-scope.js b/templates/06-scope.js new file mode 100644 index 00000000..9deb9ed6 --- /dev/null +++ b/templates/06-scope.js @@ -0,0 +1,322 @@ +/** + * ========================================== + * CONCEPT 6: FUNCTION SCOPE, BLOCK SCOPE, AND LEXICAL SCOPE + * ========================================== + * + * Scope determines the accessibility of variables: + * - Function Scope: var (visible within function) + * - Block Scope: let/const (visible within block {}) + * - Lexical Scope: Inner functions access outer variables + */ + +// ========================================== +// EXAMPLE 1: Function Scope (var) +// ========================================== + +function functionScopeExample() { + var x = 10; + + if (true) { + var x = 20; // Same variable! var is function-scoped + console.log(x); // 20 + } + + console.log(x); // 20 (modified in if block) +} + +// var is hoisted to the top of the function +function hoistingExample() { + console.log(x); // undefined (not ReferenceError!) + var x = 5; + console.log(x); // 5 +} + +// ========================================== +// EXAMPLE 2: Block Scope (let/const) +// ========================================== + +function blockScopeExample() { + let x = 10; + + if (true) { + let x = 20; // Different variable! let is block-scoped + console.log(x); // 20 + } + + console.log(x); // 10 (unchanged) +} + +// let/const in loops +for (let i = 0; i < 3; i++) { + // i is scoped to this loop + console.log(i); +} +// console.log(i); // ReferenceError: i is not defined + +// Temporal Dead Zone (TDZ) +function temporalDeadZone() { + // console.log(x); // ReferenceError (can't access before declaration) + let x = 5; + console.log(x); // 5 +} + +// ========================================== +// EXAMPLE 3: Lexical Scope +// ========================================== + +function outer() { + const outerVar = 'I am outer'; + + function inner() { + // inner() can access outerVar due to lexical scoping + console.log(outerVar); + + const innerVar = 'I am inner'; + + function deepInner() { + // deepInner() can access both outerVar and innerVar + console.log(outerVar); + console.log(innerVar); + } + + deepInner(); + } + + inner(); + // console.log(innerVar); // ReferenceError: can't access inner scope +} + +// ========================================== +// EXAMPLE 4: Global Scope +// ========================================== + +// Global variable (avoid in production code!) +var globalVar = 'I am global'; + +function accessGlobal() { + console.log(globalVar); // Accessible +} + +// Without var/let/const, creates global variable +function createAccidentalGlobal() { + // accidentalGlobal = 'Oops!'; // Creates global (don't do this!) +} + +// ========================================== +// EXAMPLE 5: Closures and Scope +// ========================================== + +function createCounter() { + let count = 0; // Private variable due to scope + + return { + increment() { + count++; + return count; + }, + decrement() { + count--; + return count; + }, + getCount() { + return count; + } + }; +} + +const counter = createCounter(); +console.log(counter.increment()); // 1 +console.log(counter.increment()); // 2 +console.log(counter.getCount()); // 2 +// console.log(count); // ReferenceError: count is private + +// ========================================== +// EXAMPLE 6: Classic var Loop Problem +// ========================================== + +// Problem with var +function varLoopProblem() { + for (var i = 0; i < 3; i++) { + setTimeout(() => { + console.log(i); // Prints 3, 3, 3 + }, 100); + } +} + +// Solution with let +function letLoopSolution() { + for (let i = 0; i < 3; i++) { + setTimeout(() => { + console.log(i); // Prints 0, 1, 2 + }, 100); + } +} + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Predict the output + */ +function exercise1() { + var a = 1; + let b = 2; + const c = 3; + + if (true) { + var a = 4; + let b = 5; + const c = 6; + console.log(a, b, c); // ? + } + + console.log(a, b, c); // ? +} + +/** + * Exercise 2: Fix the scope issue + */ +function exercise2() { + // This function has scope issues + // TODO: Fix it so each button logs its correct index + + const buttons = ['Button 1', 'Button 2', 'Button 3']; + + for (var i = 0; i < buttons.length; i++) { + setTimeout(() => { + console.log(`Clicked ${buttons[i]}`); + }, 100); + } +} + +/** + * Exercise 3: Create a private variable pattern + */ +function createBankAccount(initialBalance) { + // TODO: Create private balance variable + // TODO: Return methods to deposit, withdraw, and check balance + // TODO: Balance should not be directly accessible +} + +// Test: +// const account = createBankAccount(100); +// account.deposit(50); +// account.withdraw(25); +// console.log(account.getBalance()); // 125 +// console.log(account.balance); // undefined (private) + +/** + * Exercise 4: Understand hoisting + */ +function exercise4() { + // TODO: Explain what happens in each case + + // Case 1 + console.log(x); + var x = 5; + + // Case 2 + // console.log(y); + // let y = 5; + + // Case 3 + test(); + function test() { + console.log('Function hoisting works!'); + } +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: Accidentally creating globals + */ +function pitfall1() { + // x = 5; // Creates global variable (no var/let/const) + // Always use var/let/const +} + +/** + * Pitfall 2: var in loops + */ +function pitfall2() { + for (var i = 0; i < 5; i++) { + // All iterations share the same i + } + console.log(i); // 5 - i is still accessible! +} + +/** + * Pitfall 3: Temporal Dead Zone confusion + */ +function pitfall3() { + // This is in TDZ + // console.log(x); // ReferenceError + let x = 5; +} + +/** + * Pitfall 4: Thinking const means immutable + */ +const obj = { value: 1 }; +obj.value = 2; // This works! const prevents reassignment, not mutation + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. Use const by default, let when needed, avoid var + */ +const constantValue = 42; // Can't be reassigned +let variableValue = 10; // Can be reassigned +// var oldStyle = 5; // Avoid + +/** + * 2. Declare variables at the top of their scope + */ +function goodPractice() { + const x = 1; + let y = 2; + + // Use x and y... +} + +/** + * 3. Keep scope as narrow as possible + */ +function narrowScope() { + // Only declare variables where they're needed + + if (condition) { + const temp = calculate(); // Only exists in this block + process(temp); + } +} + +/** + * 4. Use IIFE for isolation (older pattern) + */ +(function() { + // Variables here don't pollute global scope + const privateVar = 'private'; +})(); + +/** + * 5. Use modules for better scope management + */ +// In modern JavaScript, use ES6 modules +// Each module has its own scope + +// ========================================== +// NOTES +// ========================================== +// - var: function-scoped, hoisted +// - let/const: block-scoped, TDZ +// - Prefer const > let > never var +// - Lexical scope allows closures +// - Scope chains: inner → outer → global +// - Use modules for namespace management diff --git a/templates/07-expression-vs-statement.js b/templates/07-expression-vs-statement.js new file mode 100644 index 00000000..86bf9a9d --- /dev/null +++ b/templates/07-expression-vs-statement.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 07: EXPRESSION VS STATEMENT + * ========================================== + * + * Understanding the difference between expressions and statements in JavaScript + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of expression vs statement'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/08-iife-modules-namespaces.js b/templates/08-iife-modules-namespaces.js new file mode 100644 index 00000000..5048892c --- /dev/null +++ b/templates/08-iife-modules-namespaces.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 08: IIFE, MODULES AND NAMESPACES + * ========================================== + * + * Immediately Invoked Function Expressions, ES6 Modules, and namespace patterns + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of iife, modules and namespaces'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/09-event-loop.js b/templates/09-event-loop.js new file mode 100644 index 00000000..76510556 --- /dev/null +++ b/templates/09-event-loop.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 09: MESSAGE QUEUE AND EVENT LOOP + * ========================================== + * + * Understanding asynchronous JavaScript execution model + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of message queue and event loop'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/10-timers.js b/templates/10-timers.js new file mode 100644 index 00000000..e01ccb2f --- /dev/null +++ b/templates/10-timers.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 10: SETTIMEOUT, SETINTERVAL AND REQUESTANIMATIONFRAME + * ========================================== + * + * Working with JavaScript timing functions + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of settimeout, setinterval and requestanimationframe'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/11-js-engines.js b/templates/11-js-engines.js new file mode 100644 index 00000000..832b61ac --- /dev/null +++ b/templates/11-js-engines.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 11: JAVASCRIPT ENGINES + * ========================================== + * + * How JavaScript engines (V8, SpiderMonkey) work + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of javascript engines'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/12-bitwise-operators.js b/templates/12-bitwise-operators.js new file mode 100644 index 00000000..8817fd5c --- /dev/null +++ b/templates/12-bitwise-operators.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 12: BITWISE OPERATORS, TYPE ARRAYS AND ARRAY BUFFERS + * ========================================== + * + * Low-level binary operations and typed arrays + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of bitwise operators, type arrays and array buffers'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/13-dom-layout-trees.js b/templates/13-dom-layout-trees.js new file mode 100644 index 00000000..e55cef9d --- /dev/null +++ b/templates/13-dom-layout-trees.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 13: DOM AND LAYOUT TREES + * ========================================== + * + * Document Object Model and browser rendering + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of dom and layout trees'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/14-factories-classes.js b/templates/14-factories-classes.js new file mode 100644 index 00000000..f78e5a20 --- /dev/null +++ b/templates/14-factories-classes.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 14: FACTORIES AND CLASSES + * ========================================== + * + * Object creation patterns: factory functions and ES6 classes + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of factories and classes'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/15-this-call-apply-bind.js b/templates/15-this-call-apply-bind.js new file mode 100644 index 00000000..06cad62e --- /dev/null +++ b/templates/15-this-call-apply-bind.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 15: THIS, CALL, APPLY AND BIND + * ========================================== + * + * Understanding context and function binding + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of this, call, apply and bind'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/16-new-constructor-instanceof.js b/templates/16-new-constructor-instanceof.js new file mode 100644 index 00000000..7af7bc3c --- /dev/null +++ b/templates/16-new-constructor-instanceof.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 16: NEW, CONSTRUCTOR, INSTANCEOF AND INSTANCES + * ========================================== + * + * Object instantiation and constructor functions + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of new, constructor, instanceof and instances'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/17-prototype-inheritance.js b/templates/17-prototype-inheritance.js new file mode 100644 index 00000000..570a24cc --- /dev/null +++ b/templates/17-prototype-inheritance.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 17: PROTOTYPE INHERITANCE AND PROTOTYPE CHAIN + * ========================================== + * + * JavaScript prototypal inheritance system + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of prototype inheritance and prototype chain'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/18-object-create-assign.js b/templates/18-object-create-assign.js new file mode 100644 index 00000000..984bedfd --- /dev/null +++ b/templates/18-object-create-assign.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 18: OBJECT.CREATE AND OBJECT.ASSIGN + * ========================================== + * + * Object creation and merging methods + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of object.create and object.assign'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/19-map-reduce-filter.js b/templates/19-map-reduce-filter.js new file mode 100644 index 00000000..a2ca8578 --- /dev/null +++ b/templates/19-map-reduce-filter.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 19: MAP, REDUCE, FILTER + * ========================================== + * + * Functional array methods for data transformation + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of map, reduce, filter'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/20-pure-functions.js b/templates/20-pure-functions.js new file mode 100644 index 00000000..a5f19c30 --- /dev/null +++ b/templates/20-pure-functions.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 20: PURE FUNCTIONS, SIDE EFFECTS, STATE MUTATION AND EVENT PROPAGATION + * ========================================== + * + * Functional programming concepts in JavaScript + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of pure functions, side effects, state mutation and event propagation'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/21-closures.js b/templates/21-closures.js new file mode 100644 index 00000000..9e46840c --- /dev/null +++ b/templates/21-closures.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 21: CLOSURES + * ========================================== + * + * Functions that remember their lexical scope + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of closures'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/22-higher-order-functions.js b/templates/22-higher-order-functions.js new file mode 100644 index 00000000..b20d78f7 --- /dev/null +++ b/templates/22-higher-order-functions.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 22: HIGH ORDER FUNCTIONS + * ========================================== + * + * Functions that accept or return other functions + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of high order functions'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/23-recursion.js b/templates/23-recursion.js new file mode 100644 index 00000000..b8f7caa9 --- /dev/null +++ b/templates/23-recursion.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 23: RECURSION + * ========================================== + * + * Functions that call themselves + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of recursion'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/24-collections-generators.js b/templates/24-collections-generators.js new file mode 100644 index 00000000..118d00f8 --- /dev/null +++ b/templates/24-collections-generators.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 24: COLLECTIONS AND GENERATORS + * ========================================== + * + * Map, Set, WeakMap, WeakSet, and generator functions + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of collections and generators'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/25-promises.js b/templates/25-promises.js new file mode 100644 index 00000000..746c77f3 --- /dev/null +++ b/templates/25-promises.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 25: PROMISES + * ========================================== + * + * Handling asynchronous operations with Promises + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of promises'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/26-async-await.js b/templates/26-async-await.js new file mode 100644 index 00000000..d95096e0 --- /dev/null +++ b/templates/26-async-await.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 26: ASYNC/AWAIT + * ========================================== + * + * Modern asynchronous JavaScript syntax + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of async/await'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/27-data-structures.js b/templates/27-data-structures.js new file mode 100644 index 00000000..722f96e3 --- /dev/null +++ b/templates/27-data-structures.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 27: DATA STRUCTURES + * ========================================== + * + * Implementing common data structures in JavaScript + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of data structures'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/28-big-o-notation.js b/templates/28-big-o-notation.js new file mode 100644 index 00000000..8416c47e --- /dev/null +++ b/templates/28-big-o-notation.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 28: EXPENSIVE OPERATION AND BIG O NOTATION + * ========================================== + * + * Algorithm complexity and performance analysis + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of expensive operation and big o notation'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/29-algorithms.js b/templates/29-algorithms.js new file mode 100644 index 00000000..373fc31c --- /dev/null +++ b/templates/29-algorithms.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 29: ALGORITHMS + * ========================================== + * + * Common algorithms and problem-solving patterns + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of algorithms'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/30-inheritance-polymorphism.js b/templates/30-inheritance-polymorphism.js new file mode 100644 index 00000000..c2d5ea65 --- /dev/null +++ b/templates/30-inheritance-polymorphism.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 30: INHERITANCE, POLYMORPHISM AND CODE REUSE + * ========================================== + * + * Object-oriented programming in JavaScript + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of inheritance, polymorphism and code reuse'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/31-design-patterns.js b/templates/31-design-patterns.js new file mode 100644 index 00000000..23efb728 --- /dev/null +++ b/templates/31-design-patterns.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 31: DESIGN PATTERNS + * ========================================== + * + * Common software design patterns in JavaScript + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of design patterns'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/32-currying-compose-pipe.js b/templates/32-currying-compose-pipe.js new file mode 100644 index 00000000..70d69144 --- /dev/null +++ b/templates/32-currying-compose-pipe.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 32: PARTIAL APPLICATIONS, CURRYING, COMPOSE AND PIPE + * ========================================== + * + * Advanced functional programming techniques + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of partial applications, currying, compose and pipe'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/33-clean-code.js b/templates/33-clean-code.js new file mode 100644 index 00000000..cb851431 --- /dev/null +++ b/templates/33-clean-code.js @@ -0,0 +1,105 @@ +/** + * ========================================== + * CONCEPT 33: CLEAN CODE + * ========================================== + * + * Writing maintainable and readable JavaScript + * + * This template provides a starting point for learning and practicing this concept. + */ + +// ========================================== +// EXAMPLE 1: Basic Usage +// ========================================== + +// TODO: Add basic example +console.log('Example 1: Basic usage of clean code'); + +// ========================================== +// EXAMPLE 2: Intermediate Concepts +// ========================================== + +// TODO: Add intermediate example +console.log('Example 2: More advanced usage'); + +// ========================================== +// EXAMPLE 3: Real-World Application +// ========================================== + +// TODO: Add real-world example +console.log('Example 3: Practical application'); + +// ========================================== +// PRACTICE EXERCISES +// ========================================== + +/** + * Exercise 1: Basic understanding + * TODO: Create an exercise that tests basic understanding + */ +function exercise1() { + // Your code here +} + +/** + * Exercise 2: Intermediate challenge + * TODO: Create a more challenging exercise + */ +function exercise2() { + // Your code here +} + +/** + * Exercise 3: Advanced application + * TODO: Create an advanced exercise + */ +function exercise3() { + // Your code here +} + +// ========================================== +// COMMON PITFALLS +// ========================================== + +/** + * Pitfall 1: [Common mistake description] + */ +// Example of what NOT to do + +/** + * Pitfall 2: [Common mistake description] + */ +// Example of what NOT to do + +// ========================================== +// BEST PRACTICES +// ========================================== + +/** + * 1. [Best practice description] + */ +// Example of good practice + +/** + * 2. [Best practice description] + */ +// Example of good practice + +/** + * 3. [Best practice description] + */ +// Example of good practice + +// ========================================== +// NOTES +// ========================================== +// - [Key point 1] +// - [Key point 2] +// - [Key point 3] +// - [Key point 4] +// - [Key point 5] + +// ========================================== +// RESOURCES +// ========================================== +// Refer to the main README.md for articles and videos about this concept diff --git a/templates/README.md b/templates/README.md new file mode 100644 index 00000000..0920f11f --- /dev/null +++ b/templates/README.md @@ -0,0 +1,214 @@ +# 33 JavaScript Concepts - Templates + +Welcome to the templates directory! šŸš€ + +## Overview + +This directory contains ready-to-use JavaScript templates for each of the 33 fundamental JavaScript concepts. These templates are designed to help you get started with learning, practicing, and mastering each concept. + +## How to Use These Templates + +### For Learning +1. **Read the concept**: Each template begins with a clear explanation of the concept +2. **Study the examples**: Multiple examples demonstrate the concept from basic to advanced +3. **Review pitfalls**: Learn what mistakes to avoid +4. **Follow best practices**: See recommended approaches + +### For Practice +1. **Complete the exercises**: Each template includes practice exercises +2. **Experiment**: Modify the examples and see what happens +3. **Build projects**: Use the templates as starting points for your own projects + +### Getting Started + +#### Option 1: Copy a template +```bash +# Copy the template you want to work on +cp templates/01-call-stack.js my-practice/call-stack-practice.js + +# Edit and run it +node my-practice/call-stack-practice.js +``` + +#### Option 2: Use it directly +```bash +# Navigate to templates directory +cd templates + +# Run any template +node 01-call-stack.js +``` + +#### Option 3: Import in your project +```javascript +// You can import concepts into your own files +// (uncomment exports in template files first) +const { example1, exercise1 } = require('./templates/01-call-stack.js'); +``` + +## Template Structure + +Each template follows a consistent structure: + +```javascript +/** + * CONCEPT TITLE AND DESCRIPTION + */ + +// EXAMPLES +// Multiple examples showing the concept in action + +// PRACTICE EXERCISES +// Hands-on exercises to test your understanding + +// COMMON PITFALLS +// What to avoid and why + +// BEST PRACTICES +// Recommended approaches + +// NOTES +// Key takeaways and important points +``` + +## The 33 Concepts + +### Fundamentals (1-8) +1. **Call Stack** - Understanding function execution order +2. **Primitive Types** - The building blocks of JavaScript data +3. **Value Types and Reference Types** - How data is stored and passed +4. **Type Coercion** - Implicit and explicit type conversion +5. **Equality Comparison** - == vs === vs typeof +6. **Scope** - Function, block, and lexical scope +7. **Expression vs Statement** - The difference and when to use each +8. **IIFE, Modules and Namespaces** - Code organization patterns + +### Asynchronous JavaScript (9-11) +9. **Message Queue and Event Loop** - How async code works +10. **Timers** - setTimeout, setInterval, requestAnimationFrame +11. **JavaScript Engines** - V8, SpiderMonkey, and how JS runs + +### Advanced Types and DOM (12-13) +12. **Bitwise Operators** - Binary operations and typed arrays +13. **DOM and Layout Trees** - Browser rendering and manipulation + +### Objects and Functions (14-18) +14. **Factories and Classes** - Object creation patterns +15. **this, call, apply, bind** - Context and function binding +16. **new and Constructor** - Object instantiation +17. **Prototype Inheritance** - JavaScript's inheritance model +18. **Object.create and Object.assign** - Object manipulation + +### Functional Programming (19-23) +19. **map, reduce, filter** - Array transformation methods +20. **Pure Functions** - Side effects and state mutation +21. **Closures** - Functions with persistent scope +22. **Higher Order Functions** - Functions as first-class citizens +23. **Recursion** - Self-calling functions + +### Modern JavaScript (24-26) +24. **Collections and Generators** - Map, Set, and generator functions +25. **Promises** - Handling async operations +26. **async/await** - Modern async syntax + +### Computer Science (27-29) +27. **Data Structures** - Arrays, trees, graphs, etc. +28. **Big O Notation** - Algorithm complexity +29. **Algorithms** - Common algorithms and patterns + +### Architecture (30-33) +30. **Inheritance and Polymorphism** - OOP in JavaScript +31. **Design Patterns** - Common software patterns +32. **Currying and Composition** - Advanced functional techniques +33. **Clean Code** - Writing maintainable code + +## Tips for Effective Learning + +### 1. Start from the Beginning +If you're new to JavaScript, start with concept 1 and work your way through sequentially. Each concept builds on previous ones. + +### 2. Practice Regularly +- Complete all exercises in each template +- Try to solve them without looking at the examples +- Experiment with variations + +### 3. Build Real Projects +Apply each concept in a real project. For example: +- Build a calculator to practice operators +- Create a todo app to practice DOM manipulation +- Build an async data fetcher to practice promises + +### 4. Debug and Experiment +- Use `console.log()` liberally +- Use browser dev tools +- Try to break things and understand why + +### 5. Teach Others +The best way to solidify your understanding is to explain concepts to others. + +## Running the Templates + +### Prerequisites +- Node.js installed (v12 or higher recommended) +- A code editor (VS Code, Sublime, Atom, etc.) +- Basic command line knowledge + +### In Node.js +```bash +node templates/01-call-stack.js +``` + +### In Browser Console +1. Open your browser's developer tools (F12) +2. Copy the template code +3. Paste into the console +4. Press Enter + +### With a Module Bundler +If you're using webpack, rollup, or similar: +```javascript +import './templates/01-call-stack.js'; +``` + +## Customizing Templates + +Feel free to modify these templates to suit your learning style: + +1. **Add your own examples**: Supplement with examples relevant to your work +2. **Create more exercises**: Challenge yourself with additional problems +3. **Add comments**: Annotate with your own notes and insights +4. **Combine concepts**: Create exercises that use multiple concepts together + +## Contributing + +Found a bug or have an improvement? Contributions are welcome! + +1. Fork the repository +2. Create your feature branch +3. Make your changes +4. Submit a pull request + +See [CONTRIBUTING.md](../CONTRIBUTING.md) for more details. + +## Additional Resources + +Each template focuses on hands-on practice. For comprehensive learning: + +- **Articles and Videos**: See the main [README.md](../README.md) for curated lists +- **MDN Web Docs**: [developer.mozilla.org](https://developer.mozilla.org/) +- **JavaScript.info**: [javascript.info](https://javascript.info/) +- **You Don't Know JS**: Book series by Kyle Simpson + +## Feedback + +Have suggestions for improving these templates? Open an issue on GitHub! + +## License + +These templates are part of the 33-js-concepts project and are licensed under the MIT License. See [LICENSE](../LICENSE) for details. + +--- + +Happy Learning! šŸŽ‰ + +Remember: The goal isn't just to read through these templates, but to **practice**, **experiment**, and **build** with them. The more you code, the better you'll understand these concepts.