diff --git a/README.md b/README.md index 3428dc4..dcd01f3 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # JavaScript-snippets -> Click :star:if you like the project. Pull Request are highly appreciated. Follow us on [Facebook](https://www.facebook.com/snippetsJS) +> 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 | @@ -35,8 +35,22 @@ |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)| +|36 | [reduceRight](#reduceRight)| +|37 | [Abort Fetch](#Abort-Fetch)| +|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)| +|39 | [Numeric separators allow us to improve our code readability](#Numeric-separators-allow-us-to-improve-our-code-readability)| +|40 | [pay attention when using every](#pay-attention-when-using-every)| +|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)| +|42 | [Native text to speech JS](#Native-text-to-speech-JS)| +|43 | [toFixed](#toFixed)| +|44 | [generate randomUUID](#generate-random-uuid)| +|45 | [structuredClone](#structuredClone)| +|46 | [get device orientation](#get-device-orientation)| +|47 | [CONST vs LET vs VAR](#const-let-var)| **[⬆ Back to Top](#table-of-contents)** ### How to generate a random number in a given range @@ -658,5 +672,336 @@ pasteBox.onpaste = (e) => { ``` +**[⬆ Back to Top](#table-of-contents)** +### The void operator +The void operator evaluates the given expression and then returns undefined. +```javascript + + +void 0; //returns undefined +void (0); //returns undefined +void {}; //returns undefined +void "JSsnippets; //returns undefined +void (0); //returns undefined +void (2 == '2'); //returns undefined +void anyfunction(); //returns undefined + +``` + + +**[⬆ Back to Top](#table-of-contents)** +### replaceAll +the method string.replaceAll(search, replaceWith) replaces all appearances of search string with replaceWith. +```javascript + + +const str = 'this is a JSsnippets example'; + +const updatedStr = str.replace('example', 'snippet'); // 'this is a JSsnippets snippet' + + +The tricky part is that replace method replaces only the very first match of the substring we have passed: + + +const str = 'this is a JSsnippets example and examples are great'; + +const updatedStr = str.replace('example', 'snippet'); //'this is a JSsnippets snippet and examples are great' + +In order to go through this, we need to use a global regexp instead: + + +const str = 'this is a JSsnippets example and examples are great'; + +const updatedStr = str.replace(/example/g, 'snippet'); //'this is a JSsnippets snippet and snippets are greatr' + +but now we have new friend in town, replaceAll + +const str = 'this is a JSsnippets example and examples are great'; + +const updatedStr = str.replaceAll('example', 'snippet'); //'this is a JSsnippets snippet and snippets are greatr' + +``` + + +**[⬆ Back to Top](#table-of-contents)** +### Required Function Params +Expanding on the default parameter technique, we can mark a parameter as mandatory + +```javascript +const isRequired = () => { + throw new Error( 'This is a mandatory parameter.' ); +} + + +const getPage = ( 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 + +``` + + + + +**[⬆ Back to Top](#table-of-contents)** +### Get input value as a number + +```javascript + + + +function checkMyType(event){ + + console.log(typeof event.target.value) // string + console.log(typeof event.target.valueAsNumber ) // number + +} + + +``` +**[⬆ Back to Top](#table-of-contents)** +### reduceRight + +```javascript + +const arr = ["a", "b", "c", "d", "e"] + +const reduceArray = arr.reduce((acc, current) => { + return acc + current +}, "") +//return abcde + +const reduceRightArray = arr.reduceRight((acc, current) => { + return acc + current +}, "") +//return edcba + +``` + + +**[⬆ Back to Top](#table-of-contents)** +### Abort Fetch + +```javascript + + +//HTML + + + +//JS +let controller; + +document.querySelector('#download').addEventListener('click', () => { + controller = new AbortController(); + const signal = 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(); +}); + +``` + + +**[⬆ Back to Top](#table-of-contents)** +### How to change the value of an object which is inside an array + +```javascript + +const state = [ + { + userId: 1, + name: "JSSnippets", + isOwner: false, + }, + { + userId: 2, + name: "React", + isOwner: false, + }, + { + userId: 3, + name: "Vue", + isOwner: false, + }, + { + userId: 4, + name: "Angular", + isOwner: false, + }, +]; + +const newState = state.map((obj) => + obj.name === "JSSnippets" ? { ...obj, isOwner: true } : obj +); + +``` + +**[⬆ Back to Top](#table-of-contents)** +### Numeric separators allow us to improve our code readability + +```javascript + +100_000_000 === 100000000 // true + +300_000 === 300000 //true + +``` + + + + + +**[⬆ Back to Top](#table-of-contents)** +### pay attention when using every + +Calling this method on an empty array will return true for any condition! + + +```javascript + +const arr = [] +const result = arr.every(x=> x==5) +console.log(result) //true + +``` + + + + + +**[⬆ Back to Top](#table-of-contents)** +### How to convert an array of key-value tuples into an object + + +```javascript + +const JSarr = [ + ['name', 'JSsnippets'], + ['address', 'worldwide'], + ['year', '2018'], + ['followers', '15000'] + +]; + +const obj = Object.fromEntries(JSarr); +//{ +// "name": "JSsnippets", +// "address": "worldwide", +// "year": "2018", +// "followers": "15000" +//} +``` + +**[⬆ Back to Top](#table-of-contents)** +### Native text to speech JS + + +```javascript + +const startSpeaking=()=>{ + + let msg = document.getElementById("text-to-speech").value; + let speech = new SpeechSynthesisUtterance(); + + speech.lang = "en-US"; + speech.text = msg; + speech.volume = 1; + speech.rate = 1; + speech.pitch = 1; + + window.speechSynthesis.speak(speech); +} + + +``` + +**[⬆ Back to Top](#table-of-contents)** +### toFixed + +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 . + +```javascript + +123.678.toFixed() // Returns '124' +123.678.toFixed(1) // Returns '123.7': Note rounding + +2.35.toFixed(1) // Returns '2.4'. Note it rounds up +2.65.toFixed(1) // Returns '2.6'. Note it rounds down -why??? see the warning above + +``` + + +**[⬆ Back to Top](#table-of-contents)** +### generate random uuid + +The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. + +```javascript + +crypto.randomUUID() // print in console '460ff1e6-2106-4848-833d-5c5b3bfdc943' + +crypto.randomUUID() // print in console '9a91c014-d1b1-453a-8091-ef8b9b48b14a' + + +``` + + +**[⬆ Back to Top](#table-of-contents)** +### structuredClone + +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() + +```javascript + +const user = { + name: "JS Snippets", + address: { street: "Original Road", city: "Placeshire" }, +}; + +const clonedUser = structuredClone(user); + +clonedUser.address.street = "New Road"; + +console.log("user.address.street:", user.address.street); +// > Original Road + +console.log("clonedUser.address.street:", clonedUser.address.street); +// > New Road + + +``` + +**[⬆ Back to Top](#table-of-contents)** +### get device orientation + +Browsers expose a global variable named screen, which we’ll use to access the information we need. +```javascript +function getOrientation() { + const isPortrait = screen.orientation.type.startswith('portrait') + return isPortrait ? 'portrait' : 'landscape' +} + +``` + +**[⬆ Back to Top](#table-of-contents)** +### CONST vs LET vs VAR + +| | const | Let | Var | +|------------------------|-------|-----|-----| +| Can be Reaasigned? | :x: | :white_check_mark: |:white_check_mark: | +| Cab be Redeclared? | :x: | :x: | :white_check_mark: | +| Block Scope | :white_check_mark: |:white_check_mark: | :x: | +| Function Scope | :white_check_mark: | :white_check_mark: | :white_check_mark: | +| Stored in Global Scope | :x: | :x: | :white_check_mark: |
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: