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
// Variable declarationsvaroldWay="avoid using var";letmutableVar="can be changed";constimmutableVar="cannot be reassigned";// Data typesletstring="Hello World";letnumber=42;letboolean=true;letundefinedVar;letnullVar=null;letsymbol=Symbol("unique");letbigInt=123n;// Check typesconsole.log(typeofstring);// "string"console.log(typeofnumber);// "number"console.log(typeofboolean);// "boolean"
Operators
// Arithmetic operatorsleta=10,b=3;console.log(a+b);// 13console.log(a-b);// 7console.log(a*b);// 30console.log(a/b);// 3.333...console.log(a%b);// 1 (remainder)console.log(a**b);// 1000 (exponentiation)// Comparison operatorsconsole.log(a>b);// trueconsole.log(a===b);// false (strict equality)console.log(a==b);// false (loose equality)console.log(a!==b);// true// Logical operatorsconsole.log(true&&false);// falseconsole.log(true||false);// trueconsole.log(!true);// false// Assignment operatorsa+=5;// a = a + 5a-=2;// a = a - 2a*=2;// a = a * 2
// Single line comment/*Multi-line commentCan span multiple lines*//** * JSDoc comment for documentation * @param {string} name - The name parameter * @returns {string} - A greeting message */functiongreet(name){return`Hello, ${name}!`;}
// for loopfor(leti=0;i<5;i++){console.log(i);}// while loopletcount=0;while(count<3){console.log(count);count++;}// do...while loopletx=0;do{console.log(x);x++;}while(x<3);// for...in (object properties)letobj={a: 1,b: 2,c: 3};for(letkeyinobj){console.log(key,obj[key]);}// for...of (iterable values)letarr=[1,2,3];for(letvalueofarr){console.log(value);}// Break and continuefor(leti=0;i<10;i++){if(i===5)break;// Exit loopif(i===2)continue;// Skip iterationconsole.log(i);}
Switch Statement
letday="Monday";switch(day){case"Monday":
console.log("Start of work week");break;case"Friday":
console.log("TGIF!");break;case"Saturday":
case"Sunday":
console.log("Weekend!");break;default:
console.log("Regular day");}
Functions
Function Declaration
// Function declaration (hoisted)functiongreet(name){return`Hello, ${name}!`;}// Function with multiple parametersfunctionadd(a,b){returna+b;}// Function with default parametersfunctionmultiply(a,b=1){returna*b;}console.log(greet("John"));// "Hello, John!"console.log(add(5,3));// 8console.log(multiply(5));// 5
Function Expression
// Function expression (not hoisted)constsubtract=function(a,b){returna-b;};// Named function expressionconstdivide=functiondivideNumbers(a,b){if(b===0)thrownewError("Division by zero");returna/b;};console.log(subtract(10,3));// 7
Arrow Functions
// Arrow function syntaxconstsquare=(x)=>x*x;constcube=x=>x*x*x;// Single parameter, no parentheses// Multiple parametersconstsum=(a,b)=>a+b;// Block bodyconstprocessData=(data)=>{constprocessed=data.map(x=>x*2);returnprocessed.filter(x=>x>10);};// Arrow functions don't have their own 'this'constobj={name: "Test",regularFunction: function(){console.log(this.name);// "Test"},arrowFunction: ()=>{console.log(this.name);// undefined (in strict mode)}};
// Global scopeletglobalVar="I'm global";functionouterFunction(x){// Function scopeletouterVar="I'm outer";functioninnerFunction(y){// Inner function has access to outer variables (closure)console.log(globalVar);// "I'm global"console.log(outerVar);// "I'm outer"console.log(x,y);// Parameters from both functions}returninnerFunction;}constclosureExample=outerFunction(10);closureExample(20);// Practical closure examplefunctioncreateCounter(){letcount=0;returnfunction(){return++count;};}constcounter=createCounter();console.log(counter());// 1console.log(counter());// 2
Objects and Arrays
Objects
// Object literalconstperson={name: "John",age: 30,city: "New York",greet: function(){return`Hello, I'm ${this.name}`;},// Method shorthandintroduce(){return`I'm ${this.name}, ${this.age} years old`;}};// Accessing propertiesconsole.log(person.name);// "John"console.log(person["age"]);// 30// Adding/modifying propertiesperson.email="john@email.com";person["phone"]="123-456-7890";// Object methodsconsole.log(Object.keys(person));// Array of keysconsole.log(Object.values(person));// Array of valuesconsole.log(Object.entries(person));// Array of [key, value] pairs// Object.assign (shallow copy)constnewPerson=Object.assign({},person,{age: 31});// Object destructuring in parametersfunctionprintPersonInfo({ name, age, city ="Unknown"}){console.log(`${name}, ${age}, from ${city}`);}
Arrays
// Array creationconstfruits=["apple","banana","orange"];constnumbers=newArray(1,2,3,4,5);constempty=newArray(5);// Creates array with 5 empty slots// Array methodsfruits.push("grape");// Add to endfruits.unshift("mango");// Add to beginningletlast=fruits.pop();// Remove from endletfirst=fruits.shift();// Remove from beginning// Array iterationfruits.forEach((fruit,index)=>{console.log(`${index}: ${fruit}`);});// Array transformationconstupperFruits=fruits.map(fruit=>fruit.toUpperCase());constlongFruits=fruits.filter(fruit=>fruit.length>5);consttotal=numbers.reduce((sum,num)=>sum+num,0);// Finding elementsconstfound=fruits.find(fruit=>fruit.startsWith("a"));constindex=fruits.findIndex(fruit=>fruit==="banana");constincludes=fruits.includes("apple");// Array sortingconstsorted=fruits.sort();constnumSorted=numbers.sort((a,b)=>a-b);// Numeric sort
// Spread operator with arraysconstarr1=[1,2,3];constarr2=[4,5,6];constcombined=[...arr1, ...arr2];// [1, 2, 3, 4, 5, 6]constcopied=[...arr1];// Shallow copy// Spread with objectsconstobj1={a: 1,b: 2};constobj2={c: 3,d: 4};constmerged={ ...obj1, ...obj2};// { a: 1, b: 2, c: 3, d: 4 }constupdated={ ...obj1,b: 20};// Override property// Rest operatorfunctionprocessData(first,second, ...rest){console.log(first,second);// First two argumentsconsole.log(rest);// Array of remaining arguments}// Rest in destructuringconst[head, ...tail]=[1,2,3,4,5];const{ name, ...otherProps}={name: "John",age: 30,city: "NYC"};
ES6+ Features
Let and Const
// Block scopeif(true){letblockScoped="only available in this block";constalsoBlockScoped="cannot be reassigned";varfunctionScoped="available in entire function";}// Temporal dead zoneconsole.log(x);// ReferenceErrorletx=5;// Const with objects (object is mutable, reference is not)constconfig={api: "https://api.example.com"};config.api="https://new-api.example.com";// OKconfig.timeout=5000;// OK// config = {}; // TypeError: Assignment to constant variable
Template Literals
constname="Alice";constage=25;// Template literalsconstmessage=`Hello, my name is ${name} and I'm ${age} years old.`;// Multi-line stringsconstmultiLine=` This is a multi-line string`;// Tagged templatesfunctionhighlight(strings, ...values){returnstrings.reduce((result,string,i)=>{constvalue=values[i] ? `<mark>${values[i]}</mark>` : '';returnresult+string+value;},'');}consthighlighted=highlight`Name: ${name}, Age: ${age}`;
Classes
// Class declarationclassPerson{constructor(name,age){this.name=name;this.age=age;}// Methodgreet(){return`Hello, I'm ${this.name}`;}// Gettergetinfo(){return`${this.name} (${this.age})`;}// Settersetage(value){if(value<0)thrownewError("Age cannot be negative");this._age=value;}// Static methodstaticcreateAdult(name){returnnewPerson(name,18);}}// InheritanceclassStudentextendsPerson{constructor(name,age,grade){super(name,age);// Call parent constructorthis.grade=grade;}greet(){return`${super.greet()}, I'm in grade ${this.grade}`;}}conststudent=newStudent("Bob",16,"10th");console.log(student.greet());
// Creating a PromiseconstfetchUserData=newPromise((resolve,reject)=>{constsuccess=Math.random()>0.5;setTimeout(()=>{if(success){resolve({id: 1,name: "Alice"});}else{reject(newError("Failed to fetch user data"));}},1000);});// Using PromisesfetchUserData.then(data=>{console.log("User data:",data);returndata.id;// Return for next .then()}).then(userId=>{console.log("User ID:",userId);}).catch(error=>{console.error("Error:",error.message);}).finally(()=>{console.log("Cleanup operations");});// Promise.all - Wait for all promisesconstpromise1=Promise.resolve(3);constpromise2=newPromise(resolve=>setTimeout(()=>resolve('foo'),1000));constpromise3=Promise.resolve(42);Promise.all([promise1,promise2,promise3]).then(values=>console.log(values));// [3, 'foo', 42]// Promise.race - First promise to settlePromise.race([promise1,promise2,promise3]).then(value=>console.log(value));// 3// Promise.allSettled - Wait for all, regardless of outcomePromise.allSettled([promise1,Promise.reject('error'),promise3]).then(results=>console.log(results));
Async/Await
// Async functionasyncfunctionfetchUserData(){try{constresponse=awaitfetch('/api/user');constuserData=awaitresponse.json();returnuserData;}catch(error){console.error('Error fetching user data:',error);throwerror;}}// Using async/awaitasyncfunctionmain(){try{constuser=awaitfetchUserData();console.log('User:',user);// Sequential executionconstposts=awaitfetchUserPosts(user.id);constcomments=awaitfetchPostComments(posts[0].id);// Parallel executionconst[profile,settings]=awaitPromise.all([fetchUserProfile(user.id),fetchUserSettings(user.id)]);}catch(error){console.error('Error in main:',error);}}// Async arrow functionconstquickFetch=async(url)=>{constresponse=awaitfetch(url);returnresponse.json();};// Async iterationasyncfunctionprocessItems(items){for(constitemofitems){awaitprocessItem(item);// Sequential}// Parallel processingawaitPromise.all(items.map(item=>processItem(item)));}
Fetch API
// Basic GET requestfetch('https://api.example.com/users').then(response=>{if(!response.ok){thrownewError(`HTTP error! status: ${response.status}`);}returnresponse.json();}).then(data=>console.log(data)).catch(error=>console.error('Error:',error));// POST request with async/awaitasyncfunctioncreateUser(userData){try{constresponse=awaitfetch('https://api.example.com/users',{method: 'POST',headers: {'Content-Type': 'application/json','Authorization': 'Bearer token123'},body: JSON.stringify(userData)});if(!response.ok){thrownewError(`HTTP error! status: ${response.status}`);}constnewUser=awaitresponse.json();returnnewUser;}catch(error){console.error('Error creating user:',error);throwerror;}}// File uploadasyncfunctionuploadFile(file){constformData=newFormData();formData.append('file',file);constresponse=awaitfetch('/upload',{method: 'POST',body: formData});returnresponse.json();}// Request with timeoutfunctionfetchWithTimeout(url,timeout=5000){returnPromise.race([fetch(url),newPromise((_,reject)=>setTimeout(()=>reject(newError('Timeout')),timeout))]);}
DOM Manipulation
Selecting Elements
// Single element selectorsconstelementById=document.getElementById('myId');constelementByClass=document.querySelector('.myClass');constelementByTag=document.querySelector('p');constelementByAttribute=document.querySelector('[data-id="123"]');// Multiple element selectorsconstelementsByClass=document.getElementsByClassName('myClass');constelementsByTag=document.getElementsByTagName('p');constelementsByQuery=document.querySelectorAll('.item');// Traversing the DOMconstparent=element.parentNode;constchildren=element.children;constfirstChild=element.firstElementChild;constlastChild=element.lastElementChild;constnextSibling=element.nextElementSibling;constpreviousSibling=element.previousElementSibling;// Modern traversalconstclosest=element.closest('.container');// Closest ancestor with classconstmatches=element.matches('.active');// Check if element matches selector
Modifying Elements
// Content modificationelement.textContent="New text content";element.innerHTML="<strong>Bold text</strong>";element.innerText="Visible text only";// Attribute manipulationelement.setAttribute('data-id','123');element.getAttribute('data-id');element.removeAttribute('data-id');element.hasAttribute('data-id');// Modern attribute accesselement.id='newId';element.className='new-class';element.dataset.userId='456';// data-user-id attribute// Style manipulationelement.style.color='red';element.style.backgroundColor='blue';element.style.cssText='color: red; background: blue;';// Class manipulationelement.classList.add('new-class');element.classList.remove('old-class');element.classList.toggle('active');element.classList.contains('active');element.classList.replace('old','new');// Propertieselement.value='new value';// For form elementselement.checked=true;// For checkboxeselement.disabled=false;// For form elementselement.hidden=true;// Hide element
// Creating elementsconstnewDiv=document.createElement('div');constnewText=document.createTextNode('Hello World');constnewComment=document.createComment('This is a comment');// Setting up the elementnewDiv.textContent='New content';newDiv.className='new-element';newDiv.setAttribute('data-id','123');// Adding to DOMparentElement.appendChild(newDiv);parentElement.insertBefore(newDiv,referenceElement);parentElement.replaceChild(newDiv,oldElement);// Modern insertion methodsparentElement.prepend(newDiv);// Add as first childparentElement.append(newDiv);// Add as last childelement.before(newDiv);// Insert before elementelement.after(newDiv);// Insert after elementelement.replaceWith(newDiv);// Replace element// Removing elementselement.remove();// Remove elementparentElement.removeChild(element);// Old way// Cloning elementsconstclone=element.cloneNode(true);// Deep clone with childrenconstshallowClone=element.cloneNode(false);// Shallow clone// Document fragments (performance optimization)constfragment=document.createDocumentFragment();for(leti=0;i<1000;i++){constli=document.createElement('li');li.textContent=`Item ${i}`;fragment.appendChild(li);}ul.appendChild(fragment);// Single DOM operation// Template elementconsttemplate=document.querySelector('#myTemplate');constclone=template.content.cloneNode(true);document.body.appendChild(clone);
Error Handling
Try/Catch
// Basic try/catchtry{letresult=riskyOperation();console.log(result);}catch(error){console.error('An error occurred:',error.message);}finally{console.log('This always runs');}// Catching specific error typestry{JSON.parse(invalidJson);}catch(error){if(errorinstanceofSyntaxError){console.error('Invalid JSON syntax');}elseif(errorinstanceofReferenceError){console.error('Reference error');}else{console.error('Unknown error:',error);}}// Async/await with try/catchasyncfunctionfetchData(){try{constresponse=awaitfetch('/api/data');constdata=awaitresponse.json();returndata;}catch(error){console.error('Fetch failed:',error);throwerror;// Re-throw if needed}}// Nested try/catchfunctionprocessFile(filename){try{constcontent=readFile(filename);try{constparsed=JSON.parse(content);returnparsed;}catch(parseError){console.error('Parse error:',parseError.message);returnnull;}}catch(fileError){console.error('File error:',fileError.message);returnnull;}}
Custom Errors
// Custom error classclassValidationErrorextendsError{constructor(message,field){super(message);this.name='ValidationError';this.field=field;}}classNetworkErrorextendsError{constructor(message,statusCode){super(message);this.name='NetworkError';this.statusCode=statusCode;}}// Using custom errorsfunctionvalidateUser(user){if(!user.email){thrownewValidationError('Email is required','email');}if(!user.email.includes('@')){thrownewValidationError('Invalid email format','email');}}// Error factory functionfunctioncreateError(type,message,extra={}){consterror=newError(message);error.type=type;Object.assign(error,extra);returnerror;}// Handling custom errorstry{validateUser({name: 'John'});}catch(error){if(errorinstanceofValidationError){console.error(`Validation failed for ${error.field}: ${error.message}`);}else{console.error('Unexpected error:',error);}}
Debugging
// Console methodsconsole.log('Basic logging');console.info('Information');console.warn('Warning message');console.error('Error message');// Structured loggingconsole.table([{name: 'John',age: 30},{name: 'Jane',age: 25}]);console.group('User Data');console.log('Name: John');console.log('Age: 30');console.groupEnd();// Timingconsole.time('operation');// ... some operationconsole.timeEnd('operation');// Logs elapsed time// Assertionsconsole.assert(user.age>0,'Age must be positive');// Stack traceconsole.trace('Trace point reached');// Conditional loggingconstDEBUG=true;DEBUG&&console.log('Debug information');// Object inspectionconsole.dir(complexObject,{depth: 3});// Performance monitoringfunctionmeasurePerformance(fn, ...args){conststart=performance.now();constresult=fn(...args);constend=performance.now();console.log(`Function took ${end-start} milliseconds`);returnresult;}// Error boundaries for debuggingwindow.addEventListener('error',(event)=>{console.error('Global error:',event.error);console.log('Script:',event.filename);console.log('Line:',event.lineno);console.log('Column:',event.colno);});// Promise rejection handlingwindow.addEventListener('unhandledrejection',(event)=>{console.error('Unhandled promise rejection:',event.reason);event.preventDefault();// Prevent default browser behavior});// Debugger statementfunctioncomplexFunction(data){// Process datadebugger;// Execution will pause here in dev toolsreturnprocessedData;}
Advanced Concepts
Prototypes and Inheritance
// Constructor function and prototypefunctionPerson(name,age){this.name=name;this.age=age;}Person.prototype.greet=function(){return`Hello, I'm ${this.name}`;};Person.prototype.getAge=function(){returnthis.age;};// Inheritance with constructor functionsfunctionStudent(name,age,grade){Person.call(this,name,age);// Call parent constructorthis.grade=grade;}// Set up prototype chainStudent.prototype=Object.create(Person.prototype);Student.prototype.constructor=Student;Student.prototype.study=function(){return`${this.name} is studying`;};// Prototype chain checkingconststudent=newStudent('Alice',20,'A');console.log(studentinstanceofStudent);// trueconsole.log(studentinstanceofPerson);// true// Object.getPrototypeOf and isPrototypeOfconsole.log(Object.getPrototypeOf(student)===Student.prototype);// trueconsole.log(Person.prototype.isPrototypeOf(student));// true// Modern class syntax (same prototype chain)classModernPerson{constructor(name,age){this.name=name;this.age=age;}greet(){return`Hello, I'm ${this.name}`;}}// Prototype manipulationObject.setPrototypeOf(obj,newPrototype);console.log(obj.hasOwnProperty('property'));
Regular Expressions
// Creating regex patternsconstpattern1=/hello/i;// Literal notationconstpattern2=newRegExp('hello','i');// Constructor// Common patternsconstemailPattern=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;constphonePattern=/^\(\d{3}\)\s\d{3}-\d{4}$/;consturlPattern=/https?:\/\/(www\.)?[\w\-]+(\.[\w\-]+)+[/#?]?.*$/;// String methods with regexconsttext="Hello World 123";console.log(text.match(/\d+/));// ["123"]console.log(text.search(/world/i));// 6console.log(text.replace(/\d+/,'ABC'));// "Hello World ABC"console.log(text.split(/\s+/));// ["Hello", "World", "123"]// Regex methodsconstregex=/(\d{4})-(\d{2})-(\d{2})/;constdateString="2023-12-25";console.log(regex.test(dateString));// trueconsole.log(regex.exec(dateString));// ["2023-12-25", "2023", "12", "25"]// Global and sticky flagsconstglobalRegex=/\d+/g;consttext2="123 456 789";console.log(text2.match(globalRegex));// ["123", "456", "789"]// Named capture groupsconstnameRegex=/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;constmatch=nameRegex.exec("2023-12-25");console.log(match.groups);// { year: "2023", month: "12", day: "25" }// Lookahead and lookbehindconstpositiveLookahead=/\d+(?=px)/;// Digits followed by "px"constnegativeLookahead=/\d+(?!px)/;// Digits not followed by "px"constpositiveLookbehind=/(?<=\$)\d+/;// Digits preceded by "$"constnegativeLookbehind=/(?<!\$)\d+/;// Digits not preceded by "$"
JSON
// JSON.stringifyconstobj={name: "John",age: 30,hobbies: ["reading","coding"],address: {city: "New York",zip: "10001"}};constjsonString=JSON.stringify(obj);console.log(jsonString);// JSON.stringify with replacer functionconstjsonWithReplacer=JSON.stringify(obj,(key,value)=>{if(key==='age')returnundefined;// Exclude agereturnvalue;});// JSON.stringify with space parameter (pretty print)constprettyJson=JSON.stringify(obj,null,2);// JSON.parseconstparsed=JSON.parse(jsonString);// JSON.parse with reviver functionconstparsedWithReviver=JSON.parse(jsonString,(key,value)=>{if(key==='age')returnvalue*2;// Transform agereturnvalue;});// Handling dates in JSONconstobjWithDate={name: "Event",date: newDate()};constjsonWithDate=JSON.stringify(objWithDate);constparsedWithDate=JSON.parse(jsonWithDate,(key,value)=>{if(key==='date')returnnewDate(value);returnvalue;});// Safe JSON parsingfunctionsafeJsonParse(str,defaultValue=null){try{returnJSON.parse(str);}catch(error){console.error('JSON parse error:',error);returndefaultValue;}}
Local Storage
// Storing datalocalStorage.setItem('username','john_doe');localStorage.setItem('preferences',JSON.stringify({theme: 'dark',language: 'en'}));// Retrieving dataconstusername=localStorage.getItem('username');constpreferences=JSON.parse(localStorage.getItem('preferences')||'{}');// Removing datalocalStorage.removeItem('username');localStorage.clear();// Clear all// Storage helper functionsconststorage={set(key,value){try{localStorage.setItem(key,JSON.stringify(value));}catch(error){console.error('Storage set error:',error);}},get(key,defaultValue=null){try{constitem=localStorage.getItem(key);returnitem ? JSON.parse(item) : defaultValue;}catch(error){console.error('Storage get error:',error);returndefaultValue;}},remove(key){localStorage.removeItem(key);},clear(){localStorage.clear();}};// Session storage (similar API, but session-scoped)sessionStorage.setItem('temp_data','temporary');consttempData=sessionStorage.getItem('temp_data');// Storage events (listen for changes across tabs)window.addEventListener('storage',(event)=>{console.log('Storage changed:',{key: event.key,oldValue: event.oldValue,newValue: event.newValue,url: event.url});});// Check storage availabilityfunctionisStorageAvailable(type){try{conststorage=window[type];constx='__storage_test__';storage.setItem(x,x);storage.removeItem(x);returntrue;}catch(e){returnfalse;}}console.log('localStorage available:',isStorageAvailable('localStorage'));console.log('sessionStorage available:',isStorageAvailable('sessionStorage'));
Higher-Order Functions
// Functions that take other functions as argumentsfunctionwithLogging(fn){returnfunction(...args){console.log(`Calling ${fn.name} with:`,args);constresult=fn.apply(this,args);console.log(`Result:`,result);returnresult;};}constadd=(a,b)=>a+b;constloggedAdd=withLogging(add);console.log(loggedAdd(3,4));// Logs function call and result// Memoizationfunctionmemoize(fn){constcache=newMap();returnfunction(...args){constkey=JSON.stringify(args);if(cache.has(key)){returncache.get(key);}constresult=fn.apply(this,args);cache.set(key,result);returnresult;};}constexpensiveFunction=memoize((n)=>{console.log(`Computing for ${n}`);returnn*n;});// Debouncingfunctiondebounce(fn,delay){lettimeoutId;returnfunction(...args){clearTimeout(timeoutId);timeoutId=setTimeout(()=>fn.apply(this,args),delay);};}constdebouncedSearch=debounce((query)=>{console.log('Searching for:',query);},300);// Throttlingfunctionthrottle(fn,limit){letinThrottle;returnfunction(...args){if(!inThrottle){fn.apply(this,args);inThrottle=true;setTimeout(()=>inThrottle=false,limit);}};}constthrottledScroll=throttle(()=>{console.log('Scroll event');},100);// Curryingfunctioncurry(fn){returnfunctioncurried(...args){if(args.length>=fn.length){returnfn.apply(this,args);}else{returnfunction(...nextArgs){returncurried.apply(this,args.concat(nextArgs));};}};}constmultiply=(a,b,c)=>a*b*c;constcurriedMultiply=curry(multiply);console.log(curriedMultiply(2)(3)(4));// 24// Partial applicationfunctionpartial(fn, ...presetArgs){returnfunction(...remainingArgs){returnfn(...presetArgs, ...remainingArgs);};}constgreet=(greeting,name)=>`${greeting}, ${name}!`;constsayHello=partial(greet,'Hello');console.log(sayHello('Alice'));// "Hello, Alice!"// Compositionfunctioncompose(...fns){returnfunction(value){returnfns.reduceRight((acc,fn)=>fn(acc),value);};}constaddOne=x=>x+1;constmultiplyByTwo=x=>x*2;constsquare=x=>x*x;constcomposedFn=compose(square,multiplyByTwo,addOne);console.log(composedFn(3));// ((3 + 1) * 2)^2 = 64
// Basic factory functionfunctioncreateUser(name,email,role='user'){return{
name,
email,
role,createdAt: newDate(),getInfo(){return`${this.name} (${this.email}) - ${this.role}`;},updateEmail(newEmail){this.email=newEmail;},hasPermission(permission){constpermissions={user: ['read'],admin: ['read','write','delete'],moderator: ['read','write']};returnpermissions[this.role]?.includes(permission)||false;}};}// Factory with private variables using closuresfunctioncreateBankAccount(initialBalance=0){letbalance=initialBalance;lettransactions=[];return{deposit(amount){if(amount>0){balance+=amount;transactions.push({type: 'deposit', amount,date: newDate()});returnbalance;}thrownewError('Amount must be positive');},withdraw(amount){if(amount>0&&amount<=balance){balance-=amount;transactions.push({type: 'withdrawal', amount,date: newDate()});returnbalance;}thrownewError('Invalid withdrawal amount');},getBalance(){returnbalance;},getTransactionHistory(){return[...transactions];// Return copy}};}// Factory with compositionfunctioncreateComponent(type){constbase={
type,id: Math.random().toString(36).substr(2,9),created: newDate(),render(){return`<${this.type} id="${this.id}"></${this.type}>`;}};// Add specific behavior based on typeconstbehaviors={button: {click(){console.log(`Button ${this.id} clicked`);}},input: {setValue(value){this.value=value;},getValue(){returnthis.value||'';}},modal: {show(){this.visible=true;},hide(){this.visible=false;}}};returnObject.assign(base,behaviors[type]||{});}constbutton=createComponent('button');constinput=createComponent('input');constmodal=createComponent('modal');
Observer Pattern
// Event Emitter/Observer implementationclassEventEmitter{constructor(){this.events={};}on(event,callback){if(!this.events[event]){this.events[event]=[];}this.events[event].push(callback);}off(event,callback){if(this.events[event]){this.events[event]=this.events[event].filter(cb=>cb!==callback);}}emit(event, ...args){if(this.events[event]){this.events[event].forEach(callback=>{try{callback(...args);}catch(error){console.error('Error in event callback:',error);}});}}once(event,callback){constonceCallback=(...args)=>{callback(...args);this.off(event,onceCallback);};this.on(event,onceCallback);}}// Usage exampleconstemitter=newEventEmitter();emitter.on('user:login',(user)=>{console.log(`User ${user.name} logged in`);});emitter.on('user:login',(user)=>{updateUI(user);});emitter.emit('user:login',{name: 'John',id: 123});// Observable pattern for state managementclassStore{constructor(initialState={}){this.state=initialState;this.observers=[];}subscribe(observer){this.observers.push(observer);return()=>{this.observers=this.observers.filter(obs=>obs!==observer);};}setState(newState){this.state={ ...this.state, ...newState};this.notify();}getState(){return{ ...this.state};}notify(){this.observers.forEach(observer=>{try{observer(this.state);}catch(error){console.error('Error in observer:',error);}});}}// Usageconststore=newStore({count: 0,user: null});constunsubscribe=store.subscribe((state)=>{console.log('State updated:',state);});store.setState({count: 1});store.setState({user: {name: 'Alice'}});
Performance Optimization
// Lazy loading with Intersection ObserverfunctioncreateLazyLoader(){constimageObserver=newIntersectionObserver((entries,observer)=>{entries.forEach(entry=>{if(entry.isIntersecting){constimg=entry.target;img.src=img.dataset.src;img.classList.remove('lazy');observer.unobserve(img);}});});return{observe(element){imageObserver.observe(element);}};}// Efficient DOM updates with DocumentFragmentfunctionefficientDOMUpdate(container,items){constfragment=document.createDocumentFragment();items.forEach(item=>{constelement=document.createElement('div');element.textContent=item.name;element.className='item';fragment.appendChild(element);});container.appendChild(fragment);}// Virtual scrolling for large listsclassVirtualList{constructor(container,items,itemHeight=50){this.container=container;this.items=items;this.itemHeight=itemHeight;this.viewportHeight=container.clientHeight;this.visibleCount=Math.ceil(this.viewportHeight/itemHeight)+1;this.setupScrolling();this.render();}setupScrolling(){this.container.addEventListener('scroll',this.onScroll.bind(this));}onScroll(){requestAnimationFrame(()=>this.render());}render(){constscrollTop=this.container.scrollTop;conststartIndex=Math.floor(scrollTop/this.itemHeight);constendIndex=Math.min(startIndex+this.visibleCount,this.items.length);this.container.innerHTML='';for(leti=startIndex;i<endIndex;i++){constitem=document.createElement('div');item.style.height=`${this.itemHeight}px`;item.style.transform=`translateY(${i*this.itemHeight}px)`;item.textContent=this.items[i];this.container.appendChild(item);}}}// Web Workers for heavy computationsfunctioncreateWorker(workerFunction){constblob=newBlob([` self.onmessage = function(e) { const result = (${workerFunction.toString()})(e.data); self.postMessage(result); } `],{type: 'application/javascript'});returnnewWorker(URL.createObjectURL(blob));}// Heavy computation functionfunctionheavyComputation(data){// Simulate heavy workletresult=0;for(leti=0;i<data.iterations;i++){result+=Math.sqrt(i);}returnresult;}// Usageconstworker=createWorker(heavyComputation);worker.postMessage({iterations: 1000000});worker.onmessage=(e)=>{console.log('Result from worker:',e.data);worker.terminate();};// Request Animation Frame for smooth animationsfunctionsmoothAnimation(element,from,to,duration=1000){conststartTime=performance.now();functionanimate(currentTime){constelapsed=currentTime-startTime;constprogress=Math.min(elapsed/duration,1);// Easing function (ease-out)consteased=1-Math.pow(1-progress,3);constcurrent=from+(to-from)*eased;element.style.transform=`translateX(${current}px)`;if(progress<1){requestAnimationFrame(animate);}}requestAnimationFrame(animate);}// Memory management and cleanupclassComponentManager{constructor(){this.components=newMap();this.cleanup=newMap();}create(id,component){this.components.set(id,component);// Store cleanup functionsconstcleanupFunctions=[];if(component.intervals){component.intervals.forEach(interval=>{cleanupFunctions.push(()=>clearInterval(interval));});}if(component.timeouts){component.timeouts.forEach(timeout=>{cleanupFunctions.push(()=>clearTimeout(timeout));});}if(component.listeners){component.listeners.forEach(({ element, event, handler })=>{cleanupFunctions.push(()=>element.removeEventListener(event,handler));});}this.cleanup.set(id,cleanupFunctions);}destroy(id){constcomponent=this.components.get(id);constcleanupFunctions=this.cleanup.get(id);if(cleanupFunctions){cleanupFunctions.forEach(cleanup=>cleanup());}this.components.delete(id);this.cleanup.delete(id);}destroyAll(){this.components.forEach((_,id)=>this.destroy(id));}}