├── Logo.png ├── LICENSE └── README.md /Logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roeib/JavaScript-snippets/HEAD/Logo.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 JS snippets 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JavaScript-snippets 2 | > Click :star: if you like the project. Pull Request are highly appreciated. Follow us on [Facebook](https://www.facebook.com/snippetsJS) 3 | 4 | ### Table of Contents 5 | | No. | Questions | 6 | |---- | --------- 7 | |1 | [Generate a random number in a given range](#How-to-generate-a-random-number-in-a-given-range) | 8 | |2 | [Find the difference between two arrays](#How-to-find-the-difference-between-two-arrays)| 9 | |3 | [Convert truthy/falsy to boolean(true/false)](#Convert-truthy-falsy-to-boolean)| 10 | |4 | [Repeat a string](#Repeat-a-string)| 11 | |5 | [Check how long an operation takes](#Check-how-long-an-operation-takes)| 12 | |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)| 13 | |7 | [Did you know you can flat an array?](#Did-you-know-you-can-flat-an-array)| 14 | |8 | [Get unique values in an array](#Get-unique-values-in-an-array)| 15 | |9 | [Copy Text to Clipboard](#Copy-Text-to-Clipboard)| 16 | |10 | [Nested Destructuring](#Nested-Destructuring)| 17 | |11 | [URLSearchParams](#URLSearchParams)| 18 | |12 | [Count elements in an array](#Count-elements-in-an-array)| 19 | |13 | [Aliases with JavaScript Destructuring](#Aliases-with-JavaScript-Destructuring)| 20 | |14 | [The Object.is() method determines whether two values are the same value](#the-objectis-method-determines-whether-two-values-are-the-same-value)| 21 | |15 | [Freeze an object](#Freeze-an-object)| 22 | |16 | [Printing Object keys and values](#Printing-Object-keys-and-values)| 23 | |17 | [Capture the right click event](#Capture-the-right-click-event)| 24 | |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)| 25 | |19 | [Nullish coalescing operator](#Nullish-coalescing-operator)| 26 | |20 | [Optional chaining](#Optional-chaining)| 27 | |21 | [globalThis](#globalThis)| 28 | |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)| 29 | |23 | [Fire an event listener only once.](#Fire-an-event-listener-only-once)| 30 | |24 | [Vanilla JS toggle](#Vanilla-JS-toggle)| 31 | |25 | [Check if a string is a valid JSON](#Check-if-a-string-is-a-valid-JSON)| 32 | |26 | [getBoundingClientRect](#getBoundingClientRect)| 33 | |27 | [Check if a node is in the viewport](#Check-if-a-node-is-in-the-viewport)| 34 | |28 | [Notify when element size is changed](#Notify-when-element-size-is-changed)| 35 | |29 | [Detect if Browser Tab is in the view](#Detect-if-Browser-Tab-is-in-the-view)| 36 | |30 | [Private class methods and fields](#Private-class-methods-and-fields)| 37 | |31 | [Preventing paste into an input field](#Preventing-paste-into-an-input-field)| 38 | |32 | [The void operator](#The-void-operator)| 39 | |33 | [replaceAll](#replaceAll)| 40 | |34 | [Required Function Params](#Required-Function-Params)| 41 | |35 | [Get input value as a number](#Get-input-value-as-a-number)| 42 | |36 | [reduceRight](#reduceRight)| 43 | |37 | [Abort Fetch](#Abort-Fetch)| 44 | |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)| 45 | |39 | [Numeric separators allow us to improve our code readability](#Numeric-separators-allow-us-to-improve-our-code-readability)| 46 | |40 | [pay attention when using every](#pay-attention-when-using-every)| 47 | |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)| 48 | |42 | [Native text to speech JS](#Native-text-to-speech-JS)| 49 | |43 | [toFixed](#toFixed)| 50 | |44 | [generate randomUUID](#generate-random-uuid)| 51 | |45 | [structuredClone](#structuredClone)| 52 | |46 | [get device orientation](#get-device-orientation)| 53 | |47 | [CONST vs LET vs VAR](#const-let-var)| 54 | 55 | **[⬆ Back to Top](#table-of-contents)** 56 | ### How to generate a random number in a given range 57 | ```javascript 58 | // Returns a random number(float) between min (inclusive) and max (exclusive) 59 | 60 | const getRandomNumber = (min, max) => Math.random() * (max - min) + min; 61 | 62 | getRandomNumber(2, 10) 63 | 64 | // Returns a random number(int) between min (inclusive) and max (inclusive) 65 | 66 | const getRandomNumberInclusive =(min, max)=> { 67 | min = Math.ceil(min); 68 | max = Math.floor(max); 69 | return Math.floor(Math.random() * (max - min + 1)) + min; 70 | } 71 | 72 | getRandomNumberInclusive(2, 10); 73 | ``` 74 | 75 | **[⬆ Back to Top](#table-of-contents)** 76 | ### How to find the difference between two arrays 77 | 78 | ```javascript 79 | const firstArr = [5, 2, 1]; 80 | const secondArr = [1, 2, 3, 4, 5]; 81 | 82 | const diff = [ 83 | ...secondArr.filter(x => !firstArr.includes(x)), 84 | ...firstArr.filter(x => !secondArr.includes(x)) 85 | ]; 86 | console.log('diff',diff) //[3,4] 87 | 88 | 89 | function arrayDiff(a, b) { 90 | return [ 91 | ...a.filter(x => b.indexOf(x) === -1), 92 | ...b.filter(x => a.indexOf(x) === -1) 93 | ] 94 | } 95 | console.log('arrayDiff',arrayDiff(firstArr, secondArr)) //[3,4] 96 | 97 | 98 | 99 | 100 | const difference = (a, b) => { 101 | const setA = new Set(a); 102 | const setB = new Set(b); 103 | 104 | return [ 105 | ...a.filter(x => !setB.has(x)), 106 | ...b.filter(x => !setA.has(x)) 107 | 108 | ] 109 | }; 110 | 111 | difference(firstArr, secondArr); //[3,4] 112 | console.log('difference',difference(firstArr, secondArr)) 113 | ``` 114 | 115 | **[⬆ Back to Top](#table-of-contents)** 116 | ### Convert truthy falsy to boolean 117 | 118 | ```javascript 119 | const myVar = null; 120 | const mySecondVar = 1; 121 | 122 | console.log( Boolean(myVar) ) // false 123 | console.log( !!myVar ) // false 124 | 125 | 126 | console.log( Boolean(mySecondVar) ) // true 127 | console.log( !!mySecondVar ) // true 128 | ``` 129 | **[⬆ Back to Top](#table-of-contents)** 130 | ### Repeat a string 131 | ```javascript 132 | 133 | let aliens = ''; 134 | 135 | for(let i = 0 ; i < 6 ; i++){ 136 | aliens += '👽' 137 | } 138 | //👽👽👽👽👽👽 139 | 140 | Array(6).join('👽') 141 | //👽👽👽👽👽👽 142 | 143 | 144 | '👽'.repeat(6) 145 | //👽👽👽👽👽👽 146 | 147 | ``` 148 | **[⬆ Back to Top](#table-of-contents)** 149 | ### Check how long an operation takes 150 | ```javascript 151 | //The performance.now() method returns a DOMHighResTimeStamp, measured in milliseconds. 152 | //performance.now() is relative to page load and more precise in orders of magnitude. 153 | //Use cases include benchmarking and other cases where a high-resolution time is required 154 | //such as media (gaming, audio, video, //etc.) 155 | 156 | var startTime = performance.now(); 157 | doSomething(); 158 | const endTime = performance.now(); 159 | console.log("this doSomething took " + (endTime - startTime) + " milliseconds."); 160 | ``` 161 | 162 | **[⬆ Back to Top](#table-of-contents)** 163 | ### Two ways to remove an item in a specific in an array 164 | 165 | ```javascript 166 | //Mutating way 167 | const muatatedArray = ['a','b','c','d','e']; 168 | muatatedArray.splice(2,1) 169 | console.log(muatatedArray) //['a','b','d','e'] 170 | 171 | //Non-mutating way 172 | const nonMuatatedArray = ['a','b','c','d','e']; 173 | const newArray = nonMuatatedArray.filter((item, index) => !( index === 2 )); 174 | console.log(newArray) //['a','b','d','e'] 175 | ``` 176 | 177 | **[⬆ Back to Top](#table-of-contents)** 178 | ### Did you know you can flat an array 179 | 180 | ```javascript 181 | const myArray = [2, 3, [4, 5],[7,7, [8, 9, [1, 1]]]]; 182 | 183 | myArray.flat() // [2, 3, 4, 5 ,7,7, [8, 9, [1, 1]]] 184 | 185 | myArray.flat(1) // [2, 3, 4, 5 ,7,7, [8, 9, [1, 1]]] 186 | 187 | myArray.flat(2) // [2, 3, 4, 5 ,7,7, 8, 9, [1, 1]] 188 | 189 | //if you dont know the depth of the array you can use infinity 190 | myArray.flat(infinity) // [2, 3, 4, 5 ,7,7, 8, 9, 1, 1]; 191 | 192 | ``` 193 | 194 | **[⬆ Back to Top](#table-of-contents)** 195 | ### Get unique values in an array 196 | 197 | ```javascript 198 | const numbers = [1,1,3,2,5,3,4,7,7,7,8]; 199 | 200 | //Ex1 201 | const unieqNumbers = numbers.filter((v,i,a) => a.indexOf(v )=== i ) 202 | console.log(unieqNumbers) //[1,3,2,5,4,7,8] 203 | 204 | //Ex2 205 | const unieqNumbers2 = Array.from(new Set(numbers)) 206 | console.log(unieqNumbers2) //[1,3,2,5,4,7,8] 207 | 208 | //Ex3 209 | const unieqNumbers3 = [...new Set(numbers)] 210 | console.log(unieqNumbers3) //[1,3,2,5,4,7,8] 211 | 212 | //EX4 lodash 213 | const unieqNumbers4 = _.uniq(numbers) 214 | console.log(unieqNumbers4) //[1,3,2,5,4,7,8] 215 | 216 | ``` 217 | 218 | **[⬆ Back to Top](#table-of-contents)** 219 | ### Copy Text to Clipboard 220 | 221 | 222 | ```javascript 223 | function copyToClipboard() { 224 | 225 | const copyText = document.getElementById("myInput"); 226 | copyText.select(); 227 | document.execCommand("copy"); 228 | 229 | } 230 | //new API 231 | function copyToClipboard(){ 232 | navigator.clipboard.writeText(document.querySelector('#myInput').value) 233 | } 234 | 235 | ``` 236 | 237 | **[⬆ Back to Top](#table-of-contents)** 238 | ### Nested Destructuring 239 | 240 | 241 | ```javascript 242 | const user = { 243 | id: 459, 244 | name: 'JS snippets', 245 | age:29, 246 | education:{ 247 | degree: 'Masters' 248 | } 249 | } 250 | 251 | const { education : { degree } } = user; 252 | console.log(degree) //Masters 253 | ``` 254 | 255 | **[⬆ Back to Top](#table-of-contents)** 256 | ### URLSearchParams 257 | 258 | 259 | ```javascript 260 | //The URLSearchParams interface defines utility methods to work with the query string of a URL. 261 | 262 | const urlParams = new URLSearchParams("?post=1234&action=edit"); 263 | 264 | console.log(urlParams.has('post')); // true 265 | console.log(urlParams.get('action')); // "edit" 266 | console.log(urlParams.getAll('action')); // ["edit"] 267 | console.log(urlParams.toString()); // "?post=1234&action=edit" 268 | console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1" 269 | ``` 270 | 271 | **[⬆ Back to Top](#table-of-contents)** 272 | ### Count elements in an array 273 | 274 | 275 | ```javascript 276 | const myFruits = ['Apple','Orange','Mango','Banana','Apple','Apple','Mango'] 277 | 278 | //first option 279 | const countMyFruits = myFruits.reduce((countFruits,fruit) => { 280 | countFruits[fruit] = ( countFruits[fruit] || 0 ) +1; 281 | return countFruits 282 | },{} ) 283 | console.log(countMyFruits) 284 | // { Apple:3, Banana:1, Mango:2, Orange:1 } 285 | 286 | //seconf option 287 | const fruitsCounter = {}; 288 | 289 | for( const fruit of myFruits ){ 290 | fruitsCounter[fruit] = fruitsCounter[fruit] ? fruitsCounter[fruit]+1 :1; 291 | } 292 | 293 | console.log(fruitsCounter) 294 | // { Apple:3, Banana:1, Mango:2, Orange:1 } 295 | ``` 296 | 297 | **[⬆ Back to Top](#table-of-contents)** 298 | ### Aliases with JavaScript Destructuring 299 | 300 | 301 | ```javascript 302 | 303 | //There are cases where you want the destructured variable to have a different name than the property name 304 | 305 | const obj = { 306 | name: "JSsnippets" 307 | }; 308 | 309 | 310 | // Grabs obj.name as { pageName } 311 | const { name: pageName } = obj; 312 | 313 | //log our alias 314 | console.log(pageName) // JSsnippets 315 | ``` 316 | 317 | 318 | **[⬆ Back to Top](#table-of-contents)** 319 | ### The Object.is() method determines whether two values are the same value 320 | 321 | 322 | ```javascript 323 | Object.is('foo', 'foo'); // true 324 | 325 | Object.is(null, null); // true 326 | 327 | Object.is(Nan, Nan); // true 😱 328 | 329 | const foo = { a: 1 }; 330 | const bar = { a: 1 }; 331 | Object.is(foo, foo); // true 332 | Object.is(foo, bar); // false 333 | 334 | ``` 335 | 336 | 337 | **[⬆ Back to Top](#table-of-contents)** 338 | ### Freeze an object 339 | 340 | 341 | ```javascript 342 | const obj = { 343 | name: "JSsnippets", 344 | age:29, 345 | address:{ 346 | street : 'JS' 347 | } 348 | }; 349 | 350 | const frozenObject = Object.freeze(obj); 351 | 352 | frozenObject.name = 'weLoveJS'; // Uncaught TypeError 353 | 354 | //Although, we still can change a property’s value if it’s an object: 355 | 356 | frozenObject.address.street = 'React'; // no error, new value is set 357 | 358 | 359 | delete frozenObject.name // Cannot delete property 'name' of # 360 | 361 | 362 | //We can check if an object is frozen by using 363 | Object.isFrozen(obj) //true 364 | 365 | ``` 366 | 367 | **[⬆ Back to Top](#table-of-contents)** 368 | ### Printing Object keys and values 369 | 370 | 371 | ```javascript 372 | const obj = { 373 | name: "JSsnippets", 374 | age:29, 375 | }; 376 | 377 | //Object.entries() method is used to return an array consisting of enumerable property 378 | //[key, value] pairs of the object which are passed as the parameter. 379 | 380 | for(let [key,value] of Object.entries(obj)){ 381 | console.log(`${key}: ${value}`) 382 | } 383 | 384 | //expected output: 385 | // "name: Jssnippets" 386 | // "age: 29" 387 | // order is not guaranteed 388 | 389 | ``` 390 | 391 | **[⬆ Back to Top](#table-of-contents)** 392 | ### Capture the right click event 393 | 394 | ```javascript 395 | window.oncontextmenu = () => { 396 | console.log('right click'); 397 | return false // cancel default menu 398 | } 399 | //or 400 | 401 | window.addEventListener('contextmenu', ()=>{ 402 | console.log('right click'); 403 | return false // cancel default menu 404 | },false) 405 | ``` 406 | 407 | **[⬆ Back to Top](#table-of-contents)** 408 | ### In HTML5, you can tell the browser when to run your JavaScript code 409 | ```javascript 410 | 411 | //Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag. 412 | 413 | 414 | //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. 415 | //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) 416 | 417 | 418 | //With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. 419 | 420 | ``` 421 | 422 | **[⬆ Back to Top](#table-of-contents)** 423 | ### Nullish coalescing operator 424 | ```javascript 425 | 426 | // 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. 427 | 428 | const foo = undefined ?? 'default string'; 429 | console.log(foo); 430 | // expected output: "default string" 431 | 432 | 433 | const age = 0 ?? 30; 434 | console.log(age); 435 | // expected output: "0" 436 | ``` 437 | 438 | **[⬆ Back to Top](#table-of-contents)** 439 | ### Optional chaining 440 | ```javascript 441 | 442 | const car = {} 443 | const carColor = car.name.color 444 | console.log(carColor); 445 | // error- "Uncaught TypeError: Cannot read property 'carColor' of undefined 446 | 447 | //In JavaScript, you can first check if an object exists, and then try to get one of its properties, like this: 448 | const carColor = car && car.name && car.name.color; 449 | console.log(carColor); 450 | //undefined- no error 451 | 452 | 453 | //Now this new optional chaining operator will let us be even more fancy: 454 | 455 | const newCarColor = car?.name?.color; 456 | console.log(newCarColor) 457 | //undefined- no error 458 | 459 | //You can use this syntax today using @babel/plugin-proposal-optional-chaining 460 | ``` 461 | 462 | **[⬆ Back to Top](#table-of-contents)** 463 | ### globalThis 464 | ```javascript 465 | Accessing the global property in JavaScript has always posed some difficulty. This is because 466 | different platforms have different ways to access it. 467 | 468 | Client-side JavaScript uses window or self 469 | 470 | Node.js uses global 471 | 472 | Web workers use self 473 | 474 | The 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. 475 | 476 | console.log(globalThis) //get the global this depends on your environment 477 | 478 | ``` 479 | 480 | 481 | **[⬆ Back to Top](#table-of-contents)** 482 | # The second argument of JSON.stringify lets you cherry-pick 🍒 keys to serialize. 483 | ```javascript 484 | const user = { 485 | id: 459, 486 | name: 'JS snippets', 487 | age:29, 488 | education:{ 489 | degree: 'Masters' 490 | } 491 | } 492 | 493 | JSON.stringify(user,[name,age], 2) 494 | 495 | /* 496 | returns 497 | 498 | { 499 | "name": "JS snippets", 500 | "age": 29 501 | } 502 | 503 | 504 | */ 505 | 506 | ``` 507 | 508 | **[⬆ Back to Top](#table-of-contents)** 509 | ### Fire an event listener only once 510 | ```javascript 511 | const el = document.getElementById("btn"); 512 | 513 | function myClickHandler(){ 514 | console.log('this click will only fire once') 515 | } 516 | 517 | 518 | el.addEventListener('click', myClickHandler, { 519 | once: true, 520 | }); 521 | 522 | ``` 523 | **[⬆ Back to Top](#table-of-contents)** 524 | ### Vanilla JS toggle 525 | ```javascript 526 | const span = document.querySelector("span"); 527 | let classes = span.classList; 528 | 529 | span.addEventListener("click", function() { 530 | let result = classes.toggle("active"); 531 | 532 | if (result) { 533 | console.log("active class was added"); 534 | } else { 535 | console.log("active class was removed"); 536 | } 537 | }); 538 | 539 | ``` 540 | 541 | **[⬆ Back to Top](#table-of-contents)** 542 | ### Check if a string is a valid JSON 543 | 544 | ```javascript 545 | function isJson(str) { 546 | try { 547 | JSON.parse(str); 548 | } catch (e) { 549 | //the json is not ok 550 | return false; 551 | } 552 | //the json is ok 553 | return true; 554 | } 555 | ``` 556 | **[⬆ Back to Top](#table-of-contents)** 557 | ### getBoundingClientRect 558 | 559 | ```javascript 560 | //getBoundingClientRect provides you with important pieces of data about an 561 | //HTML element’s size and positioning. 562 | 563 | const bodyBounderies = document.body.getBoundingClientRect(); 564 | // => { 565 | // top: Number, 566 | // left: Number, 567 | // right: Number, 568 | // bottom: Number, 569 | // x: Number, 570 | // y: Number, 571 | // width: Number, 572 | // height: Number, 573 | // } 574 | ``` 575 | 576 | **[⬆ Back to Top](#table-of-contents)** 577 | ### Check if a node is in the viewport 578 | bonus: add/remove animation depending if an image is in the viewport 579 | https://codepen.io/JSsnippets/pen/PoqrjEY 580 | ```javascript 581 | const image = document.querySelector('.animate-me'); 582 | 583 | observer = new IntersectionObserver((entries) => { 584 | const [ myImg ] = entries; 585 | if (myImg.intersectionRatio > 0) { 586 | myImg.target.classList.add('fancy'); 587 | } else { 588 | myImg.target.classList.remove('fancy'); 589 | } 590 | }); 591 | 592 | 593 | observer.observe(image); 594 | 595 | ``` 596 | 597 | **[⬆ Back to Top](#table-of-contents)** 598 | ### Notify when element size is changed 599 | see our codepen: https://codepen.io/JSsnippets/pen/dyYoYVX 600 | ```javascript 601 | const foo = document.getElementById("foo"); 602 | 603 | const observer = new ResizeObserver((entries) => { 604 | for (let entry of entries) { 605 | const cr = entry.contentRect; 606 | console.log = `Size: ${cr.width}px X ${cr.height}px`; 607 | } 608 | }); 609 | observer.observe(foo); 610 | 611 | ``` 612 | **[⬆ Back to Top](#table-of-contents)** 613 | ### Detect if Browser Tab is in the view 614 | play/pause video accordingly 615 | see our codepen: https://codepen.io/JSsnippets/pen/gOapPzq 616 | ```javascript 617 | 618 | 619 | const video = document.getElementById("my-video"); 620 | 621 | const onVisibilitychange =()=>{ 622 | return document.hidden 623 | ? video.pause() 624 | : video.play(); 625 | } 626 | 627 | document.addEventListener("visibilitychange", onVisibilitychange) 628 | 629 | ``` 630 | 631 | 632 | **[⬆ Back to Top](#table-of-contents)** 633 | ### Private class methods and fields 634 | ```javascript 635 | 636 | class Students { 637 | #name; 638 | 639 | constructor(){ 640 | this.#name = "JS snippets"; 641 | } 642 | 643 | #privateMethod() { 644 | return 'Come and learn Js with us'; 645 | } 646 | 647 | getPrivateMessage() { 648 | return this.#privateMethod(); 649 | } 650 | } 651 | 652 | const instance = new Something(); 653 | console.log(instance.name); //=> undefined 654 | console.log(instance.privateMethod); //=> undefined 655 | console.log(instance.getPrivateMessage()); //=> Come and learn Js with us 656 | 657 | ``` 658 | 659 | 660 | **[⬆ Back to Top](#table-of-contents)** 661 | ### Preventing paste into an input field 662 | see our codepen: https://codepen.io/JSsnippets/pen/qBbyMoJ 663 | 664 | ```javascript 665 | 666 | const pasteBox = document.getElementById("paste-no-event"); 667 | pasteBox.onpaste = (e) => { 668 | e.preventDefault(); 669 | return false; 670 | }; 671 | 672 | ``` 673 | 674 | 675 | **[⬆ Back to Top](#table-of-contents)** 676 | ### The void operator 677 | The void operator evaluates the given expression and then returns undefined. 678 | ```javascript 679 | 680 | 681 | void 0; //returns undefined 682 | void (0); //returns undefined 683 | void {}; //returns undefined 684 | void "JSsnippets; //returns undefined 685 | void (0); //returns undefined 686 | void (2 == '2'); //returns undefined 687 | void anyfunction(); //returns undefined 688 | 689 | ``` 690 | 691 | 692 | **[⬆ Back to Top](#table-of-contents)** 693 | ### replaceAll 694 | the method string.replaceAll(search, replaceWith) replaces all appearances of search string with replaceWith. 695 | ```javascript 696 | 697 | 698 | const str = 'this is a JSsnippets example'; 699 | 700 | const updatedStr = str.replace('example', 'snippet'); // 'this is a JSsnippets snippet' 701 | 702 | 703 | The tricky part is that replace method replaces only the very first match of the substring we have passed: 704 | 705 | 706 | const str = 'this is a JSsnippets example and examples are great'; 707 | 708 | const updatedStr = str.replace('example', 'snippet'); //'this is a JSsnippets snippet and examples are great' 709 | 710 | In order to go through this, we need to use a global regexp instead: 711 | 712 | 713 | const str = 'this is a JSsnippets example and examples are great'; 714 | 715 | const updatedStr = str.replace(/example/g, 'snippet'); //'this is a JSsnippets snippet and snippets are greatr' 716 | 717 | but now we have new friend in town, replaceAll 718 | 719 | const str = 'this is a JSsnippets example and examples are great'; 720 | 721 | const updatedStr = str.replaceAll('example', 'snippet'); //'this is a JSsnippets snippet and snippets are greatr' 722 | 723 | ``` 724 | 725 | 726 | **[⬆ Back to Top](#table-of-contents)** 727 | ### Required Function Params 728 | Expanding on the default parameter technique, we can mark a parameter as mandatory 729 | 730 | ```javascript 731 | const isRequired = () => { 732 | throw new Error( 'This is a mandatory parameter.' ); 733 | } 734 | 735 | 736 | const getPage = ( pageName = 'Jssnippets', url = isRequired() ) => { 737 | return `${pageName} ${url}`; 738 | } 739 | 740 | console.log(getPage()); 741 | 742 | //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, 743 | 744 | //Uncaught error: This is a mandatory parameter. 745 | //at isRequired 746 | 747 | ``` 748 | 749 | 750 | 751 | 752 | **[⬆ Back to Top](#table-of-contents)** 753 | ### Get input value as a number 754 | 755 | ```javascript 756 | 757 | 758 | 759 | function checkMyType(event){ 760 | 761 | console.log(typeof event.target.value) // string 762 | console.log(typeof event.target.valueAsNumber ) // number 763 | 764 | } 765 | 766 | 767 | ``` 768 | **[⬆ Back to Top](#table-of-contents)** 769 | ### reduceRight 770 | 771 | ```javascript 772 | 773 | const arr = ["a", "b", "c", "d", "e"] 774 | 775 | const reduceArray = arr.reduce((acc, current) => { 776 | return acc + current 777 | }, "") 778 | //return abcde 779 | 780 | const reduceRightArray = arr.reduceRight((acc, current) => { 781 | return acc + current 782 | }, "") 783 | //return edcba 784 | 785 | ``` 786 | 787 | 788 | **[⬆ Back to Top](#table-of-contents)** 789 | ### Abort Fetch 790 | 791 | ```javascript 792 | 793 | 794 | //HTML 795 | 796 | 797 | 798 | //JS 799 | let controller; 800 | 801 | document.querySelector('#download').addEventListener('click', () => { 802 | controller = new AbortController(); 803 | const signal = controller.signal; 804 | fetch('https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4', {signal}) 805 | .then(() => console.log('done')); 806 | }); 807 | 808 | document.querySelector('#abort').addEventListener('click', function() { 809 | controller.abort(); 810 | }); 811 | 812 | ``` 813 | 814 | 815 | **[⬆ Back to Top](#table-of-contents)** 816 | ### How to change the value of an object which is inside an array 817 | 818 | ```javascript 819 | 820 | const state = [ 821 | { 822 | userId: 1, 823 | name: "JSSnippets", 824 | isOwner: false, 825 | }, 826 | { 827 | userId: 2, 828 | name: "React", 829 | isOwner: false, 830 | }, 831 | { 832 | userId: 3, 833 | name: "Vue", 834 | isOwner: false, 835 | }, 836 | { 837 | userId: 4, 838 | name: "Angular", 839 | isOwner: false, 840 | }, 841 | ]; 842 | 843 | const newState = state.map((obj) => 844 | obj.name === "JSSnippets" ? { ...obj, isOwner: true } : obj 845 | ); 846 | 847 | ``` 848 | 849 | **[⬆ Back to Top](#table-of-contents)** 850 | ### Numeric separators allow us to improve our code readability 851 | 852 | ```javascript 853 | 854 | 100_000_000 === 100000000 // true 855 | 856 | 300_000 === 300000 //true 857 | 858 | ``` 859 | 860 | 861 | 862 | 863 | 864 | **[⬆ Back to Top](#table-of-contents)** 865 | ### pay attention when using every 866 | 867 | Calling this method on an empty array will return true for any condition! 868 | 869 | 870 | ```javascript 871 | 872 | const arr = [] 873 | const result = arr.every(x=> x==5) 874 | console.log(result) //true 875 | 876 | ``` 877 | 878 | 879 | 880 | 881 | 882 | **[⬆ Back to Top](#table-of-contents)** 883 | ### How to convert an array of key-value tuples into an object 884 | 885 | 886 | ```javascript 887 | 888 | const JSarr = [ 889 | ['name', 'JSsnippets'], 890 | ['address', 'worldwide'], 891 | ['year', '2018'], 892 | ['followers', '15000'] 893 | 894 | ]; 895 | 896 | const obj = Object.fromEntries(JSarr); 897 | //{ 898 | // "name": "JSsnippets", 899 | // "address": "worldwide", 900 | // "year": "2018", 901 | // "followers": "15000" 902 | //} 903 | ``` 904 | 905 | **[⬆ Back to Top](#table-of-contents)** 906 | ### Native text to speech JS 907 | 908 | 909 | ```javascript 910 | 911 | const startSpeaking=()=>{ 912 | 913 | let msg = document.getElementById("text-to-speech").value; 914 | let speech = new SpeechSynthesisUtterance(); 915 | 916 | speech.lang = "en-US"; 917 | speech.text = msg; 918 | speech.volume = 1; 919 | speech.rate = 1; 920 | speech.pitch = 1; 921 | 922 | window.speechSynthesis.speak(speech); 923 | } 924 | 925 | 926 | ``` 927 | 928 | **[⬆ Back to Top](#table-of-contents)** 929 | ### toFixed 930 | 931 | 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 . 932 | 933 | ```javascript 934 | 935 | 123.678.toFixed() // Returns '124' 936 | 123.678.toFixed(1) // Returns '123.7': Note rounding 937 | 938 | 2.35.toFixed(1) // Returns '2.4'. Note it rounds up 939 | 2.65.toFixed(1) // Returns '2.6'. Note it rounds down -why??? see the warning above 940 | 941 | ``` 942 | 943 | 944 | **[⬆ Back to Top](#table-of-contents)** 945 | ### generate random uuid 946 | 947 | The randomUUID() method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. 948 | 949 | ```javascript 950 | 951 | crypto.randomUUID() // print in console '460ff1e6-2106-4848-833d-5c5b3bfdc943' 952 | 953 | crypto.randomUUID() // print in console '9a91c014-d1b1-453a-8091-ef8b9b48b14a' 954 | 955 | 956 | ``` 957 | 958 | 959 | **[⬆ Back to Top](#table-of-contents)** 960 | ### structuredClone 961 | 962 | 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() 963 | 964 | ```javascript 965 | 966 | const user = { 967 | name: "JS Snippets", 968 | address: { street: "Original Road", city: "Placeshire" }, 969 | }; 970 | 971 | const clonedUser = structuredClone(user); 972 | 973 | clonedUser.address.street = "New Road"; 974 | 975 | console.log("user.address.street:", user.address.street); 976 | // > Original Road 977 | 978 | console.log("clonedUser.address.street:", clonedUser.address.street); 979 | // > New Road 980 | 981 | 982 | ``` 983 | 984 | **[⬆ Back to Top](#table-of-contents)** 985 | ### get device orientation 986 | 987 | Browsers expose a global variable named screen, which we’ll use to access the information we need. 988 | 989 | ```javascript 990 | 991 | function getOrientation() { 992 | const isPortrait = screen.orientation.type.startswith('portrait') 993 | return isPortrait ? 'portrait' : 'landscape' 994 | } 995 | 996 | ``` 997 | 998 | **[⬆ Back to Top](#table-of-contents)** 999 | ### CONST vs LET vs VAR 1000 | 1001 | | | const | Let | Var | 1002 | |------------------------|-------|-----|-----| 1003 | | Can be Reaasigned? | :x: | :white_check_mark: |:white_check_mark: | 1004 | | Cab be Redeclared? | :x: | :x: | :white_check_mark: | 1005 | | Block Scope | :white_check_mark: |:white_check_mark: | :x: | 1006 | | Function Scope | :white_check_mark: | :white_check_mark: | :white_check_mark: | 1007 | | Stored in Global Scope | :x: | :x: | :white_check_mark: | 1008 | --------------------------------------------------------------------------------