Super useful JavaScript tips
Dima Prohorenko
Posted on March 8, 2021
Here is a list of useful tricks for JavaScript developers that will definitely help you one day.
Removing Falsy Values From Arrays
Falsy values are values in JavaScript which evaluate to FALSE. There are only six falsy values in JavaScript and they are:
- undefined
- null
- NaN
- '' (empty string)
- 0
- false The easiest way to filter out these falsy values is to use the below function.
array.filter(Boolean);
Keep in mind that filter returns new array and does not modify the original array.
The difference between target and currentTarget in the event context.
target
refers to the DOM element that triggers an event. Otherwise, currentTarget
refers to the DOM element that the event listener is listening on.
<ul class="list">
<li class="list__item">Study JavaScript</li>
</ul>
const list = document.querySelector('.list');
list.addEventListener('click', (e) => {
console.log(e.target);
// Output: "<li class='list__item'>Study JavaScript</li>"
console.log(e.currentTarget);
// Output: "<ul class="list"><li class="list__item">Study JavaScript</li></ul>
});
Copy to Clipboard
Itβs easy, the bad thing is that we must add an with the text to be copied to the DOM. Then, we selected the content and execute the copy command with execCommand. execCommand('copy') will copy the actual selected content.
<input type="text">
<button>Copy to Clipboard</button>
button.addEventListener('click', () => {
input.select();
document.execCommand('copy');
});
Or if you don't want to use input, there's a way to copy content from div, span, p
.
<p>Some text to copy</p>
<button>Copy to Clipboard</button>
function copyToClipboard (el) {
const r = document.createRange();
r.selectNode(el);
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
document.execCommand('copy');
window.getSelection().removeAllRanges();
}
button.addEventListener('click', () => {
copyToClipboard(paragraph);
});
Truncate an Array
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array.length = 4;
console.log(array); // Result: [0, 1, 2, 3]
That's it for today. Hope you learned something new:)
Posted on March 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 18, 2023