Today I will share some rare but useful JS techniques

Today I will share some rare but useful JS techniques

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:
  • JS uses map to integrate double arrays
  • 20 JavaScript tips to help you improve development efficiency
  • Summary of some tips for bypassing nodejs code execution
  • 7 tips for dealing with undefined JavaScript values
  • JS logic judgment should not only use if-else and switch condition judgment (tips)
  • 6 tips for writing better v-for loops in Vue.js

<<:  W3C Tutorial (16): Other W3C Activities

>>:  CSS achieves a proportional display effect of an element with fixed height and width

Recommend

Sample code for implementing follow ads with JavaScript

Floating ads are a very common form of advertisin...

Draw a heart with CSS3

Achieve resultsRequirements/Functionality: How to...

setup+ref+reactive implements vue3 responsiveness

Setup is used to write combined APIs. The interna...

Problems and solutions when installing and using VMware

The virtual machine is in use or cannot be connec...

Detailed explanation of the life cycle of Angular components (Part 2)

Table of contents 1. View hook 1. Things to note ...

JavaScript basics for loop and array

Table of contents Loop - for Basic use of for loo...

About if contains comma expression in JavaScript

Sometimes you will see English commas ",&quo...

Five practical tips for web form design

1. Mobile selection of form text input: In the te...