- vừa được xem lúc

Blog#93: 20 Useful JavaScript Tips for Improved Development Efficiency

0 0 20

Người đăng: NGUYỄN ANH TUẤN

Theo Viblo Asia

Hi, I'm Tuan, a Full-stack Web Developer from Tokyo 😊. Follow my blog to not miss out on useful and interesting articles in the future.

As a developer, you are always looking for ways to improve your skills and increase your efficiency. In this article, we will share 20 useful JavaScript tips that can help you do just that. From simple ways to improve readability to more advanced techniques, these tips are sure to come in handy in your projects.

1. Number Separator

When working with large numbers, it can be difficult to read and understand them at a glance. One simple way to improve their readability is to use underscores as separators.

const largeNumber = 1_000_000_000; console.log(largeNumber); // 1000000000

2. Event Listeners Run Only Once

Sometimes you may want to add an event listener to an element, but you only want it to run once. You can use the once option to accomplish this:

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

3. Console.log Variable Wrapper

When using console.log(), you can enclose the arguments in curly braces to see both the variable name and the variable value. This can be helpful for debugging and understanding your code better.

const name = "Maxwell";
console.log({ name });

4. Check That Caps Lock Is On

You can use the KeyboardEvent.getModifierState() method to detect if Caps Lock is on. This can be useful if you are working on a login form or other application where the case of letters matters.

const passwordInput = document.getElementById('password'); passwordInput.addEventListener('keyup', function (event) {
if (event.getModifierState('CapsLock')) {
// CapsLock is open
}
});

5. Get Min/Max Values from an Array

If you want to find the minimum or maximum value in an array, you can use the Math.min() or Math.max() functions in combination with the spread operator (...).

const numbers = [5, 7, 1, 4, 9]; console.log(Math.max(...numbers)); // 9
console.log(Math.min(...numbers)); // 1 

6. Get the Mouse Position

The clientX and clientY properties of the MouseEvent object can be used to get information about the coordinates of the current mouse position.

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

7. Copy to Clipboard

The Clipboard API can be used to create a "Copy to Clipboard" function. Here's an example of how to do it:

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

8. Shorten Conditional Judgment Statements

If you have a function that is only executed when a condition is true, you can use the && shorthand to write it more concisely. For example:

// Common writing method
if (condition) { doSomething();
} // Abbreviated
condition && doSomething();

9. Use Console.table() for Formatted Tables

The console.table() method can be used to print data in a table format in the console. The syntax is:

console.table(data [, columns]);

Here's an example of how to use it:

function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName;
} const p1 = new Person("Mark", "Smith");
const p2 = new Person("Maxwell", "Siegrist");
const p3 = new Person("Lucy", "Jones"); console.table([p1, p2, p3], ["firstName"]);

10. Convert Strings to Numbers

You can use the unary plus operator (+) to quickly convert a string to a number. For example:

const str = '508'; console.log(+str) // 508;

11. De-duplicate an Array

You can use the spread operator and the Set object to remove duplicates from an array. Here's an example:

const numbers = [2, 3, 5, 5, 2]; console.log([...new Set(numbers)]); // [2, 3, 5]

12. Filter Out Dummy Values from an Array

If you want to filter out dummy values (such as undefined, null, and NaN) from an array, you can use the filter() method. Here's an example:

const myArray = [1, undefined, NaN, 2, null, '@maxwell', true, false]; const filteredArray = myArray.filter(Boolean);
console.log(filteredArray); // [1, 2, '@maxwell', true, false]

13. Create a URL Query String

You can use the URLSearchParams object to create a URL query string from an object. Here's an example:

const queryObject = { page: 2, search: 'javascript'
}; const searchParams = new URLSearchParams(queryObject);
const queryString = searchParams.toString(); console.log(queryString); // "page=2&search=javascript"

14. Check if an Element Is in the Viewport

You can use the getBoundingClientRect() method and the window.innerWidth and window.innerHeight properties to check if an element is in the viewport. Here's an example:

function isInViewport(element) { const rect = element.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= window.innerHeight && rect.right <= window.innerWidth );
}

15. Create a Throttled Function

If you want to limit the rate at which a function is called, you can use the setTimeout() method to create a "throttled" function. Here's an example:

function throttle(callback, delay) { let timeout; return function() { const context = this; const args = arguments; if (!timeout) { timeout = setTimeout(function() { callback.apply(context, args); timeout = null; }, delay); } };
} const myThrottledFunc = throttle(function() { console.log('I am throttled');
}, 1000); myThrottledFunc(); // Will log "I am throttled"
myThrottledFunc(); // Will not log
setTimeout(myThrottledFunc, 1500); // Will log "I am throttled" after 1500ms

16. Use Array.includes() for Quick Membership Checking

The Array.includes() method can be used to quickly check if an element is in an array. It is more concise than using the indexOf() method. Here's an example:

const numbers = [1, 2, 3, 4, 5]; console.log(numbers.includes(3)); // true
console.log(numbers.includes(6)); // false

17. Use Array.find() to Get the First Matching Element

