forked fromroeib/JavaScript-snippets
- Notifications
You must be signed in to change notification settings - Fork0
Short JavaScript code snippets
License
NotificationsYou must be signed in to change notification settings
HammadAli-WD/JavaScript-snippets
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Click ⭐if you like the project. Pull Request are highly appreciated. Follow us onFacebook
// Returns a random number(float) between min (inclusive) and max (exclusive) const getRandomNumber = (min, max) => Math.random() * (max - min) + min;getRandomNumber(2, 10) // Returns a random number(int) between min (inclusive) and max (inclusive)const getRandomNumberInclusive =(min, max)=> { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min;}getRandomNumberInclusive(2, 10);const firstArr = [5, 2, 1];const secondArr = [1, 2, 3, 4, 5];const diff = [ ...secondArr.filter(x => !firstArr.includes(x)), ...firstArr.filter(x => !secondArr.includes(x))];console.log('diff',diff) //[3,4]function arrayDiff(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]const difference = (a, b) => { const setA = new Set(a); const setB = new Set(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))const myVar = null; const mySecondVar = 1; console.log( Boolean(myVar) ) // falseconsole.log( !!myVar ) // falseconsole.log( Boolean(mySecondVar) ) // trueconsole.log( !!mySecondVar ) // truelet aliens = '';for(let i = 0 ; i < 6 ; i++){ aliens += '👽'}//👽👽👽👽👽👽Array(6).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.)var startTime = performance.now();doSomething();const endTime = performance.now();console.log("this doSomething took " + (endTime - startTime) + " milliseconds.");//Mutating wayconst muatatedArray = ['a','b','c','d','e'];muatatedArray.splice(2,1)console.log(muatatedArray) //['a','b','d','e']//Non-mutating wayconst nonMuatatedArray = ['a','b','c','d','e'];const newArray = nonMuatatedArray.filter((item, index) => !( index === 2 ));console.log(newArray) //['a','b','d','e']const myArray = [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];const numbers = [1,1,3,2,5,3,4,7,7,7,8];//Ex1const unieqNumbers = numbers.filter((v,i,a) => a.indexOf(v )=== i )console.log(unieqNumbers) //[1,3,2,5,4,7,8]//Ex2const unieqNumbers2 = Array.from(new Set(numbers))console.log(unieqNumbers2) //[1,3,2,5,4,7,8]//Ex3const unieqNumbers3 = [...new Set(numbers)]console.log(unieqNumbers3) //[1,3,2,5,4,7,8]//EX4 lodashconst unieqNumbers4 = _.uniq(numbers)console.log(unieqNumbers4) //[1,3,2,5,4,7,8]function copyToClipboard() { const copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); }//new APIfunction copyToClipboard(){ navigator.clipboard.writeText(document.querySelector('#myInput').value)}const user = { 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.const urlParams = new URLSearchParams("?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"const myFruits = ['Apple','Orange','Mango','Banana','Apple','Apple','Mango']//first optionconst countMyFruits = myFruits.reduce((countFruits,fruit) => { countFruits[fruit] = ( countFruits[fruit] || 0 ) +1; return countFruits },{} ) console.log(countMyFruits) // { Apple:3, Banana:1, Mango:2, Orange:1 } //seconf option const fruitsCounter = {}; for( const fruit of myFruits ){ 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 nameconst obj = { name: "JSsnippets"};// Grabs obj.name as { pageName }const { name: pageName } = obj;//log our aliasconsole.log(pageName) // JSsnippetsObject.is('foo', 'foo'); // trueObject.is(null, null); // trueObject.is(Nan, Nan); // true 😱const foo = { a: 1 };const bar = { a: 1 };Object.is(foo, foo); // trueObject.is(foo, bar); // falseconst obj = { name: "JSsnippets", age:29, address:{ street : 'JS'}};const frozenObject = 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 setdelete frozenObject.name // Cannot delete property 'name' of #<Object>//We can check if an object is frozen by usingObject.isFrozen(obj) //trueconst obj = { 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] of Object.entries(obj)){ console.log(`${key}: ${value}`)}//expected output:// "name: Jssnippets"// "age: 29"// order is not guaranteedwindow.oncontextmenu = () => {console.log('right click');return false // cancel default menu}//orwindow.addEventListener('contextmenu', ()=>{console.log('right click');return false // cancel default menu},false)//Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.<script src="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)<script async src="myscript.js"></script>//With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. <script defer src="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.const foo = undefined ?? 'default string';console.log(foo);// expected output: "default string"const age = 0 ?? 30;console.log(age);// expected output: "0"const car = {}const carColor = 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:const carColor = 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:const newCarColor = car?.name?.color;console.log(newCarColor) //undefined- no error//You can use this syntax today using @babel/plugin-proposal-optional-chainingAccessing 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 selfNode.js uses globalWeb workers use selfThe 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 environmentconst user = { id: 459, name: 'JS snippets', age:29, education:{ degree: 'Masters' }}JSON.stringify(user,[name,age], 2)/*returns{ "name": "JS snippets", "age": 29}*/const el = document.getElementById("btn");function myClickHandler(){ console.log('this click will only fire once')}el.addEventListener('click', myClickHandler, { once: true,});const span = document.querySelector("span");let classes = span.classList;span.addEventListener("click", function() { let result = classes.toggle("active"); if (result) { console.log("active class was added"); } else { console.log("active class was removed"); }});function isJson(str) { try { JSON.parse(str); } catch (e) { //the json is not ok return false; } //the json is ok return true;}//getBoundingClientRect provides you with important pieces of data about an//HTML element’s size and positioning.const bodyBounderies = 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 viewporthttps://codepen.io/JSsnippets/pen/PoqrjEY
const image = document.querySelector('.animate-me');observer = new IntersectionObserver((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
const foo = document.getElementById("foo");const observer = new ResizeObserver((entries) => { for (let entry of entries) { const cr = entry.contentRect; console.log = `Size: ${cr.width}px X ${cr.height}px`; }});observer.observe(foo);play/pause video accordinglysee our codepen:https://codepen.io/JSsnippets/pen/gOapPzq
const video = document.getElementById("my-video");const onVisibilitychange =()=>{ return document.hidden ? video.pause() : video.play();} document.addEventListener("visibilitychange", onVisibilitychange)class Students { #name; constructor(){ this.#name = "JS snippets"; } #privateMethod() { return 'Come and learn Js with us'; } getPrivateMessage() { return this.#privateMethod(); }}const instance = new Something();console.log(instance.name); //=> undefinedconsole.log(instance.privateMethod); //=> undefinedconsole.log(instance.getPrivateMessage()); //=> Come and learn Js with ussee our codepen:https://codepen.io/JSsnippets/pen/qBbyMoJ
const pasteBox = document.getElementById("paste-no-event");pasteBox.onpaste = (e) => { e.preventDefault(); return false;};About
Short JavaScript code snippets
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
No releases published
Packages0
No packages published