A few rare but useful JS tricks

1. "Back" button

history.back()A browser back button can be created using

<button onclick="history.back()">
    返回
</button>  

2. Number separator

To improve the readability of numbers, use underscores as separators

const largeNumber = 1_000_000_000;

console.log(largeNumber); // 1000000000

3. The event listener only runs once

To add an event listener and only run it once, use oncethe option

element.addEventListener('click', () => console.log('I run only once'), {
    
    
    once: true
}); 

4. console.logVariable packaging

console.log()When , enclose the parameters in curly braces, so that you can see the variable name and variable value at the same time

const myNumber = 123

console.log({
    
    myNumber})  //{myNumber: 123}

5. Get the min/max value from the array

Math.min()or Math.max()combined 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 Caps Lockwhether the (uppercase and lowercase letter conversion key) is turned on

KeyboardEvent.getModifierState()to check Caps Lockif it is open

const passwordInput = document.getElementById('password');

passwordInput.addEventListener('keyup', function (event) {
    
    
    if (event.getModifierState('CapsLock')) {
    
    
        // CapsLock 已经打开了
    }
}); 

7. Copy to clipboard

Clipboard APICreate a "copy to clipboard" function

function copyToClipboard(text) {
    
    
    navigator.clipboard.writeText(text);
}

8. Get the mouse position

MouseEventThe attribute values ​​of clientXand under the object to obtain the coordinate information of the current position of the mouseclientY

document.addEventListener('mousemove', (e) => {
    
    
    console.log(`Mouse X: ${
      
      e.clientX}, Mouse Y: ${
      
      e.clientY}`);
}); 

9. Shorten the array

Set lengththe property to shorten the array

const numbers = [1, 2, 3, 4, 5]

numbers.length = 3;

console.log(numbers); // [1, 2, 3]

10. Shorthand conditional judgment statement

Execute the function only truewhen , use &&the abbreviation

// 普通写法
if (condition) {
    
    
    doSomething();
}

// 简写
condition && doSomething(); 

11. console.table()Print a form in a specific format

grammar:

// [] 里面指的是可选参数
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

Example:

// 一个对象数组,只打印 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"]);

Print result:Print table type data

12. Array deduplication

const numbers = [2, 3, 4, 4, 2];

console.log([...new Set(numbers)]); // [2, 3, 4]  

13. Convert string to number

const str = '404';

console.log(+str) // 404; 

14. Convert numbers to strings

concatenate empty string

const myNumber = 403;

console.log(myNumber + ''); // '403'  

15. Filter all false values ​​​​from the array

const myArray = [1, undefined, NaN, 2, null, '@denicmarko', true, 3, false];

console.log(myArray.filter(Boolean)); // [1, 2, "@denicmarko", true, 3]  

16. Magical useincludes

const myTech = 'JavaScript';
const techs = ['HTML', 'CSS', 'JavaScript'];

// 普通写法
if (myTech === 'HTML' || myTech === 'CSS' || myTech === 'JavaScript') {
    
    
    // do something
}

// includes 写法
if (techs.includes(myTech)) {
    
    
    // do something 
} 

17. Use reduceto 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

Style the output CSS 语句in usingDevToolsconsole.log

console.log('%c success', 'color: green;font-size: 1.5rem');
console.log('%c 11111', 'color: green;font-size: 1.5rem');
console.log('%c waring', 'color: orange;font-size: 2rem');
console.log('%c Error', 'color: red; font-size: 3rem');

Set the output style

19. Elementaldataset

datasetAttributes to access custom data attributes for elements(data-*)

<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>   

20. Concurrency, avoid callbacks

Callbacks are messy and can lead to deep code nesting. Use Promise instead of callbacks.

// Don't ❌
getUser(function (err, user) {
    
    
  getProfile(user, function (err, profile) {
    
    
    getAccount(profile, function (err, account) {
    
    
      getReports(account, function (err, reports) {
    
    
        sendStatistics(reports, function (err) {
    
    
          console.error(err);
        });
      });
    });
  });
});

// Do ✅
getUser()
  .then(getProfile)
  .then(getAccount)
  .then(getReports)
  .then(sendStatistics)
  .catch((err) => console.error(err));

