Click ⭐ if you like the project. Pull Request are highly appreciated. Follow us on Facebook
// Returns a random number(float) between min (inclusive) and max (exclusive) constgetRandomNumber=(min,max)=>Math.random()*(max-min)+min;getRandomNumber(2,10)// Returns a random number(int) between min (inclusive) and max (inclusive)constgetRandomNumberInclusive=(min,max)=>{min=Math.ceil(min);max=Math.floor(max);returnMath.floor(Math.random()*(max-min+1))+min;}getRandomNumberInclusive(2,10);
constfirstArr=[5,2,1];constsecondArr=[1,2,3,4,5];constdiff=[ ...secondArr.filter(x=>!firstArr.includes(x)), ...firstArr.filter(x=>!secondArr.includes(x))];console.log('diff',diff)// [3, 4]functionarrayDiff(a,b){return[ ...a.filter(x=>b.indexOf(x)===-1), ...b.filter(x=>a.indexOf(x)===-1)]}console.log('arrayDiff',arrayDiff(firstArr,secondArr))// [3, 4]constdifference=(a,b)=>{constsetA=newSet(a);constsetB=newSet(b);return[ ...a.filter(x=>!setB.has(x)), ...b.filter(x=>!setA.has(x))]};difference(firstArr,secondArr);// [3, 4]console.log('difference',difference(firstArr,secondArr))
constmyVar=null;constmySecondVar=1;console.log(Boolean(myVar))// falseconsole.log(!!myVar)// falseconsole.log(Boolean(mySecondVar))// trueconsole.log(!!mySecondVar)// true
letaliens='';for(leti=0;i<6;i++){aliens+='👽'}//👽👽👽👽👽👽Array(6+1).join('👽')//👽👽👽👽👽👽'👽'.repeat(6)//👽👽👽👽👽👽
// The performance.now() method returns a DOMHighResTimeStamp, measured in milliseconds.// performance.now() is relative to page load and more precise in orders of magnitude. // Use cases include benchmarking and other cases where a high-resolution time is required // such as media (gaming, audio, video, // etc.)varstartTime=performance.now();doSomething();constendTime=performance.now();console.log("this doSomething took "+(endTime-startTime)+" milliseconds.");
// Mutating wayconstmuatatedArray=['a','b','c','d','e'];muatatedArray.splice(2,1)console.log(muatatedArray)// ['a', 'b', 'd', 'e']// Non-mutating wayconstnonMuatatedArray=['a','b','c','d','e'];constnewArray=nonMuatatedArray.filter((item,index)=>!(index===2));console.log(newArray)// ['a', 'b', 'd', 'e']
constmyArray=[2,3,[4,5],[7,7,[8,9,[1,1]]]];myArray.flat()// [2, 3, 4, 5, 7, 7, [8, 9, [1, 1]]]myArray.flat(1)// [2, 3, 4, 5, 7, 7, [8, 9, [1, 1]]]myArray.flat(2)// [2, 3, 4, 5, 7, 7, 8, 9, [1, 1]]// if you dont know the depth of the array you can use infinitymyArray.flat(infinity)// [2, 3, 4, 5, 7, 7, 8, 9, 1, 1];
constnumbers=[1,1,3,2,5,3,4,7,7,7,8];// Ex1constunieqNumbers=numbers.filter((v,i,a)=>a.indexOf(v)===i)console.log(unieqNumbers)// [1, 3, 2, 5, 4, 7, 8]// Ex2constunieqNumbers2=Array.from(newSet(numbers))console.log(unieqNumbers2)// [1, 3, 2, 5, 4, 7, 8]// Ex3constunieqNumbers3=[...newSet(numbers)]console.log(unieqNumbers3)// [1, 3, 2, 5, 4, 7, 8]// EX4 lodashconstunieqNumbers4=_.uniq(numbers)console.log(unieqNumbers4)// [1, 3, 2, 5, 4, 7, 8]
functioncopyToClipboard(){constcopyText=document.getElementById("myInput");copyText.select();document.execCommand("copy");}// new APIfunctioncopyToClipboard(){navigator.clipboard.writeText(document.querySelector('#myInput').value)}
constuser={id: 459,name: 'JS snippets',age:29,education:{degree: 'Masters'}}const{education : { degree }}=user;console.log(degree)// Masters
// The URLSearchParams interface defines utility methods to work with the query string of a URL.consturlParams=newURLSearchParams("?post=1234&action=edit");console.log(urlParams.has('post'));// trueconsole.log(urlParams.get('action'));// "edit"console.log(urlParams.getAll('action'));// ["edit"]console.log(urlParams.toString());// "?post=1234&action=edit"console.log(urlParams.append('active','1'));// "?post=1234&action=edit&active=1"
constmyFruits=['Apple','Orange','Mango','Banana','Apple','Apple','Mango']// first optionconstcountMyFruits=myFruits.reduce((countFruits,fruit)=>{countFruits[fruit]=(countFruits[fruit]||0)+1;returncountFruits},{})console.log(countMyFruits)// { Apple:3, Banana:1, Mango:2, Orange:1 }// seconf optionconstfruitsCounter={};for(constfruitofmyFruits){fruitsCounter[fruit]=fruitsCounter[fruit] ? fruitsCounter[fruit]+1 :1;}console.log(fruitsCounter)// { Apple:3, Banana:1, Mango:2, Orange:1 }
// There are cases where you want the destructured variable to have a different name than the property nameconstobj={name: "JSsnippets"};// Grabs obj.name as { pageName }const{name: pageName}=obj;// log our aliasconsole.log(pageName)// JSsnippets
Object.is('foo','foo');// trueObject.is(null,null);// trueObject.is(Nan,Nan);// true 😱constfoo={a: 1};constbar={a: 1};Object.is(foo,foo);// trueObject.is(foo,bar);// false
constobj={name: "JSsnippets",age:29,address:{street : 'JS'}};constfrozenObject=Object.freeze(obj);frozenObject.name='weLoveJS';// Uncaught TypeError// Although, we still can change a property’s value if it’s an object:frozenObject.address.street='React';// no error, new value is setdeletefrozenObject.name// Cannot delete property 'name' of #<Object>// We can check if an object is frozen by usingObject.isFrozen(obj)// true
constobj={name: "JSsnippets",age:29,};// Object.entries() method is used to return an array consisting of enumerable property //[key, value] pairs of the object which are passed as the parameter.for(let[key,value]ofObject.entries(obj)){console.log(`${key}: ${value}`)}// expected output:// "name: Jssnippets"// "age: 29"// order is not guaranteed
window.oncontextmenu=()=>{console.log('right click');returnfalse// cancel default menu}// orwindow.addEventListener('contextmenu',()=>{console.log('right click');returnfalse// cancel default menu},false)
// Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.<scriptsrc="myscript.js"></script>// With async (asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.// Async is more useful when you really don't care when the script loads and nothing else that is user dependent depends upon that script loading.(for scripts likes Google analytics)<scriptasyncsrc="myscript.js"></script> // With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. <scriptdefersrc="myscript.js"></script>
// an equality check against nullary values (e.g. null or undefined). Whenever the expression to the left of the ?? operator evaluates to either // undefined or null, the value defined to the right will be returned.constfoo=undefined??'default string';console.log(foo);// expected output: "default string"constage=0??30;console.log(age);// expected output: "0"
constcar={}constcarColor=car.name.colorconsole.log(carColor);// error- "Uncaught TypeError: Cannot read property 'carColor' of undefined // In JavaScript, you can first check if an object exists, and then try to get one of its properties, like this:constcarColor=car&&car.name&&car.name.color;console.log(carColor);// undefined- no error// Now this new optional chaining operator will let us be even more fancy:constnewCarColor=car?.name?.color;console.log(newCarColor)// undefined- no error// You can use this syntax today using @babel/plugin-proposal-optional-chaining
/* Accessing the global property in JavaScript has always posed some difficulty. This is because different platforms have different ways to access it. Client-side JavaScript uses window or self Node.js uses global Web workers use self The globalThis property provides a standard way of accessing the global 'this' value across environments. you can access the global object in a consistent manner without having to know which environment the code is being run in.*/console.log(globalThis)// get the global this depends on your environment
constuser={id: 459,name: 'JS snippets',age:29,education:{degree: 'Masters'}}JSON.stringify(user,[name,age],2)/*returns{ "name": "JS snippets", "age": 29}*/
constel=document.getElementById("btn");functionmyClickHandler(){console.log('this click will only fire once')}el.addEventListener('click',myClickHandler,{once: true,});
constspan=document.querySelector("span");letclasses=span.classList;span.addEventListener("click",function(){letresult=classes.toggle("active");if(result){console.log("active class was added");}else{console.log("active class was removed");}});
functionisJson(str){try{JSON.parse(str);}catch(e){// the json is not okreturnfalse;}// the json is okreturntrue;}
// getBoundingClientRect provides you with important pieces of data about an// HTML element’s size and positioning.constbodyBounderies=document.body.getBoundingClientRect();// => {// top: Number,// left: Number,// right: Number,// bottom: Number,// x: Number,// y: Number,// width: Number,// height: Number,// }
bonus: add/remove animation depending if an image is in the viewport https://codepen.io/JSsnippets/pen/PoqrjEY
constimage=document.querySelector('.animate-me');observer=newIntersectionObserver((entries)=>{const[myImg]=entries;if(myImg.intersectionRatio>0){myImg.target.classList.add('fancy');}else{myImg.target.classList.remove('fancy');}});observer.observe(image);
see our codepen: https://codepen.io/JSsnippets/pen/dyYoYVX
constfoo=document.getElementById("foo");constobserver=newResizeObserver((entries)=>{for(letentryofentries){constcr=entry.contentRect;console.log=`Size: ${cr.width}px X ${cr.height}px`;}});observer.observe(foo);
play/pause video accordingly see our codepen: https://codepen.io/JSsnippets/pen/gOapPzq
constvideo=document.getElementById("my-video");constonVisibilitychange=()=>{returndocument.hidden ? video.pause() : video.play();}document.addEventListener("visibilitychange",onVisibilitychange)
classStudents{ #name;constructor(){this.#name ="JS snippets";} #privateMethod(){return'Come and learn Js with us';}getPrivateMessage(){returnthis.#privateMethod();}}constinstance=newSomething();console.log(instance.name);//=> undefinedconsole.log(instance.privateMethod);//=> undefinedconsole.log(instance.getPrivateMessage());//=> Come and learn Js with us
see our codepen: https://codepen.io/JSsnippets/pen/qBbyMoJ
constpasteBox=document.getElementById("paste-no-event");pasteBox.onpaste=(e)=>{e.preventDefault();returnfalse;};
The void operator evaluates the given expression and then returns undefined.
void0;// returns undefinedvoid(0);// returns undefinedvoid{};// returns undefinedvoid "JSsnippets; // returns undefined void(0);// returns undefinedvoid(2=='2');// returns undefinedvoidanyfunction();// returns undefined
the method string.replaceAll(search, replaceWith) replaces all appearances of search string with replaceWith.
conststr='this is a JSsnippets example';constupdatedStr=str.replace('example','snippet');// 'this is a JSsnippets snippet'Thetrickypartisthatreplacemethodreplacesonlytheveryfirstmatchofthesubstringwehave passed: conststr='this is a JSsnippets example and examples are great';constupdatedStr=str.replace('example','snippet');//'this is a JSsnippets snippet and examples are great'Inordertogothroughthis,weneedtouseaglobalregexpinstead: conststr='this is a JSsnippets example and examples are great';constupdatedStr=str.replace(/example/g,'snippet');//'this is a JSsnippets snippet and snippets are greatr'butnowwehavenewfriendintown,replaceAllconststr='this is a JSsnippets example and examples are great';constupdatedStr=str.replaceAll('example','snippet');//'this is a JSsnippets snippet and snippets are greatr'
Expanding on the default parameter technique, we can mark a parameter as mandatory
constisRequired=()=>{thrownewError('This is a mandatory parameter.');}constgetPage=(pageName='Jssnippets',url=isRequired())=>{return`${pageName}${url}`;}console.log(getPage());// In the above code, url will be undefined and that will try to set the default value for it which is the isRequired() function. It will throw an error as,// Uncaught error: This is a mandatory parameter.// at isRequired
<inputtype="number"id="JSsnippets"onkeyup="checkMyType(event)"/>functioncheckMyType(event){console.log(typeofevent.target.value)// stringconsole.log(typeofevent.target.valueAsNumber)// number}
constarr=["a","b","c","d","e"]constreduceArray=arr.reduce((acc,current)=>{returnacc+current},"")// return abcdeconstreduceRightArray=arr.reduceRight((acc,current)=>{returnacc+current},"")// return edcba
<!-- HTML --><buttonid="download">Download</button><buttonid="abort">Abort</button><!-- JS --><scripttype="text/javascript">letcontroller;document.querySelector('#download').addEventListener('click',()=>{controller=newAbortController();constsignal=controller.signal;fetch('https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4',{signal}).then(()=>console.log('done'));});document.querySelector('#abort').addEventListener('click',function(){controller.abort();});</script>
conststate=[{userId: 1,name: "JSSnippets",isOwner: false,},{userId: 2,name: "React",isOwner: false,},{userId: 3,name: "Vue",isOwner: false,},{userId: 4,name: "Angular",isOwner: false,},];constnewState=state.map((obj)=>obj.name==="JSSnippets" ? { ...obj,isOwner: true} : obj);
100_000_000===100000000// true300_000===300000// true
Calling this method on an empty array will return true for any condition!
constarr=[]constresult=arr.every(x=>x==5)console.log(result)// true
constJSarr=[['name','JSsnippets'],['address','worldwide'],['year','2018'],['followers','15000']];constobj=Object.fromEntries(JSarr);//{// "name": "JSsnippets",// "address": "worldwide",// "year": "2018",// "followers": "15000"//}
conststartSpeaking=()=>{letmsg=document.getElementById("text-to-speech").value;letspeech=newSpeechSynthesisUtterance();speech.lang="en-US";speech.text=msg;speech.volume=1;speech.rate=1;speech.pitch=1;window.speechSynthesis.speak(speech);}
Warning: Floating point numbers cannot represent all decimals precisely in binary. This can lead to unexpected results, such as 0.1 + 0.2 === 0.3 returning false .
123.678.toFixed()// Returns '124'123.678.toFixed(1)// Returns '123.7': Note rounding2.35.toFixed(1)// Returns '2.4'. Note it rounds up2.65.toFixed(1)// Returns '2.6'. Note it rounds down -why??? see the warning above
The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
crypto.randomUUID()// print in console '460ff1e6-2106-4848-833d-5c5b3bfdc943'crypto.randomUUID()// print in console '9a91c014-d1b1-453a-8091-ef8b9b48b14a'
If you want to deep clone a value in Node.js, you no longer need to use a library or the JSON.parse(JSON.stringify(value)) hack. You can use the new global function structuredClone()
constuser={name: "JS Snippets",address: {street: "Original Road",city: "Placeshire"},};constclonedUser=structuredClone(user);clonedUser.address.street="New Road";console.log("user.address.street:",user.address.street);// > Original Roadconsole.log("clonedUser.address.street:",clonedUser.address.street);// > New Road
Browsers expose a global variable named screen, which we’ll use to access the information we need.
functiongetOrientation(){constisPortrait=screen.orientation.type.startswith('portrait')returnisPortrait ? 'portrait' : 'landscape'}
const | Let | Var | |
---|---|---|---|
Can be Reassigned? | ❌ | ✅ | ✅ |
Can be Redeclared? | ❌ | ❌ | ✅ |
Block Scope | ✅ | ✅ | ❌ |
Function Scope | ✅ | ✅ | ✅ |
Stored in Global Scope | ❌ | ❌ | ✅ |
Array.prototype.slice=function(start=0,end=this.length,step=1){constresult=[];conststepCount=step<0 ? step*-1 : step;constendPoint=end>this.length ? this.length : end;for(leti=start;i<endPoint;i+=stepCount){result.push(this[i]);}if(step<0){result.reverse();}returnresult;};constarray=[0,1,2,3,4,5,6,7,8,9];console.log(array.slice(1,9));// [1, 2, 3, 4, 5, 6, 7, 8]console.log(array.slice(1));// [1, 2, 3, 4, 5, 6, 7, 8, 9]console.log(array.slice(1,9,2));// [1, 3, 5, 7]console.log(array.slice(1,9,-2));// [7, 5, 3, 1]
// Three quick steps to shuffle an array in Javascript: Map to a random number, sort on that and map the object back! constshuffleArray=anArray=>anArray.map(a=>[Math.random(),a]).sort((a,b)=>a[0]-b[0]).map(a=>a[1]);console.log(shuffleArray([1,2,3,4,5,6,7,8,9,10]))// [4, 6, 8, 7, 9, 10, 1, 2, 3, 5]
Math.max.apply(null,[1,2,10,3])// 10
constmostFrequent=arr=>Object.entries(arr.reduce((a,v)=>{a[v]=a[v] ? a[v]+1 : 1;returna;},{})).reduce((a,v)=>(v[1]>=a[1] ? v : a),[null,0])[0];console.log(mostFrequent([1,2,4,2,5]));// 2