forked fromroeib/JavaScript-snippets
- Notifications
You must be signed in to change notification settings - Fork0
A collection of useful JavaScript snippets
NotificationsYou must be signed in to change notification settings
adi-works/JavaScript-snippets
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Find us onFacebook.
// 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
// first optionletaliens='';for(leti=0;i<6;i++){aliens+='👽';}// 👽👽👽👽👽👽// second optionArray(6).join('👽');// 👽👽👽👽👽👽// third option'👽'.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(`operation took${endTime-startTime} milliseconds.`);
// Mutating wayconstmutatedArray=['a','b','c','d','e'];mutatedArray.splice(2,1);console.log(mutatedArray);// ['a','b','d','e']// Non-mutating wayconstnonMutatedArray=['a','b','c','d','e'];constnewArray=nonMutatedArray.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 don't 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];// first optionconstuniqNumbers=numbers.filter((value,index,array)=>array.indexOf(value)===i);console.log(uniqNumbers);// [1,3,2,5,4,7,8]// second optionconstuniqNumbers2=Array.from(newSet(numbers));console.log(uniqNumbers2);// [1,3,2,5,4,7,8]// third optionconstuniqNumbers3=[...newSet(numbers)];console.log(uniqNumbers3);// [1,3,2,5,4,7,8]// forth option (using lodash)constuniqNumbers4=_.uniq(numbers);console.log(uniqNumbers4);// [1,3,2,5,4,7,8]
// old APIfunctioncopyToClipboard(){constcopyText=document.getElementById('myInput');copyText.select();document.execCommand('copy');}// new APIfunctioncopyToClipboard(){navigator.clipboard.writeText(document.getElementById('myInput'));}
constuser={id:459,name:'JS snippets',age:29,education:{degree:'Masters'}};const{education:{ degree}}=user;console.log(degree);// Masters
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"
constlist=[1,2,3,4,5,6,7,8,9];constshuffle=list.sort(predicate);functionpredicate(a,b){return0.5-Math.random();}console.log(shuffle);
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 }// second 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 properties// [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="script.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="script.js"></script>// With defer, browser will run your script when the page// finished parsing. (not necessary finishing downloading all image files.<scriptdefersrc="script.js"></script>
// an equality check against nil 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.color;console.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
About
A collection of useful JavaScript snippets
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
No releases published
Packages0
No packages published
Languages
- JavaScript89.5%
- HTML6.5%
- CSS4.0%