The Array.find() method can be used to get the first element in an array that matches a specific condition. Here's an example:

const numbers = [1, 2, 3, 4, 5]; const evenNumber = numbers.find(number => number % 2 === 0);
console.log(evenNumber); // 2

18. Use Object.values() to Get an Array of an Object's Values

The Object.values() method can be used to get an array of an object's values. This can be useful when you want to work with the values of an object in an array-like manner. Here's an example:

const person = { firstName: 'Maxwell', lastName: 'Siegrist', age: 30
}; console.log(Object.values(person)); // ['Maxwell', 'Siegrist', 30]

19. Use Array.reduce() to Sum Arrays

The Array.reduce() method can be used to reduce an array to a single value by applying a function to each element. Here's an example of how to use it to sum an array:

const myArray = [10, 20, 30, 40];
const reducer = (total, currentValue) => total + currentValue; console.log(myArray.reduce(reducer)); // 100

20. Access Element's Custom Data Attributes with the dataset Property

The dataset property can be used to access an element's custom data attributes (data-*). Here's an example:

<div id="user" data-name="Maxwell" data-age="32" data-something="Some Data"> Hello Maxwell
</div> <script> const user = document.getElementById('user'); console.log(user.dataset); // { name: "Maxwell", age: "32", something: "Some Data" } console.log(user.dataset.name); // "Maxwell" console.log(user.dataset.age); // "32" console.log(user.dataset.something); // "Some Data"
</script>

Conclusion

In this article, we covered 20 useful JavaScript tips that can help you improve your development efficiency. These tips included:

  1. Using underscores as separators to improve the readability of large numbers
  2. Adding event listeners that run only once
  3. Wrapping console.log arguments in curly braces to see both the variable name and value
  4. Using KeyboardEvent.getModifierState() to check if Caps Lock is on
  5. Using Math.min() and Math.max() with the spread operator to find the minimum or maximum value in an array
  6. Getting the mouse position with clientX and clientY properties of the MouseEvent object
  7. Copying to the clipboard with the Clipboard API
  8. Shortening conditional judgment statements with the && shorthand
  9. Printing tables in the console with console.table()
  10. Converting strings to numbers with the unary plus operator
  11. De-duplicating arrays with the spread operator and the Set object
  12. Filtering out dummy values from an array with the filter() method
  13. Creating a URL query string with the URLSearchParams object
  14. Checking if an element is in the viewport with getBoundingClientRect() and window.innerWidth andwindow.innerHeight
  15. Creating a throttled function with setTimeout()
  16. Using Array.includes() for quick membership checking
  17. Using Array.find() to get the first matching element in an array
  18. Using Object.values() to get an array of an object's values
  19. Using Array.reduce() to sum arrays
  20. Accessing an element's custom data attributes with the dataset property

I hope these tips will help you improve your development efficiency and take your skills to the next level. Happy coding!

As always, I hope you enjoyed this article and learned something new. Thank you and see you in the next articles!

If you liked this article, please give me a like and subscribe to support me. Thank you. 😊

Ref

Bình luận

Bài viết tương tự

- vừa được xem lúc

Giới thiệu Typescript - Sự khác nhau giữa Typescript và Javascript

Typescript là gì. TypeScript là một ngôn ngữ giúp cung cấp quy mô lớn hơn so với JavaScript.

0 0 500

- vừa được xem lúc

Bạn đã biết các tips này khi làm việc với chuỗi trong JavaScript chưa ?

Hi xin chào các bạn, tiếp tục chuỗi chủ đề về cái thằng JavaScript này, hôm nay mình sẽ giới thiệu cho các bạn một số thủ thuật hay ho khi làm việc với chuỗi trong JavaScript có thể bạn đã hoặc chưa từng dùng. Cụ thể như nào thì hãy cùng mình tìm hiểu trong bài viết này nhé (go).

0 0 414

- vừa được xem lúc

Một số phương thức với object trong Javascript

Trong Javascript có hỗ trợ các loại dữ liệu cơ bản là giống với hầu hết những ngôn ngữ lập trình khác. Bài viết này mình sẽ giới thiệu về Object và một số phương thức thường dùng với nó.

0 0 136

- vừa được xem lúc

Tìm hiểu về thư viện axios

Giới thiệu. Axios là gì? Axios là một thư viện HTTP Client dựa trên Promise.

0 0 117

- vừa được xem lúc

Imports và Exports trong JavaScript ES6

. Giới thiệu. ES6 cung cấp cho chúng ta import (nhập), export (xuất) các functions, biến từ module này sang module khác và sử dụng nó trong các file khác.

0 0 93

- vừa được xem lúc

Bài toán đọc số thành chữ (phần 2) - Hoàn chỉnh chương trình dưới 100 dòng code

Tiếp tục bài viết còn dang dở ở phần trước Phân tích bài toán đọc số thành chữ (phần 1) - Phân tích đề và những mảnh ghép đầu tiên. Bạn nào chưa đọc thì có thể xem ở link trên trước nhé.

0 0 229