Member-only story
15 Useful JavaScript Tips
15 useful JavaScript tips to improve your development efficiency

This article collects some common JavaScript Tips from around the web. I have used all of these tips in my projects and recommend them today.
1. Number separator
To improve the readability of numbers, you can use underscores as separators.
const largeNumber = 1_000_000_000;
console.log(largeNumber); // 1000000000
2. Event listeners run only once
If you want to add an event listener and run it only once, you can use the once option.
element.addEventListener('click', () => console.log('I run only once'), {
once: true
});
3. console.log Variable wrapper
In console.log()
, enclose the arguments in curly braces so that you can see both the variable name and the variable value.
const name = "Maxwell";
console.log({ name });
4. Check that 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 open
}
});
5. Get min/max values from an array
You can use Math.min()
or Math.max()
in combination with the extension operator to find the minimum or maximum value in an array.
const numbers = [5, 7, 1, 4, 9];
console.log(Math.max(...numbers)); // 9
console.log(Math.min(...numbers)); // 1
6. Get the mouse position
You can use the values of the clientX
and clientY
properties of the MouseEvent
object 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}`);
});