You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Modern Class SyntaxclassUser{// Private fields (# makes it private)
#password;// Constructor methodconstructor(username,password){this.username=username;// Public propertythis.#password =password;// Private property}// Instance methodlogin(){return`${this.username} is logging in...`;}// Static method (called on class itself)staticvalidateUsername(username){returnusername.length>=3;}// GettergetuserInfo(){return`Username: ${this.username}`;}// SettersetuserPassword(newPassword){if(newPassword.length>=8){this.#password =newPassword;}}}// Using the classconstuser=newUser('john_doe','secret123');console.log(user.login());// "john_doe is logging in..."console.log(User.validateUsername('john_doe'));// true
Inheritance and Polymorphism
// Base classclassAnimal{constructor(name){this.name=name;}speak(){return`${this.name} makes a sound`;}}// Derived classclassDogextendsAnimal{constructor(name,breed){super(name);// Call parent constructorthis.breed=breed;}speak(){return`${this.name} barks!`;// Override parent method}fetch(){return`${this.name} fetches the ball`;}}// Using inheritanceconstdog=newDog('Rex','German Shepherd');console.log(dog.speak());// "Rex barks!"console.log(dog.fetch());// "Rex fetches the ball"
Advanced Functions & Closures
Higher-Order Functions
// Functions that take or return other functionsconstmultiply=(multiplier)=>{// Returns a new functionreturn(number)=>number*multiplier;};constdouble=multiply(2);consttriple=multiply(3);console.log(double(5));// 10console.log(triple(5));// 15// Function compositionconstcompose=(f,g)=>(x)=>f(g(x));constaddOne=(x)=>x+1;constsquare=(x)=>x*x;constaddThenSquare=compose(square,addOne);console.log(addThenSquare(3));// 16 ((3 + 1)²)
// Converting a function with multiple arguments// into a sequence of functions with single argumentsconstcurry=(fn)=>{returnfunctioncurried(...args){if(args.length>=fn.length){returnfn(...args);}return(...moreArgs)=>curried(...args, ...moreArgs);};};// Example usageconstsum=(a,b,c)=>a+b+c;constcurriedSum=curry(sum);console.log(curriedSum(1)(2)(3));// 6console.log(curriedSum(1,2)(3));// 6console.log(curriedSum(1)(2,3));// 6
Asynchronous Programming
Promises Deep Dive
// Creating and using promisesconstfetchData=(id)=>{returnnewPromise((resolve,reject)=>{// Simulating API callsetTimeout(()=>{constdata={id: id,name: 'Item '+id};if(id>0){resolve(data);// Success case}else{reject('Invalid ID');// Error case}},1000);});};// Promise chainingfetchData(1).then(data=>{console.log('First then:',data);returnfetchData(2);// Return another promise}).then(data=>{console.log('Second then:',data);}).catch(error=>{console.error('Error:',error);}).finally(()=>{console.log('Operation complete');});
Async/Await Patterns
// Basic async/awaitasyncfunctiongetData(){try{constresult1=awaitfetchData(1);console.log('First result:',result1);constresult2=awaitfetchData(2);console.log('Second result:',result2);return[result1,result2];}catch(error){console.error('Error:',error);}}// Parallel executionasyncfunctiongetMultipleData(){try{// Run promises in parallelconstresults=awaitPromise.all([fetchData(1),fetchData(2),fetchData(3)]);console.log('All results:',results);}catch(error){console.error('Error in parallel execution:',error);}}
Advanced Async Patterns
// Custom async iteratorasyncfunction*generateSequence(start,end){for(leti=start;i<=end;i++){// Yield promise resultsyieldawaitfetchData(i);}}// Using async iteratorasyncfunctionprocessSequence(){forawait(constdataofgenerateSequence(1,3)){console.log('Processed:',data);}}// Race condition handlingasyncfunctiongetFirstResult(){try{constresult=awaitPromise.race([fetchData(1),fetchData(2),fetchData(3)]);console.log('First to complete:',result);}catch(error){console.error('Race error:',error);}}
// Map - key-value pairs with any type of keyconstuserMap=newMap();userMap.set('john',{age: 30});userMap.set(42,'meaning');// Numbers as keysuserMap.set(user,'object');// Objects as keys// Set - unique valuesconstuniqueNumbers=newSet([1,2,2,3,3,4]);uniqueNumbers.add(5);uniqueNumbers.has(2);// trueuniqueNumbers.size;// 5// WeakMap and WeakSetconstweakMap=newWeakMap();// Garbage-collection-friendlyconstkey={id: 1};weakMap.set(key,'data');
Modern Functions and Methods
// Array methodsconstitems=[1,2,3,4,5];// Pipeline of operationsconstresult=items.filter(n=>n>2)// [3, 4, 5].map(n=>n*2)// [6, 8, 10].reduce((sum,n)=>sum+n);// 24// Object methodsconstsource={a: 1,b: 2};constclone=Object.fromEntries(// Create object from entriesObject.entries(source)// Get key-value pairs.map(([key,val])=>[key,val*2]));// String methodsconsttext=' Hello World ';text.trimStart();// "Hello World "text.trimEnd();// " Hello World"text.replaceAll('l','L');// " HeLLo WorLd "
// Observer PatternclassEventEmitter{constructor(){this.events={};}on(event,callback){if(!this.events[event]){this.events[event]=[];}this.events[event].push(callback);}emit(event,data){if(this.events[event]){this.events[event].forEach(callback=>callback(data));}}}// Strategy PatternclassPaymentProcessor{constructor(strategy){this.strategy=strategy;}processPayment(amount){returnthis.strategy.pay(amount);}}classCreditCardStrategy{pay(amount){return`Paid ${amount} with credit card`;}}
Performance Optimization
Memory Management
// Efficient data structuresconstlargeArray=newArray(1000000);// Pre-allocate spaceconsttypedArray=newFloat64Array(1000);// Typed arrays for numbers// Memory leaks preventionclassResourceManager{constructor(){this.resources=newWeakMap();// Automatic cleanup}addResource(key,value){this.resources.set(key,value);}// Proper cleanupdispose(){this.resources=null;}}
Code Optimization
// Caching results (memoization)constmemoize=(fn)=>{constcache=newMap();return(...args)=>{constkey=JSON.stringify(args);if(cache.has(key)){returncache.get(key);// Return cached result}constresult=fn(...args);cache.set(key,result);// Store for laterreturnresult;};};// Efficient loopsconstarr=[1,2,3,4,5];// Faster than forEach for large arraysfor(leti=0;i<arr.length;i++){// Process item}
DOM Performance
// Batch DOM updatesconstfragment=document.createDocumentFragment();for(leti=0;i<1000;i++){constdiv=document.createElement('div');div.textContent=`Item ${i}`;fragment.appendChild(div);}document.body.appendChild(fragment);// Single DOM update// Virtual scrolling for large listsclassVirtualScroller{constructor(container,items){this.container=container;this.items=items;this.viewportHeight=container.clientHeight;this.rowHeight=30;this.visibleItems=Math.ceil(this.viewportHeight/this.rowHeight);this.renderVisible();}renderVisible(){// Only render items in viewportconststart=Math.floor(this.container.scrollTop/this.rowHeight);constitems=this.items.slice(start,start+this.visibleItems);// Render items...}}
Testing & Debugging
Unit Testing
// Using Jest testing frameworkdescribe('Calculator',()=>{// Setup before testsconstcalculator=newCalculator();test('adds two numbers correctly',()=>{expect(calculator.add(2,3)).toBe(5);});test('subtracts two numbers correctly',()=>{expect(calculator.subtract(5,3)).toBe(2);});// Test async functionstest('fetches user data',async()=>{constdata=awaitcalculator.fetchData();expect(data).toHaveProperty('id');});});// Mock functions and dependenciesconstmockAPI={getData: jest.fn().mockResolvedValue({success: true})};