{"id":14155502,"url":"https://github.com/roeib/JavaScript-snippets","last_synced_at":"2025-08-06T01:31:39.742Z","repository":{"id":35464189,"uuid":"214877603","full_name":"roeib/JavaScript-snippets","owner":"roeib","description":"Short JavaScript code snippets","archived":false,"fork":false,"pushed_at":"2024-07-28T19:07:23.000Z","size":109,"stargazers_count":616,"open_issues_count":9,"forks_count":130,"subscribers_count":54,"default_branch":"master","last_synced_at":"2024-08-17T08:05:28.037Z","etag":null,"topics":["es6-javascript","interview-questions","javascript-snippets","js","nodejs","snippets"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/roeib.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-10-13T19:06:46.000Z","updated_at":"2024-08-17T08:05:32.241Z","dependencies_parsed_at":"2024-08-17T08:16:45.218Z","dependency_job_id":null,"html_url":"https://github.com/roeib/JavaScript-snippets","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/roeib%2FJavaScript-snippets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/roeib%2FJavaScript-snippets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/roeib%2FJavaScript-snippets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/roeib%2FJavaScript-snippets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/roeib","download_url":"https://codeload.github.com/roeib/JavaScript-snippets/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228821405,"owners_count":17977166,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["es6-javascript","interview-questions","javascript-snippets","js","nodejs","snippets"],"created_at":"2024-08-17T08:03:41.448Z","updated_at":"2024-12-09T02:31:25.525Z","avatar_url":"https://github.com/roeib.png","language":null,"readme":"# JavaScript-snippets\n\u003e Click :star:  if you like the project. Pull Request are highly appreciated. Follow us on [Facebook](https://www.facebook.com/snippetsJS)\n\n### Table of Contents\n| No. | Questions |\n|---- | ---------\n|1  | [Generate a random number in a given range](#How-to-generate-a-random-number-in-a-given-range) |\n|2  | [Find the difference between two arrays](#How-to-find-the-difference-between-two-arrays)|\n|3  | [Convert truthy/falsy to boolean(true/false)](#Convert-truthy-falsy-to-boolean)|\n|4  | [Repeat a string](#Repeat-a-string)|\n|5  | [Check how long an operation takes](#Check-how-long-an-operation-takes)|\n|6  | [Two ways to remove an item in a specific in an array](#Two-ways-to-remove-an-item-in-a-specific-in-an-array)|\n|7  | [Did you know you can flat an array?](#Did-you-know-you-can-flat-an-array)|\n|8  | [Get unique values in an array](#Get-unique-values-in-an-array)|\n|9  | [Copy Text to Clipboard](#Copy-Text-to-Clipboard)|\n|10 | [Nested Destructuring](#Nested-Destructuring)|\n|11 | [URLSearchParams](#URLSearchParams)|\n|12 | [Count elements in an array](#Count-elements-in-an-array)|\n|13 | [Aliases with JavaScript Destructuring](#Aliases-with-JavaScript-Destructuring)|\n|14 | [The Object.is() method determines whether two values are the same value](#the-objectis-method-determines-whether-two-values-are-the-same-value)|\n|15 | [Freeze an object](#Freeze-an-object)|\n|16 | [Printing Object keys and values](#Printing-Object-keys-and-values)|\n|17 | [Capture the right click event](#Capture-the-right-click-event)|\n|18 | [In HTML5, you can tell the browser when to run your JavaScript code](#in-html5-you-can-tell-the-browser-when-to-run-your-javascript-code)|\n|19 | [Nullish coalescing operator](#Nullish-coalescing-operator)|\n|20 | [Optional chaining](#Optional-chaining)|\n|21 | [globalThis](#globalThis)|\n|22 | [The second argument of JSON.stringify lets you cherry-pick 🍒 keys to serialize.](#the-second-argument-of-jsonstringify-lets-you-cherry-pick--keys-to-serialize)|\n|23 | [Fire an event listener only once.](#Fire-an-event-listener-only-once)|\n|24 | [Vanilla JS toggle](#Vanilla-JS-toggle)|\n|25 | [Check if a string is a valid JSON](#Check-if-a-string-is-a-valid-JSON)|\n|26 | [getBoundingClientRect](#getBoundingClientRect)|\n|27 | [Check if a node is in the viewport](#Check-if-a-node-is-in-the-viewport)|\n|28 | [Notify when element size is changed](#Notify-when-element-size-is-changed)|\n|29 | [Detect if Browser Tab is in the view](#Detect-if-Browser-Tab-is-in-the-view)|\n|30 | [Private class methods and fields](#Private-class-methods-and-fields)|\n|31 | [Preventing paste into an input field](#Preventing-paste-into-an-input-field)|\n|32 | [The void operator](#The-void-operator)|\n|33 | [replaceAll](#replaceAll)|\n|34 | [Required Function Params](#Required-Function-Params)|\n|35 | [Get input value as a number](#Get-input-value-as-a-number)|\n|36 | [reduceRight](#reduceRight)|\n|37 | [Abort Fetch](#Abort-Fetch)|\n|38 | [How to change the value of an object which is inside an array](#How-to-change-the-value-of-an-object-which-is-inside-an-array)|\n|39 | [Numeric separators allow us to improve our code readability](#Numeric-separators-allow-us-to-improve-our-code-readability)|\n|40 | [pay attention when using every](#pay-attention-when-using-every)|\n|41 | [How to convert an array of key-value tuples into an object](#How-to-convert-an-array-of-key-value-tuples-into-an-object)|\n|42 | [Native text to speech JS](#Native-text-to-speech-JS)|\n|43 | [toFixed](#toFixed)|\n|44 | [generate randomUUID](#generate-random-uuid)|\n|45 | [structuredClone](#structuredClone)|\n|46 | [get device orientation](#get-device-orientation)|\n|47 | [CONST vs LET vs VAR](#const-let-var)|\n\n**[⬆ Back to Top](#table-of-contents)**\n### How to generate a random number in a given range\n```javascript\n// Returns a random number(float) between min (inclusive) and max (exclusive) \n\nconst getRandomNumber = (min, max) =\u003e Math.random() * (max - min) + min;\n\ngetRandomNumber(2, 10)\n\n // Returns a random number(int) between min (inclusive) and max (inclusive)\n\nconst getRandomNumberInclusive =(min, max)=\u003e {\n    min = Math.ceil(min);\n    max = Math.floor(max);\n    return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\ngetRandomNumberInclusive(2, 10);\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### How to find the difference between two arrays\n\n```javascript\nconst firstArr = [5, 2, 1];\nconst secondArr = [1, 2, 3, 4, 5];\n\nconst diff = [\n    ...secondArr.filter(x =\u003e !firstArr.includes(x)),\t\t\t\t\t\n    ...firstArr.filter(x =\u003e !secondArr.includes(x))\n];\nconsole.log('diff',diff) //[3,4]\n\n\nfunction arrayDiff(a, b) {\n    return [\n        ...a.filter(x =\u003e b.indexOf(x) === -1),\n        ...b.filter(x =\u003e a.indexOf(x) === -1)\n    ]\n}\nconsole.log('arrayDiff',arrayDiff(firstArr, secondArr)) //[3,4]\n\n\n\n\nconst difference = (a, b) =\u003e {\n    const setA = new Set(a);\n    const setB = new Set(b);\n\n    return [\n        ...a.filter(x =\u003e !setB.has(x)),\n        ...b.filter(x =\u003e !setA.has(x))\n\n    ]\n};\n\ndifference(firstArr, secondArr); //[3,4]\nconsole.log('difference',difference(firstArr, secondArr))\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### Convert truthy falsy to boolean\n\n```javascript\nconst myVar = null; \nconst mySecondVar = 1; \n\nconsole.log( Boolean(myVar) ) // false\nconsole.log( !!myVar ) // false\n\n\nconsole.log( Boolean(mySecondVar) ) // true\nconsole.log( !!mySecondVar ) // true\n```\n**[⬆ Back to Top](#table-of-contents)**\n### Repeat a string\n```javascript\n\nlet aliens = '';\n\nfor(let i = 0 ; i \u003c 6 ; i++){\n aliens += '👽'\n}\n//👽👽👽👽👽👽\n\nArray(6).join('👽')\n//👽👽👽👽👽👽\n\n\n'👽'.repeat(6)\n//👽👽👽👽👽👽\n\n```\n**[⬆ Back to Top](#table-of-contents)**\n### Check how long an operation takes\n```javascript\n//The performance.now() method returns a DOMHighResTimeStamp, measured in milliseconds.\n//performance.now() is relative to page load and more precise in orders of magnitude. \n//Use cases include benchmarking and other cases where a high-resolution time is required \n//such as media (gaming, audio, video, //etc.)\n\nvar startTime = performance.now();\ndoSomething();\nconst endTime = performance.now();\nconsole.log(\"this doSomething took \" + (endTime - startTime) + \" milliseconds.\");\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### Two ways to remove an item in a specific in an array\n\n```javascript\n//Mutating way\nconst muatatedArray = ['a','b','c','d','e'];\nmuatatedArray.splice(2,1)\nconsole.log(muatatedArray) //['a','b','d','e']\n\n//Non-mutating way\nconst nonMuatatedArray = ['a','b','c','d','e'];\nconst newArray = nonMuatatedArray.filter((item, index) =\u003e !( index === 2 ));\nconsole.log(newArray) //['a','b','d','e']\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### Did you know you can flat an array\n\n```javascript\nconst myArray = [2, 3, [4, 5],[7,7, [8, 9, [1, 1]]]];\n\nmyArray.flat() // [2, 3, 4, 5 ,7,7, [8, 9, [1, 1]]]\n\nmyArray.flat(1) // [2, 3, 4, 5 ,7,7, [8, 9, [1, 1]]]\n\nmyArray.flat(2) // [2, 3, 4, 5 ,7,7, 8, 9, [1, 1]]\n\n//if you dont know the depth of the array you can use infinity\nmyArray.flat(infinity) // [2, 3, 4, 5 ,7,7, 8, 9, 1, 1];\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### Get unique values in an array\n\n```javascript\nconst numbers = [1,1,3,2,5,3,4,7,7,7,8];\n\n//Ex1\nconst unieqNumbers = numbers.filter((v,i,a) =\u003e a.indexOf(v )=== i )\nconsole.log(unieqNumbers) //[1,3,2,5,4,7,8]\n\n//Ex2\nconst unieqNumbers2 = Array.from(new Set(numbers))\nconsole.log(unieqNumbers2) //[1,3,2,5,4,7,8]\n\n//Ex3\nconst unieqNumbers3 = [...new Set(numbers)]\nconsole.log(unieqNumbers3) //[1,3,2,5,4,7,8]\n\n//EX4 lodash\nconst unieqNumbers4 = _.uniq(numbers)\nconsole.log(unieqNumbers4) //[1,3,2,5,4,7,8]\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### Copy Text to Clipboard\n\n\n```javascript\nfunction copyToClipboard() {\n\n  const copyText = document.getElementById(\"myInput\");\n  copyText.select();\n  document.execCommand(\"copy\");\n  \n}\n//new API\nfunction copyToClipboard(){\n navigator.clipboard.writeText(document.querySelector('#myInput').value)\n}\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###  Nested Destructuring\n\n\n```javascript\nconst user = {\n id: 459,\n name: 'JS snippets',\n age:29,\n education:{\n  degree: 'Masters'\n }\n}\n\nconst { education : { degree } } = user;\nconsole.log(degree) //Masters\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###  URLSearchParams \n\n\n```javascript\n//The URLSearchParams interface defines utility methods to work with the query string of a URL.\n\nconst urlParams = new URLSearchParams(\"?post=1234\u0026action=edit\");\n\nconsole.log(urlParams.has('post')); // true\nconsole.log(urlParams.get('action')); // \"edit\"\nconsole.log(urlParams.getAll('action')); // [\"edit\"]\nconsole.log(urlParams.toString()); // \"?post=1234\u0026action=edit\"\nconsole.log(urlParams.append('active', '1')); // \"?post=1234\u0026action=edit\u0026active=1\"\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###  Count elements in an array\n\n\n```javascript\nconst myFruits = ['Apple','Orange','Mango','Banana','Apple','Apple','Mango']\n\n//first option\nconst countMyFruits = myFruits.reduce((countFruits,fruit) =\u003e {\n  countFruits[fruit] = ( countFruits[fruit] || 0 ) +1;\n  return countFruits\n },{} )\n console.log(countMyFruits)\n // { Apple:3, Banana:1, Mango:2, Orange:1 }\n \n //seconf option\n const fruitsCounter = {};\n \n for( const fruit of myFruits ){\n   fruitsCounter[fruit] = fruitsCounter[fruit] ? fruitsCounter[fruit]+1 :1;\n }\n  \n console.log(fruitsCounter)\n // { Apple:3, Banana:1, Mango:2, Orange:1 }\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###  Aliases with JavaScript Destructuring\n\n\n```javascript\n\n//There are cases where you want the destructured variable to have a different name than the property name\n\nconst obj = { \n  name: \"JSsnippets\"\t\t\t\t\t\t\t\t\t\t\t\t\t\n};\n\n\n// Grabs obj.name as { pageName }\nconst { name: pageName } = obj;\n\n//log our alias\nconsole.log(pageName) // JSsnippets\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n###  The Object.is() method determines whether two values are the same value\n\n\n```javascript\nObject.is('foo', 'foo');     // true\n\nObject.is(null, null);       // true\n\nObject.is(Nan, Nan);       // true 😱\n\nconst foo = { a: 1 };\nconst bar = { a: 1 };\nObject.is(foo, foo);         // true\nObject.is(foo, bar);         // false\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n###  Freeze an object\n\n\n```javascript\nconst obj = { \n  name: \"JSsnippets\",\n  age:29,\n  address:{\n\t  street : 'JS'\n\t}\n};\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\nconst frozenObject = Object.freeze(obj);\n\nfrozenObject.name = 'weLoveJS'; // Uncaught TypeError\n\n//Although, we still can change a property’s value if it’s an object:\n\nfrozenObject.address.street = 'React'; // no error, new value is set\n\n\ndelete frozenObject.name // Cannot delete property 'name' of #\u003cObject\u003e\n\n\n//We can check if an object is frozen by using\nObject.isFrozen(obj) //true\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###  Printing Object keys and values\n\n\n```javascript\nconst obj = { \n  name: \"JSsnippets\",\n  age:29,\n};\n\n//Object.entries() method is used to return an array consisting of enumerable property \n//[key, value] pairs of the object which are passed as the parameter.\n\nfor(let [key,value] of Object.entries(obj)){\n   console.log(`${key}: ${value}`)\n}\n\n//expected output:\n// \"name: Jssnippets\"\n// \"age: 29\"\n// order is not guaranteed\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###  Capture the right click event\n\n```javascript\nwindow.oncontextmenu = () =\u003e {\n\tconsole.log('right click');\n\treturn false // cancel default menu\n}\n//or\n\nwindow.addEventListener('contextmenu', ()=\u003e{\n\tconsole.log('right click');\n\treturn false // cancel default menu\n},false)\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###  In HTML5, you can tell the browser when to run your JavaScript code\n```javascript\n\n//Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.\n\u003cscript src=\"myscript.js\"\u003e\u003c/script\u003e\n\n//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.\n//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)\n\u003cscript async src=\"myscript.js\"\u003e\u003c/script\u003e\n\n//With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. \n\u003cscript defer src=\"myscript.js\"\u003e\u003c/script\u003e\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###   Nullish coalescing operator\n```javascript\n\n// 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.\n\nconst foo = undefined ?? 'default string';\nconsole.log(foo);\n// expected output: \"default string\"\n\n\nconst age = 0 ?? 30;\nconsole.log(age);\n// expected output: \"0\"\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###  Optional chaining\n```javascript\n\nconst car = {}\nconst carColor = car.name.color\nconsole.log(carColor);\n// error- \"Uncaught TypeError: Cannot read property 'carColor' of undefined\t\t\n\n//In JavaScript, you can first check if an object exists, and then try to get one of its properties, like this:\nconst carColor = car \u0026\u0026 car.name \u0026\u0026 car.name.color;\nconsole.log(carColor);\n//undefined- no error\n\n\n//Now this new optional chaining operator will let us be even more fancy:\n\nconst newCarColor = car?.name?.color;\nconsole.log(newCarColor) \n//undefined- no error\n\t\t\t\t\t\n//You can use this syntax today using @babel/plugin-proposal-optional-chaining\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###  globalThis\n```javascript\nAccessing the global property in JavaScript has always posed some difficulty. This is because \ndifferent platforms have different ways to access it.\n\nClient-side JavaScript uses window or self\n\nNode.js uses global\n\nWeb workers use self\n\nThe 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. \n\nconsole.log(globalThis) //get the global this depends on your environment\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n#  The second argument of JSON.stringify lets you cherry-pick 🍒 keys to serialize.\n```javascript\nconst user = {\n id: 459,\n name: 'JS snippets',\n age:29,\n education:{\n  degree: 'Masters'\n }\n}\n\nJSON.stringify(user,[name,age], 2)\t\t\t\t\t\t\n\n/*\nreturns\n\n{\n  \"name\": \"JS snippets\",\n  \"age\": 29\n}\n\n\n*/\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n###  Fire an event listener only once\n```javascript\nconst el = document.getElementById(\"btn\");\n\nfunction myClickHandler(){\n  console.log('this click will only fire once')\n}\n\n\nel.addEventListener('click', myClickHandler, {\n  once: true,\n});\n\n```\n**[⬆ Back to Top](#table-of-contents)**\n###  Vanilla JS toggle\n```javascript\nconst span = document.querySelector(\"span\");\nlet classes = span.classList;\n\nspan.addEventListener(\"click\", function() {\n  let result = classes.toggle(\"active\");\n\n  if (result) {\n    console.log(\"active class was added\");\n  } else {\n    console.log(\"active class was removed\");\n  }\n});\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### Check if a string is a valid JSON\n\n```javascript\nfunction isJson(str) {\n    try {\n        JSON.parse(str);\n    } catch (e) {\n      //the json is  not ok\n        return false;\n    }\n    //the json is ok\n    return true;\t\t\t\t\t\t\t\t\t\n}\n```\n**[⬆ Back to Top](#table-of-contents)**\n### getBoundingClientRect\n\n```javascript\n//getBoundingClientRect provides you with important pieces of data about an\n//HTML element’s size and positioning.\n\nconst bodyBounderies = document.body.getBoundingClientRect();\n// =\u003e  {\n//       top: Number,\n//       left: Number,\n//       right: Number,\n//       bottom: Number,\n//       x: Number,\n//       y: Number,\n//       width: Number,\n//       height: Number,\n//     }\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### Check if a node is in the viewport\nbonus: add/remove animation depending if an image is in the viewport\nhttps://codepen.io/JSsnippets/pen/PoqrjEY\n```javascript\nconst image = document.querySelector('.animate-me');\n\nobserver = new IntersectionObserver((entries) =\u003e {\n  const [ myImg ] = entries;\n    if (myImg.intersectionRatio \u003e 0) {\n      myImg.target.classList.add('fancy');\n    } else {\n      myImg.target.classList.remove('fancy');\n    }\n});\n\n\nobserver.observe(image);\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### Notify when element size is changed \nsee our codepen: https://codepen.io/JSsnippets/pen/dyYoYVX\n```javascript\nconst foo = document.getElementById(\"foo\");\n\nconst observer = new ResizeObserver((entries) =\u003e {\n  for (let entry of entries) {\n    const cr = entry.contentRect;\n    console.log = `Size: ${cr.width}px X ${cr.height}px`;\n  }\n});\nobserver.observe(foo);\n\n```\n**[⬆ Back to Top](#table-of-contents)**\n### Detect if Browser Tab is in the view\nplay/pause video accordingly\nsee our codepen: https://codepen.io/JSsnippets/pen/gOapPzq\n```javascript\n\n\nconst video =  document.getElementById(\"my-video\");\n\nconst onVisibilitychange =()=\u003e{\n   return document.hidden \n     ? video.pause() \n     : video.play();\n} \n\ndocument.addEventListener(\"visibilitychange\", onVisibilitychange)\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### Private class methods and fields\n```javascript\n\nclass Students {\n  #name;\n\n  constructor(){\n    this.#name = \"JS snippets\";\n  }\n\n  #privateMethod() {\n    return 'Come and learn Js with us';\n  }\n\n  getPrivateMessage() {\n      return this.#privateMethod();\n  }\n}\n\nconst instance = new Something();\nconsole.log(instance.name); //=\u003e undefined\nconsole.log(instance.privateMethod); //=\u003e undefined\nconsole.log(instance.getPrivateMessage()); //=\u003e Come and learn Js with us\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### Preventing paste into an input field\nsee our codepen: https://codepen.io/JSsnippets/pen/qBbyMoJ\n\n```javascript\n\nconst pasteBox = document.getElementById(\"paste-no-event\");\npasteBox.onpaste = (e) =\u003e {\n  e.preventDefault();\n  return false;\n};\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### The void operator \nThe void operator evaluates the given expression and then returns undefined.\n```javascript\n\n\nvoid 0;  \t\t//returns undefined\nvoid (0); \t\t//returns undefined\nvoid {}; \t\t//returns undefined\nvoid \"JSsnippets; \t//returns undefined\nvoid (0); \t\t//returns undefined\nvoid (2 == '2'); \t//returns undefined\nvoid anyfunction(); \t//returns undefined\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### replaceAll \nthe method string.replaceAll(search, replaceWith) replaces all appearances of search string with replaceWith.\n```javascript\n\n\nconst str = 'this is a JSsnippets example';\n\nconst updatedStr = str.replace('example', 'snippet'); // 'this is a  JSsnippets snippet'\n\n\nThe tricky part is that replace method replaces only the very first match of the substring we have passed:\n\n\nconst str = 'this is a JSsnippets example and examples are great';\n\nconst updatedStr = str.replace('example', 'snippet'); //'this is a JSsnippets snippet and examples are great'\n\nIn order to go through this, we need to use a global regexp instead:\n\n\nconst str = 'this is a JSsnippets example and examples are great';\n\nconst updatedStr = str.replace(/example/g, 'snippet'); //'this is a JSsnippets snippet and snippets are greatr'\n\nbut now we have new friend in town, replaceAll\n\nconst str = 'this is a JSsnippets example and examples are great';\n\nconst updatedStr = str.replaceAll('example', 'snippet'); //'this is a JSsnippets snippet and snippets are greatr'\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### Required Function Params \nExpanding on the default parameter technique, we can mark a parameter as mandatory\n\n```javascript\nconst isRequired = () =\u003e {\n    throw new Error( 'This is a mandatory parameter.' );\n}\n\n\nconst getPage = ( pageName = 'Jssnippets', url = isRequired() ) =\u003e {\n    return `${pageName} ${url}`;\n}\n\nconsole.log(getPage());\n\n//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,\n\n//Uncaught error: This is a mandatory parameter.\n//at isRequired\n\n```\n\n\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### Get input value as a number\n\n```javascript\n\n\u003cinput type=\"number\" id=\"JSsnippets\" onkeyup=\"checkMyType(event)\" /\u003e\n\nfunction checkMyType(event){\n  \n  console.log(typeof event.target.value) // string\n  console.log(typeof event.target.valueAsNumber ) // number\n\n}\n\n\n```\n**[⬆ Back to Top](#table-of-contents)**\n### reduceRight\n\n```javascript\n\nconst arr = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n\nconst reduceArray = arr.reduce((acc, current) =\u003e {\n    return acc + current\n}, \"\")\n//return abcde\n\nconst reduceRightArray = arr.reduceRight((acc, current) =\u003e {\n    return acc + current\n}, \"\")\n//return edcba\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### Abort Fetch\n\n```javascript\n\n\n//HTML\n\u003cbutton id=\"download\"\u003eDownload\u003c/button\u003e\n\u003cbutton id=\"abort\"\u003eAbort\u003c/button\u003e\n\n//JS\nlet controller;\n\ndocument.querySelector('#download').addEventListener('click', () =\u003e {\n  controller = new AbortController();\n  const signal = controller.signal;\n  fetch('https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4', {signal})\n    .then(() =\u003e console.log('done'));\n});\n\ndocument.querySelector('#abort').addEventListener('click', function() {\n  controller.abort();\n});\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### How to change the value of an object which is inside an array\n\n```javascript\n\nconst state = [\n  {\n    userId: 1,\n    name: \"JSSnippets\",\n    isOwner: false,\n  },\n  {\n    userId: 2,\n    name: \"React\",\n    isOwner: false,\n  },\n  {\n    userId: 3,\n    name: \"Vue\",\n    isOwner: false,\n  },\n  {\n    userId: 4,\n    name: \"Angular\",\n    isOwner: false,\n  },\n];\n\nconst newState = state.map((obj) =\u003e\n  obj.name === \"JSSnippets\" ? { ...obj, isOwner: true } : obj\t\t\t\n);\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### Numeric separators allow us to improve our code readability\n\n```javascript\n\n100_000_000 === 100000000 // true\n\n300_000 === 300000 //true\n\n```\n\n\n\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### pay attention when using every\n\nCalling this method on an empty array will return true for any condition!\n\n\n```javascript\n\nconst arr = []\nconst result = arr.every(x=\u003e x==5)\nconsole.log(result) //true\n\n```\n\n\n\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### How to convert an array of key-value tuples into an object\n\n\n```javascript\n\nconst JSarr = [\n    ['name', 'JSsnippets'],\n    ['address', 'worldwide'],\n    ['year', '2018'],\n    ['followers', '15000']\n\n];\n\nconst obj = Object.fromEntries(JSarr);\n//{\n//  \"name\": \"JSsnippets\",\n// \"address\": \"worldwide\",\n//  \"year\": \"2018\",\n//  \"followers\": \"15000\"\n//}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### Native text to speech JS\n\n\n```javascript\n\nconst startSpeaking=()=\u003e{\n\n\tlet msg = document.getElementById(\"text-to-speech\").value;\n\tlet speech = new SpeechSynthesisUtterance();\n\t\n\tspeech.lang = \"en-US\";\n\tspeech.text = msg;\n\tspeech.volume = 1;\n\tspeech.rate = 1;\n\tspeech.pitch = 1;\n\n\twindow.speechSynthesis.speak(speech);\n}\n\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### toFixed\n\nWarning: 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 .\n\n```javascript\n\n123.678.toFixed()       // Returns '124'\n123.678.toFixed(1)      // Returns '123.7': Note rounding\n\n2.35.toFixed(1)        // Returns '2.4'. Note it rounds up\n2.65.toFixed(1)        // Returns '2.6'. Note it rounds down -why??? see the warning above\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### generate random uuid\n\nThe randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.\n\n```javascript\n\ncrypto.randomUUID() // print in console '460ff1e6-2106-4848-833d-5c5b3bfdc943'\n\ncrypto.randomUUID() // print in console '9a91c014-d1b1-453a-8091-ef8b9b48b14a'\n\n\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n### structuredClone\n\nIf 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()\n\n```javascript\n\nconst user = {\n  name: \"JS Snippets\",\n  address: { street: \"Original Road\", city: \"Placeshire\" },\n};\n\nconst clonedUser = structuredClone(user);\n\nclonedUser.address.street = \"New Road\";\n\nconsole.log(\"user.address.street:\", user.address.street);\n// \u003e Original Road\n\nconsole.log(\"clonedUser.address.street:\", clonedUser.address.street);\n// \u003e New Road\n\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### get device orientation\n\nBrowsers expose a global variable named screen, which we’ll use to access the information we need.\n\n```javascript\n\nfunction getOrientation() {  \n    const isPortrait = screen.orientation.type.startswith('portrait')  \n    return isPortrait ? 'portrait' : 'landscape'\n}\n\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n### CONST vs LET vs VAR\n\n|                        | const | Let | Var |\n|------------------------|-------|-----|-----|\n| Can be Reaasigned?     | :x:     | :white_check_mark:   |:white_check_mark:   |\n| Cab be Redeclared?     | :x:    | :x:  | :white_check_mark:  |\n| Block Scope            | :white_check_mark:    |:white_check_mark:   | :x:   |\n| Function Scope         | :white_check_mark:     | :white_check_mark:   | :white_check_mark:   |\n| Stored in Global Scope | :x:     | :x:   | :white_check_mark:   |\n","funding_links":[],"categories":["nodejs"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Froeib%2FJavaScript-snippets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Froeib%2FJavaScript-snippets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Froeib%2FJavaScript-snippets/lists"}