# JavaScript-snippets > Click :star:if you like the project. Pull Request are highly appreciated. Follow us on [Facebook](https://www.facebook.com/snippetsJS) ### Table of Contents | No. | Questions | |---- | --------- |1 | [Generate a random number in a given range](#How-to-generate-a-random-number-in-a-given-range) | |2 | [Find the difference between two arrays](#How-to-find-the-difference-between-two-arrays)| |3 | [Convert truthy/falsy to boolean(true/false)](#Convert-truthy-falsy-to-boolean)| |4 | [Repeat a string](#Repeat-a-string)| |5 | [Check how long an operation takes](#Check-how-long-an-operation-takes)| |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)| |7 | [Did you know you can flat an array?](#Did-you-know-you-can-flat-an-array)| |8 | [Get unique values in an array](#Get-unique-values-in-an-array)| |9 | [Copy Text to Clipboard](#Copy-Text-to-Clipboard)| |10 | [Nested Destructuring](#Nested-Destructuring)| |11 | [URLSearchParams](#URLSearchParams)| |12 | [Count elements in an array](#Count-elements-in-an-array)| |13 | [Aliases with JavaScript Destructuring](#Aliases-with-JavaScript-Destructuring)| |14 | [The Object.is() method determines whether two values are the same value](#the-objectis-method-determines-whether-two-values-are-the-same-value)| |15 | [Freeze an object](#Freeze-an-object)| |16 | [Printing Object keys and values](#Printing-Object-keys-and-values)| |17 | [Capture the right click event](#Capture-the-right-click-event)| |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)| |19 | [Nullish coalescing operator](#Nullish-coalescing-operator)| |20 | [Optional chaining](#Optional-chaining)| |21 | [globalThis](#globalThis)| |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)| |23 | [Fire an event listener only once.](#Fire-an-event-listener-only-once)| |24 | [Vanilla JS toggle](#Vanilla-JS-toggle)| |25 | [Check if a string is a valid JSON](#Check-if-a-string-is-a-valid-JSON)| |26 | [getBoundingClientRect](#getBoundingClientRect)| |27 | [Check if a node is in the viewport](#Check-if-a-node-is-in-the-viewport)| |28 | [Notify when element size is changed](#Notify-when-element-size-is-changed)| |29 | [Detect if Browser Tab is in the view](#Detect-if-Browser-Tab-is-in-the-view)| |30 | [Private class methods and fields](#Private-class-methods-and-fields)| |31 | [Preventing paste into an input field](#Preventing-paste-into-an-input-field)| |32 | [The void operator](#The-void-operator)| |33 | [replaceAll](#replaceAll)| |34 | [Required Function Params](#Required-Function-Params)| |35 | [Get input value as a number](#Get-input-value-as-a-number)| **[⬠Back to Top](#table-of-contents)** ### How to generate a random number in a given range ```javascript // 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); ``` **[⬠Back to Top](#table-of-contents)** ### How to find the difference between two arrays ```javascript 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)) ``` **[⬠Back to Top](#table-of-contents)** ### Convert truthy falsy to boolean ```javascript const myVar = null; const mySecondVar = 1; console.log( Boolean(myVar) ) // false console.log( !!myVar ) // false console.log( Boolean(mySecondVar) ) // true console.log( !!mySecondVar ) // true ``` **[⬠Back to Top](#table-of-contents)** ### Repeat a string ```javascript let aliens = ''; for(let i = 0 ; i < 6 ; i++){ aliens += 'ð½' } //ð½ð½ð½ð½ð½ð½ Array(6).join('ð½') //ð½ð½ð½ð½ð½ð½ 'ð½'.repeat(6) //ð½ð½ð½ð½ð½ð½ ``` **[⬠Back to Top](#table-of-contents)** ### Check how long an operation takes ```javascript //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."); ``` **[⬠Back to Top](#table-of-contents)** ### Two ways to remove an item in a specific in an array ```javascript //Mutating way const muatatedArray = ['a','b','c','d','e']; muatatedArray.splice(2,1) console.log(muatatedArray) //['a','b','d','e'] //Non-mutating way const nonMuatatedArray = ['a','b','c','d','e']; const newArray = nonMuatatedArray.filter((item, index) => !( index === 2 )); console.log(newArray) //['a','b','d','e'] ``` **[⬠Back to Top](#table-of-contents)** ### Did you know you can flat an array ```javascript 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 infinity myArray.flat(infinity) // [2, 3, 4, 5 ,7,7, 8, 9, 1, 1]; ``` **[⬠Back to Top](#table-of-contents)** ### Get unique values in an array ```javascript const numbers = [1,1,3,2,5,3,4,7,7,7,8]; //Ex1 const unieqNumbers = numbers.filter((v,i,a) => a.indexOf(v )=== i ) console.log(unieqNumbers) //[1,3,2,5,4,7,8] //Ex2 const unieqNumbers2 = Array.from(new Set(numbers)) console.log(unieqNumbers2) //[1,3,2,5,4,7,8] //Ex3 const unieqNumbers3 = [...new Set(numbers)] console.log(unieqNumbers3) //[1,3,2,5,4,7,8] //EX4 lodash const unieqNumbers4 = _.uniq(numbers) console.log(unieqNumbers4) //[1,3,2,5,4,7,8] ``` **[⬠Back to Top](#table-of-contents)** ### Copy Text to Clipboard ```javascript function copyToClipboard() { const copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); } //new API function copyToClipboard(){ navigator.clipboard.writeText(document.querySelector('#myInput').value) } ``` **[⬠Back to Top](#table-of-contents)** ### Nested Destructuring ```javascript const user = { id: 459, name: 'JS snippets', age:29, education:{ degree: 'Masters' } } const { education : { degree } } = user; console.log(degree) //Masters ``` **[⬠Back to Top](#table-of-contents)** ### URLSearchParams ```javascript //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')); // true console.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" ``` **[⬠Back to Top](#table-of-contents)** ### Count elements in an array ```javascript const myFruits = ['Apple','Orange','Mango','Banana','Apple','Apple','Mango'] //first option const 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 } ``` **[⬠Back to Top](#table-of-contents)** ### Aliases with JavaScript Destructuring ```javascript //There are cases where you want the destructured variable to have a different name than the property name const obj = { name: "JSsnippets" }; // Grabs obj.name as { pageName } const { name: pageName } = obj; //log our alias console.log(pageName) // JSsnippets ``` **[⬠Back to Top](#table-of-contents)** ### The Object.is() method determines whether two values are the same value ```javascript Object.is('foo', 'foo'); // true Object.is(null, null); // true Object.is(Nan, Nan); // true ð± const foo = { a: 1 }; const bar = { a: 1 }; Object.is(foo, foo); // true Object.is(foo, bar); // false ``` **[⬠Back to Top](#table-of-contents)** ### Freeze an object ```javascript const 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 set delete frozenObject.name // Cannot delete property 'name' of #