diff --git a/README.md b/README.md index 160449f..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 | @@ -37,8 +37,20 @@ |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 @@ -711,8 +723,285 @@ const updatedStr = str.replaceAll('example', 'snippet'); //'this is a JSsnippets ``` +**[⬆ 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: |