1. Back button Use history.back() to create a browser "back" button. <button onclick="history.back()"> Return</button> 2. Number separator To improve readability of numbers, you can use underscores as separators: const largeNumber = 1_000_000_000; console.log(largeNumber); // 1000000000 3. Event listeners only run once If you want to add an event listener and run it only once, you may use the once option: element.addEventListener('click', () => console.log('I run only once'), { once: true }); 4. console.log variable wrapper When you console.log(), enclose the parameters in curly braces so that you can see both the variable name and the variable value. 5. Get the minimum/maximum value from an array You can use Math.min() or Math.max() with the spread operator to find the minimum or maximum value in an array. const numbers = [6, 8, 1, 3, 9]; console.log(Math.max(...numbers)); // 9 console.log(Math.min(...numbers)); // 1 6. Check if Caps Lock is on You can use KeyboardEvent.getModifierState() to detect if Caps Lock is on. const passwordInput = document.getElementById('password'); passwordInput.addEventListener('keyup', function (event) { if (event.getModifierState('CapsLock')) { // CapsLock is already on } }); 7. Copy to clipboard You can use the Clipboard API to create a "copy to clipboard" functionality: function copyToClipboard(text) { navigator.clipboard.writeText(text); } 8. Get the mouse position You can use the clientX and clientY properties of the MouseEvent object to obtain the current coordinate information of the mouse position. document.addEventListener('mousemove', (e) => { console.log(`Mouse X: ${e.clientX}, Mouse Y: ${e.clientY}`); }); 9. Shorten the array You can set the length property to shorten the array. const numbers = [1, 2, 3, 4, 5] numbers.length = 3; console.log(numbers); // [1, 2, 3] 10. Abbreviated conditional statements If you want to execute a function only if a condition is true, you can use the && shorthand. // Normal writing if (condition) { doSomething(); } // Shorthand condition && doSomething(); 11. console.table() prints a table in a specific format grammar: // [] refers to the optional parameters console.table(data [, columns]); parameter: data indicates the data to be displayed. Must be an array or object. columns represents an array containing the names of the columns. Examples: // An array of objects, only print firstName function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } const john = new Person("John", "Smith"); const jane = new Person("Jane", "Doe"); const emily = new Person("Emily", "Jones"); console.table([john, jane, emily], ["firstName"]); The print result is as follows: 12. Array deduplication const numbers = [2, 3, 4, 4, 2]; console.log([...new Set(numbers)]); // [2, 3, 4] 13. Convert a string to a number const str = '404'; console.log(+str) // 404; 14. Convert a number to a string Concatenates an empty string. const myNumber = 403; console.log(myNumber + ''); // '403' 15. Filter all false values from an array const myArray = [1, undefined, NaN, 2, null, '@denicmarko', true, 3, false]; console.log(myArray.filter(Boolean)); // [1, 2, "@denicmarko", true, 3] 16. Use includes const myTech = 'JavaScript'; const techs = ['HTML', 'CSS', 'JavaScript']; // Normal writing if (myTech === 'HTML' || myTech === 'CSS' || myTech === 'JavaScript') { // do something } // includes syntax if (techs.includes(myTech)) { // do something } 17. Use reduce to sum an array const myArray = [10, 20, 30, 40]; const reducer = (total, currentValue) => total + currentValue; console.log(myArray.reduce(reducer)); // 100 18. console.log() Style Did you know that you can style console.log output in DevTools using CSS statements: 19. Element dataset Use the dataset attribute to access custom data attributes ( data-* ) of an element: <div id="user" data-name="John Doe" data-age="29" data-something="Some Data"> John Doe </div> <script> const user = document.getElementById('user'); console.log(user.dataset); // { name: "John Doe", age: "29", something: "Some Data" } console.log(user.dataset.name); // "John Doe" console.log(user.dataset.age); // "29" console.log(user.dataset.something); // "Some Data" </script> This concludes the article about sharing some rare but very useful JS tips today. For more relevant JS tips, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: W3C Tutorial (16): Other W3C Activities
>>: CSS achieves a proportional display effect of an element with fixed height and width
MySQL is a relatively easy-to-use relational data...
illustrate This article was written on 2017-05-20...
Generally speaking, in order to get more complete...
I recently deployed Django and didn't want to...
The development of Docker technology provides a m...
Table of contents 1. Definition and call of const...
Preface Excel is powerful and widely used. With t...
1. Check the character set 1. Check the MYSQL dat...
A: Usually stored in the client. jwt, or JSON Web...
Rendering If you want to achieve the effect shown...
CSS Sprite, also known as CSS Sprite, is an image...
This is the style recommendation given by the W3C ...
Table of contents 1. Introduction to autofs servi...
The previous article introduced several methods f...
1. Check BIOS First check which startup mode your...