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

Complete Tutorial on Deploying Java Web Project on Linux Server

Most of this article refers to other tutorials on...

Detailed explanation of the implementation of nginx process lock

Table of contents 1. The role of nginx process lo...

Analyze the difference between computed and watch in Vue

Table of contents 1. Introduction to computed 1.1...

JavaScript implementation of a simple addition calculator

This article example shares the specific code of ...

Design and implementation of Vue cascading drop-down box

Table of contents 1. Database design 2. Front-end...

mysql 8.0.19 win10 quick installation tutorial

This tutorial shares the installation tutorial of...

Vue implements 3 ways to switch tabs and switch to maintain data status

3 ways to implement tab switching in Vue 1. v-sho...

Detailed explanation of CSS elastic box flex-grow, flex-shrink, flex-basis

The functions of the three attributes flex-grow, ...

Detailed process analysis of docker deployment of snail cinema system

Environmental Statement Host OS: Cetnos7.9 Minimu...

js uses the reduce method to make your code more elegant

Preface In actual projects, the most common proce...