// or using Async/Await ✅✅

async function sendUserStatistics() {
    
    
  try {
    
    
    const user = await getUser();
    const profile = await getProfile(user);
    const account = await getAccount(profile);
    const reports = await getReports(account);
    return sendStatistics(reports);
  } catch (e) {
    
    
    console.error(err);
  }
}

21. Prefer map instead of switch statement

Reduce complexity and improve performance

// Don't ❌
const getColorByStatus = (status) => {
    
    
  switch (status) {
    
    
    case "success":
      return "green";
    case "failure":
      return "red";
    case "warning":
      return "yellow";
    case "loading":
    default:
      return "blue";
  }
};

// Do ✅
const statusColors = {
    
    
  success: "green",
  failure: "red",
  warning: "yellow",
  loading: "blue",
};

const getColorByStatus = (status) => statusColors[status] || "blue";

22. Use optional links

const user = {
    
    
  email: "[email protected]",
  billing: {
    
    
    iban: "...",
    swift: "...",
    address: {
    
    
      street: "Some Street Name",
      state: "CA",
    },
  },
};

// Don't ❌
const email = (user && user.email) || "N/A";
const street =
  (user &&
    user.billing &&
    user.billing.address &&
    user.billing.address.street) ||
  "N/A";
const state =
  (user &&
    user.billing &&
    user.billing.address &&
    user.billing.address.state) ||
  "N/A";

// Do ✅
const email = user?.email ?? "N/A";
const street = user?.billing?.address?.street ?? "N/A";
const street = user?.billing?.address?.state ?? "N/A";

23. Use shorthand wherever possible

// Don't ❌
if (isActive === true) {
    
    
  // ...
}

if (firstName !== "" && firstName !== null && firstName !== undefined) {
    
    
  // ...
}

const isUserEligible = user.isVerified() && user.didSubscribe() ? true : false;

// Do ✅
if (isActive) {
    
    
  // ...
}

if (!!firstName) {
    
    
  // ...
}

const isUserEligible = user.isVerified() && user.didSubscribe();

24. Avoid too many branches

Returning early makes your code linear, more readable and less complex

// Don't ❌
function addUserService(db, user) {
    
    
  if (!db) {
    
    
    if (!db.isConnected()) {
    
    
      if (!user) {
    
    
        return db.insert("users", user);
      } else {
    
    
        throw new Error("No user");
      }
    } else {
    
    
      throw new Error("No database connection");
    }
  } else {
    
    
    throw new Error("No database");
  }
}

// Do ✅
function addUserService(db, user) {
    
    
  if (!db) throw new Error("No database");
  if (!db.isConnected()) throw new Error("No database connection");
  if (!user) throw new Error("No user");

  return db.insert("users", user);
}

25. When passing a mutable value to a function, you should clone a new value and return it instead of changing it directly

// Don't ❌
function enrollStudentInCourse(course, student) {
    
    
  course.push({
    
     student, enrollmentDate: Date.now() });
}

// Do ✅
function enrollStudentInCourse(course, student) {
    
    
  return [...course, {
    
     student, enrollmentDate: Date.now() }];
}

26. Limit the number of parameters

// Don't ❌
function sendPushNotification(title, message, image, isSilent, delayMs) {
    
    
  // ...
}

sendPushNotification("New Message", "...", "http://...", false, 1000);

// Do ✅
function sendPushNotification({
     
      title, message, image, isSilent, delayMs }) {
    
    
  // ...
}

const notificationConfig = {
    
    
  title: "New Message",
  message: "...",
  image: "http://...",
  isSilent: false,
  delayMs: 1000,
};

sendPushNotification(notificationConfig);

27. Use default parameters

Default arguments are cleaner than && || or using extra conditional statements inside the function body


// Don't ❌
function printAllFilesInDirectory(dir) {
    
    
  const directory = dir || "./";
  //   ...
}

// Do ✅
function printAllFilesInDirectory(dir = "./") {
    
    
  // ...
}

Guess you like

Origin blog.csdn.net/qiaoqiaohong/article/details/121007694